String counts python with a function and input - python

I have this task:
Create a program that counts and displays in the terminal the number of characters of the following words. The program must contain at least one function.
This is what i created:
value = input("Write your word here:")
def word(value):
word = 0
for i in len(int(value)):
print(value)
How i solve the task?

your code has to be edited. As you are beginner I added some explanation for you.
As you are beginner you can check some Python-tutorial to learn Python.
# write your function, which will iterate over the value
# and print each character
def word(value):
for i in range(len(value)): # range, instead of len(value), int values are not iterable
print(value[i]) # print the i-th value
# you can directly iterate on value which is a string
for c in value:
print(c)
value = input("Write your word here:")
word(value)

Related

How do I apply this string length function to a column in my dataframe?

I have written a function that returns the length of a string,
def string_length():
string = input("Please enter a string: ")
"""This prompts the user to enter a string"""
return(len(string))
I have a dataset called film which has a column titled Phrase. I want to add a new column to my dataset which applies my function to the Phrase column and inputs the string length for each value in the phrase.
I tried using the following code:
film['Phrase length']=film['Phrase'].apply(string_length)
However, this returns an error:
TypeError: string_length() takes 0 positional arguments but 1 was given
What do I need to do to fix this code?
I'm sure I'm missing something very silly but I'm still quite new to python!
The function prompts the user for some input. This won't work if you apply it to a dataframe. You can however apply the built-in len() function:
film['Phrase length'] = film.Phrase.apply(len)
If I understand your question correctly then you must be looking for this:
def string_length(str):
x = len(str)
return x
df['Phrase length'] = df['Phrase'].apply(lambda x: string_length(x))
or,
df['Phrase length'] = df['Phrase'].map(string_length)
UPDATE:
If you want to use input() to enter the column name of your choice then use the following:
def string_length(data):
print("Please enter column name:")
a = input()
data[a+'_len'] = data[a].astype(str).apply(lambda x: len(x))
followed by:
string_length(df)
Enter the column name of your choice and then try printing the dataframe.

Python Dictionaries with lists from user input how to solve this?

Write a program that ask the user to enter an integer representing the number of items to be added to the stock. For these items, the program should then ask for the item barcode number and name, add them to a dictionary and print them.
Why is my code not working as expected?
size=input("Enter size of list")
names=[input()]
code=[int(input())]
for i in size:
print("Enter name and code")
names.append(input())
code.append(int(input()))
dict={names[i]:code[i]}
print(dict)
This a functioning version of your code:
size = input("Enter size of list")
names = []
code = []
for i in range(int(size)):
print("Enter name and code")
names.append(input())
code.append(int(input()))
d = dict(zip(names, code))
print(d)
Among the errors that needed fixing:
Only use input() in your for loop when you need the data.
i needs to cycle through range(int(size)) rather than a string input.
Create the dictionary from your lists at the end via zip.
Do not name variables after classes, e.g. use d instead of dict.

Why is my program only appending every other input into my list?

I am attempting to create a python program that takes multiple lines from the user and adds them to a list. Inputting a blank line ends the program and returns the list. However only every other line is being added to the list. If anyone could help that would be great.
def read_lines():
lines = []
contin = True
while contin:
if len(input()) == 0:
contin = False
else:
lines.append(input())
return(lines)
There is my code here is what is happening:
>>> read_lines()
abc
def
ghi
jkl
['def', 'jkl']
Because you call it twice for each iteration. You call it once for the len check, and once for the append. Each time, it extracts a new string from the command line. Consider calling it once and storing the result in a variable, at the top of your loop. Then do your len and append operations on that stored result.
The first time you call input with the if statement, it will get the input from the user. Suppose you enter a valid string, then the length will not be zero and the if block will not be executed. So, you go to else block where you again get a new input from the user; This discards the previous input that you got since you did not store it in any variable. Thus, for each valid input you give only the alternate elements are appended to the list.
Your code will append all the input you enter into the list when you alternately press enter key and a valid input in the same order.
I have added the correct code here:
def read_lines():
lines = []
contin = True
while contin:
string = input()
if len(string) == 0:
contin = False
else:
lines.append(string)
return(lines)

How to compare array entries to dictionary keys and return a dictionary value

I am trying to make a python program that takes user input text or a file and changes each character into a value and then returns the result.
I have a user string that being read into a list.
I am trying to have a for loop go through that list and check each character against a dictionary key and then return the value in the dictionary. How would i go about doing that?
Thanks
Code so far:
for i in range (0, len(text)):
for j in alphabet.keys():
if text[i].upper() == alphabet.values():
j+=1
print(alphabet.items())
i+=1
for item in list_:
try:
print(d[item])
except KeyError as e:
print("{} not in d".format(e.args[0]))
Without seeing your code, I can't offer anything more relevant
You probably want to use string.maketrans and string.translate
>>> import string
>>> table = string.maketrans('abc', 'xyz')
>>> string.translate('the cat is bad', table)
'the zxt is yxd'
Most of the code below is simply to create the dictionary that translates letters of an input into randomised corresponding values in a dict (i.e. each letter maps to another random letter). Points on your code:
1) range() automatically defaults to starting at 0 so range(0, n) is better just written as range(n)
2) You don't need to use range() at all here. for letter in string will take an input string and go through it, letter by letter. for elephant in string will do the same, each letter is being assigned to the name elephant in turn, so the fact that I chose to use letter instead is simply for readability.
3) Using keys(), values() and items() is not the way to query a dictionary. You have two standard approaches; I could use translation_dict[letter] which will throw KeyError if the value of letter is not a key in the dictionary, or translation_dict.get(letter) which will return None if the key doesn't exist. In the below example, I used get() but also added another parameter ("not in dict") which replaces None as the default value if the letter isn't found as a key.
import string # For setup of example data
import random # For setup of example data
# Just creating the translation dictionary and fake user input
alphabet = list(string.uppercase)
translated = random.sample(alphabet, len(alphabet))
translation_dict = {i: j for i, j in zip(alphabet, translated)}
user_input = 'Hello'
# The loop you're trying
for letter in user_input:
corresponding_value = translation_dict.get(letter.upper(), 'Not in dict')
print(corresponding_value)

How to iteratively replace list items with dictionary values in python?

I'm trying to create an encoding/decoding function which takes an input string and switches each letter to the corresponding value in the dictionary Key by matching letter to a key.It's basically a ROT-13 cipher.
def Encode_Decode(A):
A=list(A)
for n in range(0,len(A),+1):
if A[n]==Key.keys:
map(Key.values(),A[n])
print("This translates to: "+"".join(A))
Encode_Decode("Hello there")
I use a dictionary which assigns a key value in the alphabet to a letter 13 letters up
Key= {'a':'n','b':'o','c':'p','d':'q','e':'r','f':'s',
'g':'t','h':'u','i':'v',
'j':'w','k':'x','l':'y','m':'z','n':'a',
'o':'b','p':'c','q':'d','r':'e'
,'s':'f','t':'g','u':'h','v':'i','w':'j',
'x':'k','y':'l','z':'m','A':'N',
'B':'O','C':'P','D':'Q','E':'R','F':'S',
'G':'T','H':'U','I':'V','J':'W',
'K':'X','L':'Y','M':'Z','N':'A','O':'B',
'P':'C','Q':'D','R':'E','S':'F',
'T':'G','U':'H','V':'I','W':'J',
'X':'K','Y':'L','Z':'M'}
Can anyone tell me why my function doesn't return a translated sentence?
This is not the only problem, but ... I think you want:
if A[n] in Key:
instead of
if A[n]==Key.keys:
Key is a confusing name for a dict, by the way.
I know this is merely a comment, not a complete answer, but I don't know how to format comments :)
If all possible characters were in Key, you could just write this:
def Encode_Decode(A):
A = map(Key.get, A)
print("This translates to: "+"".join(A))
However, in your test string, there is a space, and Key.get(' ') returns None. "".join(A) will fail if there is a None in the sequence
You can fix that by passing a default argument to Key.get
def Encode_Decode(A):
A = (Key.get(x, x) for x in A)
print("This translates to: "+"".join(A))
Key.get(x, x) means if x isn't in the dictionary, just use x instead, so spaces and other characters will be unchanged

Categories

Resources