Name error in one program whereas syntax error in another - python

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

Related

How do I parse a string without running into infinite loops?

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]}')

Name 'USER_INPUT' is not defined? (Python 3.9.2)

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!')

how does one check if a letter is used after input?

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

Editing a String without Python Commands (with "for i in range")

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)

how to only allow letters to be used python statment

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.

Categories