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.
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.
name = input("Hi. What's your name? ")
print("name")
print("Hi,", name)
input("\n\nPress the enter key to exit.")
It says multiple statements found while compiling a single statement
I'm using a book and tried many different things. Also, I'm a noob at this as you can tell. If you have any suggestions that'll be great
Your code is fine, assuming you are using python 3, but you need to type (or paste) each line, one at a time. Based on what you are seeing, I suspect you are putting it all in at once, without a new line after each line.
If you are using python 2, you'll need to use raw_input rather than input, like this:
name = raw_input("Hi. What's your name? ")
print("name")
print("Hi,", name)
input("\n\nPress the enter key to exit.")
So couple of things:
print("name") will not print the name you captured from the last variable but a string that says name
print("Hi,", name) prints ('Hi,', 'Dmitry') which is probably not what you want, instead do this: ', '.join(["Hi", name]) There are probably other Python 3 conventions but I work in Python 2 so I don't know them all off the top of my head.
input("\n\nPress the enter key to exit.") not sure of the purpose of this line. Seems like a stray line from a block of code and it's not being assigned to any variable. Furthermore it throws an error SyntaxError. What book are you using if I may ask?
You can check the Python version in the HELP>about IDLE tab of IDLE editor or Shell - you seem to be using python 2 as others have stated
If you are able to enter and run one line of code at a time, followed by the next line then you are using the Shell, not the IDLE editor
You should be able to paste the code you have in question into IDLE editor and run (F5) - you should be prompted to save before it is run in the Shell.
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.
I tried searching for this answer online but I haven't found any luck. I am wondering if python supports a logical not operator (usually '!') in other languages for an if statement, or any control statement really. For example, I am looking to achieve this functionality.
if !(re.search('[0-9]', userInputVariable):
fix error and report to user
...Proceed with rest of code...
Where basically if the user does not input a number I correct it to a default value and proceed with script
Thanks!
You're looking for the not operator.
But that's not how you check for a number.
try:
int(userInputVariable)
except ValueError:
print "Not a number"
...
if not userInputVariable.isdigit():