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]}')
So at first, I needed to create a program where the user enters a Character and if that is Int then an error should pop up... if its Str then it should further divide into Consonants and Vowels. However, this wouldn't solve the problem (and it wasn't working) as the user could enter special characters which would just filter out as Consonants
Z = (input("Enter a character: "))
if type(Z) == int:
print(Z, "is a numeral")
else:
if (Z=='A' or Z=='a' or Z =='E' or Z=='e' or Z=='I'or Z=='i'
or Z=='O' or Z=='o' or Z=='U' or Z=='u'):
print(Z, "is a Vowel")
else:
print(Z, "is a Consonant")
So, after this, I tried to create a list which has all the alphabets in it, and then I thought it would work ... I was wrong
my=input('Enter a character:')
list=[a,A,b,B,c,C,d,D,e,E,f,F,g,G,h,H,i,I,j,J,k,K,l,L,m,M,n,N,o,O,p,P,q,Q,r,R,s,S,t,T,u,U,v,V,w,W,x,X,y,Y,z,Z]
if my in list:
if (my=='A' or my=='a' or my=='E' or my=='e' or my=='I'or my=='i'
or my=='O' or my=='o' or my=='U' or my=='u'):
print(my, "is a Vowel")
else:
print(my, "is a Consonant")
else:
print ('HAHAHA')
This shows this error
Traceback (most recent call last):
File "C:\Users\veert\Desktop\Python\VowelOrConsonant#1.py", line 2, in <module>
list=[a,A,b,B,c,C,d,D,e,E,f,F,g,G,h,H,i,I,j,J,k,K,l,L,m,M,n,N,o,O,p,P,q,Q,r,R,s,S,t,T,u,U,v,V,w,W,x,X,y,Y,z,Z]
NameError: name 'a' is not defined
Please help me guys
The above list value should be type String. So you need to add every character inside "" as below.
my=input('Enter a character:')
list=["a","A","b","B","c","C","d","D","e","E"]
if my in list:
if (my=='A' or my=='a' or my=='E' or my=='e' or my=='I'or my=='i'
or my=='O' or my=='o' or my=='U' or my=='u'):
print(my, "is a Vowel")
else:
print(my, "is a Consonant")
else:
print ('HAHAHA')
When you add list = [a, A, b, B, .... ], Python interpreter try to search value of that variables a, A, b, B etc. It is not pre-defined here. So, it return that NameError.
Something like this maybe?
vowels = ['A','a','E','e','I','i','O','o','U','u'],
consonants = ['B','b','C','c','D','d','H','h','J','j','K','k','L','l','M','m','N','n','P','p','Q','q','R','r','S','s','T','t','V','v','W','w','X','x','Y','y','Z','z']
inp = input('Please enter a character > ')
if inp not in vowels and inp not in consonants:
print(f'{inp} is not in the alphabet')
if inp in vowels:
print(f'{inp} is a vowel')
if inp in consonants:
print(f'{inp} is a consonant')
I've separated vowels from consonants trying to shorten the comparison operators to only a few for readability.
Cater for all input:
alphaneumeric = {
'vowel': ['A','a','E','e','I','i','O','o','U','u'],
'consonant': ['B','b','C','c','D','d','H','h','J','j','K','k','L','l','M','m','N','n','P','p','Q','q','R','r','S','s','T','t','V','v','W','w','X','x','Y','y','Z','z'],
'number': ['1','2','3','4','5','6','7','8','9','0'],
'symbol': ['!','#','#','$','%','^','&','*','(',')','[',']','{','}','<','>','.',',','\'','"',':',';','-','=','/','\\','~','`']
}
inp = input('Please enter a chacter > ')
for key, lst in alphaneumeric.items():
if inp in lst:
print(f'{inp} is a {key}')
break # return immediately
def isPalindrome(word):
l = len(word)
for i in range(l/2):
if(word[i] != word[i+l-1]):
return 0
return 1
def main():
print("\n\n\tTo Check if the word is a Palindrome\n\n")
word = raw_input("Enter a word : ")
if(isPalindrome(word) == 1):
print("It is a Palindrome")
elif:
print("It is not a Palindrome")
main()
In my opinion everything is right in the program. It goes good when I enter a word which is not a palindrome but when I enter a palindrome it gives an error like this:
Enter a word : madam
Traceback (most recent call last):
File "temp.py", line 16, in <module>
File "temp.py", line 6, in isPalindrome
IndexError: string index out of range
First thing that is wrong is: elif: - if you're using else-if you should provide a condition, the fix in this case it to change it to else:
Second, the if should be: if(word[i] != word[l-i-1]): in order for the function to work (check that each letter is equal to its equivalent in the word).
Third, less critical but still important: keep the styling:
remove redundant braces
use proper naming convention (snake-case - not camel-case)
use True/False as return values instead of 1/0
use floor division // (as AChampion mentioned in the comments)
Complete code (fixed):
def is_palindrome(word):
l = len(word)
for i in range(l//2):
if word[i] != word[l-i-1]:
return False
return True
def main():
print("\n\n\tTo Check if the word is a Palindrome\n\n")
word = raw_input("Enter a word : ")
if is_palindrome(word):
print("It is a Palindrome")
else:
print("It is not a Palindrome")
if __name__ == "__main__":
main()
Your logic for checking palindrome should be:
if(word[i] != word[l-1-i]):
return 0
It's okay to do l/2 if you're on python 2 but python 3 will produce the result as a floating point value.
Your code seems to be in py3.
And you need to give a condition to the elif block. Otherwise, change it to else.
Change word[i+l-1] to word[l-i-1]:
def isPalindrome(word):
l = len(word)
for i in range(l // 2):
if(word[i] != word[l-i-1]):
return 0
return 1
The goal is to get the word[l-i-1 to count down while i is counting up; hence, you need to subtract i rather than add it.
Also, I would change the l/2 to l // 2 so that it works in Python 3 as well.
Hope that helps :-)
You should round the l/2 value
def isPalindrome(word):
l = len(word)
for i in range(round(l/2)):
if(word[i] != word[i+l-1]):
return 0
return 1
print("\n\n\tTo Check if the word is a Palindrome\n\n")
word = input("Enter a word : ")
if(isPalindrome(word) == 1):
print("It is a Palindrome")
else:
print("It is not a Palindrome")
I'm having trouble with a word game I'm trying to make, scrabble.
A part of my code,where it eventually gives the error, is:
def is_valid_word(word, hand, word_list):
"""
Returns True if word is in the word_list and is entirely
composed of letters in the hand. Otherwise, returns False.
Does not mutate hand or word_list.
word: string
hand: dictionary (string -> int)
word_list: list of lowercase strings
"""
hand_copy = hand.copy()
if word not in wordList:
return False
for char in word:
if char not in hand_copy:
return False
else:
hand_copy[char] -= 1
if hand_copy[char] < 0:
return False
return True
def play_hand(hand, words):
"""
Allows the user to play the given hand, as follows:
* The hand is displayed.
* The user may input a word.
* An invalid word is rejected, and a message is displayed asking
the user to choose another word.
* When a valid word is entered, it uses up letters from the hand.
* After every valid word: the score for that word is displayed,
the remaining letters in the hand are displayed, and the user
is asked to input another word.
* The sum of the word scores is displayed when the hand finishes.
* The hand finishes when there are no more unused letters.
The user can also finish playing the hand by inputing a single
period (the string '.') instead of a word.
hand: dictionary (string -> int)
words: list of lowercase strings
"""
n = HAND_SIZE
display_hand(hand)
print "You may enter '.' if you cannot create a word."
word = raw_input("Please enter a word:")
score = 0
totalscore = 0
while not len(hand) == 0 and not word == ".":
print word
if is_valid_word(word, hand, load_words()) == False:
print "That is not a valid word"
word = raw_input("Please enter a word:")
elif is_valid_word(word, hand, load_words()) == True:
score = get_word_score(word, n)
print "You word was worth " + str(score) + " points."
totalscore = totalscore + score
print "Your total score is: " + str(totalscore) + "."
print "Here is your updated hand."
hand = update_hand(hand,word)
display_hand(hand)
if len(hand) != 0:
word = raw_input("Please enter a word:")
print "Your total score is: " + str(totalscore) + "."
return
def play_game(words):
"""
Allow the user to play an arbitrary number of hands.
* Asks the user to input 'n' or 'r' or 'e'.
* If the user inputs 'n', let the user play a new (random) hand.
When done playing the hand, ask the 'n' or 'e' question again.
* If the user inputs 'r', let the user play the last hand again.
* If the user inputs 'e', exit the game.
* If the user inputs anything else, ask them again.
"""
hand = deal_hand(HAND_SIZE)
while True:
cmd = raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game: ')
if cmd == 'n':
hand = deal_hand(HAND_SIZE)
play_hand(hand, words)
print
elif cmd == 'r':
play_hand(hand, words)
print
elif cmd == 'e':
break
else:
print "Invalid command."
In my opninion this should work. I can start the game, deal a new hand, replay the last hand or end a game. But when I try to make a word from the given letters it gives this error:
Traceback (most recent call last):
File "wordgames.py", line 257, in <module>
play_game(words)
File "wordgames.py", line 241, in play_game
play_hand(hand, words)
File "wordgames.py", line 204, in play_hand
if is_valid_word(word, hand, load_words()) == False:
File "wordgames.py", line 163, in is_valid_word
if word not in wordList:
NameError: global name 'wordlist' is not defined
I've been trying a lot, but nothing helps... Please can somebody help me fixing this?
Thanks in advance!
The error is clearly stated at the bottom of the traceback:
File "wordgames.py", line 163, in is_valid_word
if word not in wordList:
NameError: global name 'wordlist' is not defined
ie you don't define wordList - the input variable is called word_list.
Also you should fix the indentation in your question to make it clear where the function definition ends and you return to global scope.
As jonsharpe points out, your traceback is also inconsistent (wordlist instead of wordList)