Hello everyone I have a question regarding a parsing of string and this is the code I have so far:
sentence =' '
while sentence != 'q':
sentence = input('Please enter your input: ').split(',')
if len(sentence) > 1:
print('First word: {sentence[0]}')
print('Second word: {sentence[1]}')
continue
elif len(sentence) == 1:
print('Error no comma.')
continue
elif sentence == 'q':
break
And the output will be if there is no comma inputted will give me the following:
Enter input string:
Jill Allen
Error: No comma in string.
and it will keep on asking me for a string until I entered q for quit and the program exits as follows:
Enter input string:
Jill, Allen
First word: Jill
Second word: Allen
Enter input string:
Golden , Monkey
First word: Golden
Second word: Monkey
Enter input string:
Washington,DC
First word: Washington
Second word: DC
Enter input string:
q
My problem is I am unable to quit the infinite loop. Can anyone help me on this? I think the program is unable to distinguish 'Jill Allen' from 'q' since both of them have len(sentence) == 1 and that is the problem as it gives me Error no comma and asked for an input over and over.
I think the key to understanding your problem may be here:
sentence = input('Please enter your input: ').split(',')
You are storing the user input in a string, but then you are calling the string method str.split(). This method basically returns a list of sub-strings, based on the separator you pass as an argument. If there is no separator, the method will instead create a list whose only element is the original input string.
You can find more information about this method here: https://docs.python.org/3/library/stdtypes.html#str.split.
So, if your input is "q", separator will be storing the array ["q"], as there is no comma. And this array's length is 1, so it will enter the first "elif", and execute the "continue", therefore ending current iteration.
In absence of further information about your project, if you need to do it this way, you can change the order of the last two conditionals and the break conditional itself in order for it to work:
sentence =' '
while True:
sentence = input('Please enter your input: ').split(',')
if len(sentence) > 1:
print(f'First word: {sentence[0]}')
print(f'Second word: {sentence[1]}')
continue
elif sentence[0] == 'q':
break
elif len(sentence) == 1:
print('Error no comma.')
continue
I also changed the while condition, because it was redundant with the "break" statement.
You have to change the places of the last two if statements. Because the last if statement never gets executed as if you split sentence which is just q, its length is 1.
sentence =' '
while sentence != 'q':
sentence = input('Please enter your input: ').split(',')
if len(sentence) > 1:
print('First word: {sentence[0]}')
print('Second word: {sentence[1]}')
continue
elif sentence == 'q':
break
elif len(sentence) == 1:
print('Error no comma.')
continue
Check this code. It's working fine for me.
def wordPrinter(text):
if len(sentence) > 1:
print(f'First word: {sentence[0]}')
print(f'Second word: {sentence[1]}')
elif len(sentence) == 1:
print('Error no comma.')
while True:
sentence = input('Please enter your input: ').split(',')
if sentence == ["q"]:
break
else:
wordPrinter(sentence)
As you splitting the input from very beginning you have to compare string by list element.
Code:
sentence =' '
while True:
sentence = input('Please enter your input: ').split(',') #['q']
if len(sentence) > 1:
print(f'First word: {sentence[0]}')
print(f'Second word: {sentence[1]}')
continue
elif sentence == ['q']:
break
else:
print('Error no comma.')
continue
while (sentence := input('Please enter your input: ')) != 'q':
first, *rest = sentence.split(',')
if rest:
print(f'First word: {first}')
second, *rest = rest
print(f'Second word: {second}')
if rest:
print(f'Rest: {",".join(rest)}')
else:
print('Error no comma.')
You can use Python 3.8's walrus operator to assign the input to a variable and also check it's value. I then used iterable unpacking to get the first element of the str.split and the rest as a list. Checking a list itself in a condition tells you if it has any elements in it. I did the same for the second word. Additionally I'm also printing the rest of the words if there are any.
when you use split() you will take list, so sentence cant be str('q')
try like this:
sentence=' '
while True:
sentence = input().split(',')
if (len(sentence) == 1)&(sentence[0] == 'q'):
break
elif len(sentence)<=1:
print('error')
else:
print(f'First word: {sentence[0]}')
print(f'Second word: {sentence[1]}')
I'm trying to make a Python program which takes in a string and evaluates whether it's a palindrome (reads the same backwards) or not. I've tried to extend it by not allowing numbers to come as an input, and that part works fine.
a = eval(input('Put a word here: '))
if type(a) == int or float:
print('That\'s a number man.')
exit()
b = a[::-1]
if a == b:
print('The word is a palindrome!')
else:
print('The word is not a palindrome!')
However, when I run the program with a random word, such as 'fries', as an input in cmd (using Windows, Python 3.9.2), I get this error:
Traceback (most recent call last):
File "C:\Users\Azelide\Desktop\folderr\hello.py", line 1, in <module>
a = eval(input('Put a word here: '))
File "<string>", line 1, in <module>
NameError: name 'fries' is not defined
I've seen people getting this error when running Python 2 and using input() instead of raw_input(), that should not be a problem in Python 3 though. By the way, when I omit the part of the code which excludes numbers from the input, the palindrome checker works fine. Any ideas?
As mentioned in the comments, your first condition always evaluates to true
try this:
a = input('Put a word here: ')
for char in a:
if char.isdigit():
print('That\'s a number man.')
exit()
b = a[::-1]
if a == b:
print('The word is a palindrome!')
else:
print('The word is not a palindrome!')
output:
Put a word here: fries
The word is not a palindrome!
I have managed to solve it now, while extending it to not allow number-letter combinations.
a = input('Put a word here: ')
try:
float(a)
print('That\'s a number man.')
exit()
except ValueError:
for char in a:
if char.isdigit():
print('That\'s a combination of letters and numbers.')
exit()
b = a[::-1]
if a == b:
print('The word is a palindrome!')
else:
print('The word is not a palindrome!')
I will tell you what is wrong in your code the function eval takes a string so that if the string could be a function it will make the function else it will raise error and when you made the function input inside it, this returns a value if this value == a function then make the function else raise error like this
a = eval(input('enter a name: '))
now if the user enters a value which can not be a function it will raise error like this
name'value that the user input' is not defined
now you can make as what the people said up
a = input('Put a word here: ')
try:
float(a)
print('That\'s a number man.')
exit()
except ValueError:
for char in a:
if char.isdigit():
print('That\'s a combination of letters and numbers.')
exit()
b = a[::-1]
if a == b:
print('The word is a palindrome!')
else:
print('The word is not a palindrome!')
I am supposed to write a program that asks the user to enter a word with 5 letters and then check whether the third letter is e or not.
input('Enter word with 5 letters:'
if [2] == e:
print("the third letter is e")
but nothing happens after I input a word with 5 letters.
Corrected code should be like this:
word = input('Enter word with 5 letters: ')
if word[2] == 'e':
print("the third letter is e")
Try this,
user_input = input('Enter word with 5 letters:')
if user_input[2] == 'e':
print("the third letter is e")
You need to save the value, in this case the input, into a variable and then access its letters with [].
userInput = input('Enter word with 5 letters: ')
if userInput[2] == 'e':
print("the third letter is e")
You always have to save values, information and actions into variables if you want to use or modify them further on.
In Python you can read strings like arrays.
For example:
myString = "abcdef"
print(myString[3])
Your result will be d
So what you have to do is
1st take the input and save it to a variable like this
string_input = input()
2nd check if the third letter is 'e' or not
if(string_input[2]=='e'):
print("Third letter is e")
Note: string[] returns char value
For an assignment, I need code that asks the user for a word and a letter. Then, it edits the word to not include the specific letter. It needs in include a "for i in range" statement. The code before works but doesn't use a for loop and uses a python command.
word1 = raw_input ("Give me a word! ")
letter1 = raw_input ("Give me a letter! ")
modify = word1.replace(letter1,"")
check = word1.find(letter1)
if check == -1:
print "There is no letters to replace in", word1
check = 0
if check >= 1:
print modify
How about:
word = raw_input('Give me a word! ')
letter = raw_input('Give me a letter! ')
cleaned = ''
for i in range(len(word)):
if word[i] != letter:
cleaned += word[i]
if cleaned:
print cleaned
else:
print 'There is no letters to replace in', word
You can iterate through a string letter by letter like you would a list or dict
word='someword'
for letter in word:
print(letter)
I'm making a Morse code program:
def main ():
morse_code = {"a":".-","b":"-...","c":"-.-.","d":"-..","e":".","f":"..-.","g":"--.","h":"....","i":"..","j":".---","k":"-.-","l":".-..",
"m":"--","n":"-.","o":"---","p":".--.","q":"--.-","r":".-.","s":"...","t":"-","u":"..-","v":"...-","w":".--","x":"-..-","y":"-.--","z":"--.."}
phrase = input("please enter your word or words: ")
for key in phrase:
print("your word or sentence translated to morse code is : ")
print(morse_code[key], end = " ")
if phrase == int or float:
print("try the input")
retry()
def retry ():
main()
retry()
main()
How do I print an error if someone enters a number?
This is what you need:-
morse_code = {"a":".-","b":"-...","c":"-.-.","d":"-..","e":".","f":"..-.","g":"--.","h":"....","i":"..","j":".---","k":"-.-","l":".-..",
"m":"--","n":"-.","o":"---","p":".--.","q":"--.-","r":".-.","s":"...","t":"-","u":"..-","v":"...-","w":".--","x":"-..-","y":"-.--","z":"--.."}
phrase = input("please enter your word or words: ")
if any(char.isdigit() for char in phrase):
print("try the input")
else:
print("your word or sentence translated to morse code is : ")
code = ' '.join(morse_code[key] for key in phrase)
print(code)
You can use str.isdigit
for key in phrase:
if not key.isdigit():
print("your word or sentence translated to morse code is : ")
print(morse_code[key], end = " ")
You can check if the input is between a and z by doing:
try:
index = ord(key.lower())
if index >= 97 and index <= 122:
# Do your thing
except TypeError:
# Wrong input
The TypeError shouldn't happen, it's just good practice to wrap code with errors handling.
Or, you can do:
if not key.isdigit():
# Key isn't between 0 and 9. Can be uppercase or a symbol, though.
if ord(key.lower()) >= 97 and ord(key.lower()) <= 122:
# Do your thing. It's pretty much the same as before but with one more step.
Your first problem you will have is that the if statement is A: after the printing out of the Morsecode version of the letter, and B: it is outside of the for loop completely.
You can rectify this by putting it in the for loop before the printing like so:
phrase = input("please enter your word or words: ")
print("your word or sentence translated to morse code is : ")
for key in phrase:
if phrase == int or float:
print("try the input")
else:
print(morse_code[key], end = " ")
However the above code still won't work, as the way you are checking if the current letter being printed out is a int or float isn't how you do it.
The easiest method is to change the codition of the if statement to if key.isdigit():
This will leave you with this final block of code:
phrase = input("please enter your word or words: ")
print("your word or sentence translated to morse code is : ")
for key in phrase:
if key.isdigit:
print("try the input")
else:
print(morse_code[key], end = " ")
This now works, however, lets say I enter abc123. The output I would get is .-
-...
-.-.
try the input
try the input
as the code is running the forloop regardless of if there are numbers in the input or not. To prevent this, you should check the input for numbers, before you have the for loop printing out the morse code.
phrase = input("please enter your word or words: ")
while not phrase.isalpha():
phrase = input("invalid input: ")
print("your word or sentence translated to morse code is : ")
for key in phrase:
print(morse_code[key], end = " ")
If you need any help, let me know!
Using isdigit() will solve your problem also use break to receive new input
morse_code = {"a":".-","b":"-...","c":"-.-.","d":"-..","e":".","f":"..-.","g":"--.","h":"....","i":"..","j":".---","k":"-.-","l":".-..",
"m":"--","n":"-.","o":"---","p":".--.","q":"--.-","r":".-.","s":"...","t":"-","u":"..-","v":"...-","w":".--","x":"-..-","y":"-.--","z":"--.."}
Morse_Parse=[]
phrase = input("please enter your word or words: ")
print("your word or sentence translated to morse code is : ")
for key in range(0,len( phrase)):
if phrase[key].isdigit():
print("you inderted an digit , Try another input")
break
else:
Morse_Parse.append(morse_code[phrase[key]]+" ")
print("Morse for your input is "Morse_Parse)
using flag will improve print task
morse_code = {"a":".-","b":"-...","c":"-.-.","d":"-..","e":".","f":"..-.","g":"--.","h":"....","i":"..","j":".---","k":"-.-","l":".-..",
"m":"--","n":"-.","o":"---","p":".--.","q":"--.-","r":".-.","s":"...","t":"-","u":"..-","v":"...-","w":".--","x":"-..-","y":"-.--","z":"--.."}
Morse_Parse=[]
phrase = input("please enter your word or words: ")
print("your word or sentence translated to morse code is : ")
flag=1
for key in range(0,len( phrase)):
if phrase[key].isdigit():
print("you inderted an digit , Try another input")
flag=0
break
else:
Morse_Parse.append(morse_code[phrase[key]]+" ")
if flag==1:
print("Morse for your input is "Morse_Parse)
how to only allow letters
How do I print an error if someone enters a number?
The second case is covered easily by checking .isdigit on each character as others mentioned. But I will cover the first case.
Start by defining a string of valid characters. Assuming your valid character set is lowercase a-z, this would be the same as string.ascii_lowercase
import string
valid_characters = string.ascii_lowercase # a-z
def char_valid(c):
'''Check if a character is valid, returns True/False'''
return c in valid_characters
def phrase_valid(phrase):
'''Check if the phrase is valid, returns True/False'''
return all(char_valid(char) for char in phrase)
while True:
user_phrase = input('Enter some characters')
if phrase_valid(user_phrase):
# If the phrase is valid, end the loop
break
else:
print('That was not a valid phrase')
# the loop continues and will ask for input again
This pattern works any time you want to keep asking for input until it is valid.