I am writing a program which is supposed to contain a way of informing the user that the input for one of the variables is not a string, if entered as a name by user.
E.g. program expects a user input of any string, and if it is a string which is contained within dictionary, it will print out its value, if not, it will print out an error message.
ageofdeath.getage('JesusChrist')
33
ageofdeath.getage('John McCena')
This is not a bible character. Please enter a name of a character from the bible.
but, the program should at least throw an error message when confronted with wrong user input such as
ageofdeat.getage(JesusChrist)
ideally popping up a message along the lines of "This is not a string please input a string". Instead, no matter whether i try to use if = or isinstance, it always shows typical python name is not defined error. Is there a way of going round this or not really, as it is a default way of python shell handling the input?
Your program isn't even getting to the part where it executes your getage() method. It is failing far earlier.
You're using input() instead of raw_input(). Thus JesusChrist is taken as the name of a variable because input() evaluates what the user types as a Python expression. JesusChrist is a legal Python variable name, it just hasn't been defined, so Python tells you that. And because it knows you can't do anything with a value that doesn't exist, it stops.
Now you could catch that error by wrapping your input() in a try/except block, but that's just trying to compensate for making the wrong decision in the first place. The right answer is to use raw_input() to get input from your user and it will always be a string.
Related
When I run the following code :
import math
x=float(input('enter : '))
print(x)
and then I input : math.sin or cos or pi or log .... of a number like : sin(2) ,I get this error :
Traceback (most recent call last):
File "C:\Users\user\Desktop\hh.py", line 10, in <module>
x=float(input('enter : '))
ValueError: could not convert string to float: 'sin(x)'
You can get an answer by combining comments from #Walter Tross and #wwii. How to fix the problem if you want users to be able to enter code that will be evaluated with the result stored in x, you should use:
from ast import literal_eval
x = literal_eval(input('enter:'))
P.S. You will need to put quotation marks around the user input.
P.P.S. Your user can put in basically any code to be executed using this input.
To get to the why, you are giving python commands and expecting it to evaluate what you said and store it in x. You are giving words to python and not giving it a way to convert them to numbers. It'd be the same as typing into your terminal 2 plus 2. The words don't mean anything unless you have some kind of compiler.
It is difficult for you to write a program to understand and evaluate expressions, especially ones that include functions like sin or sqrt. However, if you are sure that the user of your program is safe (and that is usually a bad assumption), you can get Python to do the evaluation using the built-in eval function. You could try this:
import math
strexpr = input('enter: ')
print(eval(strexpr))
Then, if you run this program and the user types math.sin(2), the program prints
0.9092974268256817
which is the correct value of the sine of two radians.
NOTE: This little program will allow the user to type any valid Python expression then evaluate it. If the user knows how, he could use this to format the hard drive and wipe out all your data or do all kinds of mischief. Use this only if you are totally sure of the user. But how can you ever be sure about anyone else?
This piece of code is supposed to find account balance after withdraw from bank(fee=0.5).
wd,ac=raw_input().split(" ")
wd=int(wd)
ac=float(ac)
if(ac<wd):
print(ac)
elif(wd%5==0):
if(ac>wd+0.50):
print(ac-wd-0.50)
else:
print(ac)
else:
print(ac)
I got a Runtime NZEC Error while submitting on codechef. I am newbie and had searched for resolve and had used split(" ") in place of int(input()), which I had tried previously, but the problem still occurs.
Geeksforgeeks says:
"In python, generally multiple inputs are separated by commas and we read them using input() or int(input()), but most of the online coding platforms while testing gives input separated by space and in those cases int(input()) is not able to read the input properly and shows error like NZEC"
Given that I've tried to account for that... What is wrong with my code?
It looks like an error with your raw_input statement. Remember that, in python 3, raw_input doesn't exist any more. If you changed it from raw_input to input, then the code works just fine.
I want user to input a name of a table, table = str(input("table: ")) works, but it's kind of annoying to put 'name' everytime instead of just name, is there any work around for this?
Use raw_input:
table = raw_input("table: ")
>input([prompt])
Equivalent to eval(raw_input(prompt))
This function does not catch user errors. If the input is not syntactically valid, a SyntaxError will be raised. Other exceptions may be raised if there is an error during evaluation.
If the readline module was loaded, then input() will use it to provide elaborate line editing and history features.
Consider using the raw_input() function for general input from users.
print("text")
print("text")
name=str(input("text"))
name=name.capitalize()
tutorial=str(input(print(name,"do you know the rules? (YES/NO)",sep=", ")))
tutorial=tutorial.upper()
I can't find the error in my code. Everytime I run it a "None" keeps coming out of nowhere. (replaced some parts of the code so it can be read more easily)
Name? >>>HAL 9000
Hal 9000, do you know the rules? (YES/NO)
None #This I want to erase
Your problem is in this line:
tutorial=str(input(print(name,"do you know the rules? (YES/NO)",sep=", ")))
You are getting that None because you have an unnecessary print inside your input. Your input is using the return of that print, which does not return anything, so by default is None. You are still seeing what is inside print because of the obvious functionality of print to output what you are sending inside the print method.
View this example that replicates your problem:
>>> input(print('bob'))
bob
None
''
>>>
To fix this problem, remove that print. Also, change the string in your input to use string format:
tutorial=str(input("{} do you know the rules? (YES/NO)".format(name)))
print doesn't return a value, so it's treated as returning None. Which means that you're effectively calling input(None) which prints out "None" before prompting you for input.
key=input("What is your word? ")
ans=open("file.txt","r")
for line in ans:
for word in line.split():
if (key) in (word):
print("Yes")
The code works when I write it without the input variable but as soon as I do it comes back saying that the text I entered is not defined.
Change input to raw_input and the code will work as expected. input evaluates whatever user enters as Python code where as raw_input returns the user input as a string.
In Python2, input() is not the same as in Python3. In Python2, input() is the same as eval(raw_input()). That is, it converts what the user types into Python code. When the user types a normal word, Python tries to evaluate it but finds that the variable is not defined. In Python2, you need to use raw_input(), not input().