I want to get a string from a user, and then to manipulate it.
testVar = input("Ask user for something.")
Is there a way for testVar to be a string without me having the user type his response in quotes? i.e. "Hello" vs. Hello
If the user types in Hello, I get the following error:
NameError: name 'Hello' is not defined
Use raw_input() instead of input():
testVar = raw_input("Ask user for something.")
input() actually evaluates the input as Python code. I suggest to never use it. raw_input() returns the verbatim string entered by the user.
The function input will also evaluate the data it just read as python code, which is not really what you want.
The generic approach would be to treat the user input (from sys.stdin) like any other file. Try
import sys
sys.stdin.readline()
If you want to keep it short, you can use raw_input which is the same as input but omits the evaluation.
We can use the raw_input() function in Python 2 and the input() function in Python 3.
By default the input function takes an input in string format. For other data type you have to cast the user input.
In Python 2 we use the raw_input() function. It waits for the user to type some input and press return and we need to store the value in a variable by casting as our desire data type. Be careful when using type casting
x = raw_input("Enter a number: ") #String input
x = int(raw_input("Enter a number: ")) #integer input
x = float(raw_input("Enter a float number: ")) #float input
x = eval(raw_input("Enter a float number: ")) #eval input
In Python 3 we use the input() function which returns a user input value.
x = input("Enter a number: ") #String input
If you enter a string, int, float, eval it will take as string input
x = int(input("Enter a number: ")) #integer input
If you enter a string for int cast ValueError: invalid literal for int() with base 10:
x = float(input("Enter a float number: ")) #float input
If you enter a string for float cast ValueError: could not convert string to float
x = eval(input("Enter a float number: ")) #eval input
If you enter a string for eval cast NameError: name ' ' is not defined
Those error also applicable for Python 2.
If you want to use input instead of raw_input in python 2.x,then this trick will come handy
if hasattr(__builtins__, 'raw_input'):
input=raw_input
After which,
testVar = input("Ask user for something.")
will work just fine.
testVar = raw_input("Ask user for something.")
My Working code with fixes:
import random
import math
print "Welcome to Sam's Math Test"
num1= random.randint(1, 10)
num2= random.randint(1, 10)
num3= random.randint(1, 10)
list=[num1, num2, num3]
maxNum= max(list)
minNum= min(list)
sqrtOne= math.sqrt(num1)
correct= False
while(correct == False):
guess1= input("Which number is the highest? "+ str(list) + ": ")
if maxNum == guess1:
print("Correct!")
correct = True
else:
print("Incorrect, try again")
correct= False
while(correct == False):
guess2= input("Which number is the lowest? " + str(list) +": ")
if minNum == guess2:
print("Correct!")
correct = True
else:
print("Incorrect, try again")
correct= False
while(correct == False):
guess3= raw_input("Is the square root of " + str(num1) + " greater than or equal to 2? (y/n): ")
if sqrtOne >= 2.0 and str(guess3) == "y":
print("Correct!")
correct = True
elif sqrtOne < 2.0 and str(guess3) == "n":
print("Correct!")
correct = True
else:
print("Incorrect, try again")
print("Thanks for playing!")
This is my work around to fail safe in case if i will need to move to python 3 in future.
def _input(msg):
return raw_input(msg)
The issue seems to be resolved in Python version 3.4.2.
testVar = input("Ask user for something.")
Will work fine.
Related
I'm very familiar with the random module but I always stumbled when it came to functions. How do I make a function only occur if it meets a certain condition? It gives me no output when im trying to validate my answer...
choice = input ("Which type of password would you like to generate? \n 1. Alphabetical \n")
if choice == 1:
characters = list(string.ascii_letters)
def generate_random_abc_password():
length = int(input("Enter password length: "))
random.shuffle(characters)
password = []
for i in range(length):
password.append(random.choice(characters))
random.shuffle(password)
print("".join(password))
generate_random_abc_password()
Seems like the most common mistake among beginners. When you use an input() function, it will return you some number/text/float or decimal number but in string type. For example
x = input("Enter your number")
# If i would input 2, my x variable would contain "2"
# 3 => "3"
# 550 => "550" and so on...
To avoid such a problem and to store your value in proper type, you need to wrap your input with int() function, as shown below
x = int(input(("Enter your number"))
# From now, whenever i prompt any number from my keyboard, it will
# be an integer number, which i can substract, add, multiply and divide.
As simple as it is. Happy learning!
You should convert the input to integer as by default the data type for input is string.
Alternatively rather than changing input data type you can compare it with the str(1) or change if choice == 1: to if choice == '1':
You can try using :
import string
import random
choice = int(input ("Which type of password would you like to generate? \n 1. Alphabetical \n"))
if choice == 1:
characters = list(string.ascii_letters)
def generate_random_abc_password():
length = int(input("Enter password length: "))
random.shuffle(characters)
password = []
for i in range(length):
password.append(random.choice(characters))
random.shuffle(password)
print("".join(password))
generate_random_abc_password()
The above code will result in :
Which type of password would you like to generate?
1. Alphabetical
1
Enter password length: 10
MEQyTcspdy
The problem here is that you've defined the characters variable in your if block. That is your function is not aware of of the variable that is why you should pass the characters variable as a input to the function the code should look like
choice = input ("Which type of password would you like to generate? \n 1. Alphabetical \n")
if choice == 1:
characters = list(string.ascii_letters)
def generate_random_abc_password(characters):
length = int(input("Enter password length: "))
random.shuffle(characters)
password = []
for i in range(length):
password.append(random.choice(characters))
random.shuffle(password)
print("".join(password))
generate_random_abc_password(characters)
A function works like an isolated piece of code it takes it's own inputs and returns it's own outputs or does it's stuff.
As well as the input isn't casted to an int as the above mentioned answer says...
I'm making a simple guessing game in python and was trying to create an "Invalid entry" message for when the user enters in any input that is not an integer.
I have tried to use just 'int' in an if statement to address all integers, but that is not working.
I know that I have the syntax wrong. I'm just not sure what the correct syntax to do it would be.
import random
play = True
while play:
count = 1
hidden = random.randrange(1,5)
guess = int(input("Guess a number between 1 and 5:"))
if guess != int
guess = int(input("Invalid Entry. Please enter an Integer between 1 and 5:"))
while guess != hidden:
count+=1
if guess > hidden + 10:
print("your guess is to high!")
elif guess < hidden -10:
print("your too low!")
elif guess > hidden:
print("your really warm, but still to high!")
elif guess < hidden:
print("your really warm, but still to low")
print("You have guessed incorrectly, Try again!. \n")
#reset the guess variable and make another guess
guess = int(input("Guess a number between 1 and 5:"))
print("Nice!!! Your guess was correct!\n you got the correct number in" , count , "tries.")
count = 1
playagain = str(input("Do you want to play again?\nType yes or no: "))
if playagain == "no" or "n" or "N" or "no thank you":
play = False
elif playagain == "yes" or "y" or "Y" or "YES" or "yes":
play = True
else: playagain != "yes" or "y" or "Y" or "YES" or "yes" "no" or "n" or "N" or "no thank you"
playagain = str(input("Invalid Entry. Please Type yes or no: "))
This is the error that I'm getting. There may be some other mistakes in my code as well.
File "comrandomguess.py", line 18
if guess != int
^
SyntaxError: invalid syntax
If you really want to verify that the user entry is an int, you want to keep the input in string form. Then write a small function to test the input. Here, I'll use a list comprehension and the string join and isdigit methods, to ensure the user has only entered digits 0-9 in the string, i.e. then this function returns True (else False) (*modified as per Jack Taylor comment below, also for s = '' case):
def testForInt(s):
if s:
try:
_ = s.encode('ascii')
except UnicodeEncodeError:
return False
test = ''.join([x for x in s if x.isdigit()])
return (test == s)
else:
return False
If you want to sandbox the user entirely, wrap it in a loop like this:
acceptable = False
while not acceptable:
entry = input("Enter an int: ")
if testForInt(entry):
entry = int(entry)
acceptable = True
else:
print("Invalid Entry")
If you want a simpler version with no function call(see Jack Taylor comment), this works too:
acceptable = False
while not acceptable:
entry = input("Enter an int: ")
try:
entry = int(entry)
acceptable = True
except ValueError as e:
print(f"Failed due to {str(e)}")
Now you've got what you know is an int, with no worries. This kind of approach to verifying user entry saves many headaches if consistently implemented. See SQL injection etc.
I always use this method to check if something is not an integer:
Python 3
if not round(guess) == guess: print("Do Stuff")
Python 2
if not round(guess) == guess: print "Do Stuff"
You need to do something like this:
play = True
while play:
guess = input("Guess a number between 1 and 5: ")
try:
number = int(guess)
except ValueError:
print("You need to input an integer.")
continue
if number < 1 or number > 5:
print("You need to input an integer between 1 and 5.")
continue
# ...
print("Your number was: " + guess)
play = False
When you first use input(), you get a string back. If you try to turn that string into an integer straight away by doing int(input()), and if the player types a string like "abcd", then Python will raise an exception.
>>> int(input("Guess a number: "))
Guess a number: abcd
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'abcd'
To avoid this, you have to handle the exception by doing int(guess) inside a try/except block.
The continue statement skips back to the start of the while loop, so if you use it you can get away with only having to ask for input once.
Parse the user input as string to avoid ValueError.
guess = input("Guess a number between 1 and 5: ")
while not guess.isdigit() or int(guess) > 5 or int(guess) < 1:
guess = input("Invalid Entry. Please enter an Integer between 1 and 5: ")
guess = int(guess)
Above code ensures that user input is a positive integer and between 1 and 5. Next, convert the user input to integer for further use.
Additionally, if you want to check the data type of a python object/variable then use the isinstance method. Example:
a = 2
isinstance(a, int)
Output:
>>> True
I'm new to python. I was creating a code that use .isdigit. It goes like this:
a = int(input("Enter 1st number: "))
if 'a'.isdigit():
b = int(input("Enter 2nd number: "))
else:
print "Your input is invalid."
But when I enter an alphabet, it doesn't come out the "Your input is invalid.
And if I entered a digit, it doesn't show the b, 'Enter 2nd number'.
Is there anyway anyone out there can help me see what's the issue with my code.
That will be a great help. Thanks.
You are assigning the input to a variable a, but when you try to query it with isdigit() you're actually querying a string 'a', not the variable you created.
Also, you are forcing a conversion to an int before you've even checked if it's an int. If you need to convert it to an int, you should do that after you run the .isdigit() check:
a = raw_input("Enter 1st number: ")
if a.isdigit():
a = int(a)
b = int(raw_input("Enter 2nd number: "))
else:
print("Your input is invalid.")
Try to convert your a variable to string type, like this:
a = int(input("Enter 1st number: "))
if str(a).isdigit():
b = int(input("Enter 2nd number: "))
else:
print("Your input is invalid.")
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
I have a function that evaluates input, and I need to keep asking for their input and evaluating it until they enter a blank line. How can I set that up?
while input != '':
evaluate input
I thought of using something like that, but it didn't exactly work. Any help?
There are two ways to do this. First is like this:
while True: # Loop continuously
inp = raw_input() # Get the input
if inp == "": # If it is a blank line...
break # ...break the loop
The second is like this:
inp = raw_input() # Get the input
while inp != "": # Loop until it is a blank line
inp = raw_input() # Get the input again
Note that if you are on Python 3.x, you will need to replace raw_input with input.
This is a small program that will keep asking an input until required input is given.
we should keep the required number as a string, otherwise it may not work. input is taken as string by default
required_number = '18'
while True:
number = input("Enter the number\n")
if number == required_number:
print ("GOT IT")
break
else:
print ("Wrong number try again")
or you can use eval(input()) method
required_number = 18
while True:
number = eval(input("Enter the number\n"))
if number == required_number:
print ("GOT IT")
break
else:
print ("Wrong number try again")
you probably want to use a separate value that tracks if the input is valid:
good_input = None
while not good_input:
user_input = raw_input("enter the right letter : ")
if user_input in list_of_good_values:
good_input = user_input
Easier way:
required_number = 18
user_number = input("Insert a number: ")
while f"{required_number} != user_number:
print("Oops! Something is wrong")
user_number = input("Try again: ")
print("That's right!")
#continue the code
After 4th line, even if u type something else other than yes, it still prints okay?
x = input("Enter any number of your choice: ")
print("the number you picked is", x)
yes = x
input(" right? : ")
if yes:
print("ok")
else:
print("you liar")
Unless you don't enter anything when you prompt for this:
x = input("Enter any number of your choice: ")
if yes: # it's always going to be true
Also this is not doing anything:
input(" right? : ")
you need to assign it to a variable
I think what you want is this:
sure = input(" right? : ")
if sure == 'yes':
You may want to use isnumeric() in case you want to check for a number.
Some documentation on isnumeric() is located at http://www.tutorialspoint.com/python/string_isnumeric.htm
At the moment, you are basically just checking the existence of the variable yes.
BTW: The output for checking up on the number can be rewritten to a formatted statement as follows:
print("The number you picked is {:d} right?".format(x))
Checking, if the user answers with a "yes", can be done easily as well:
yes = input("The number you picked is {:d} right?".format(x))
if (yes == "yes"):
print("ok")
else:
print("you liar")
In case of python2.x you should use raw_input() instead of input(), which is fine for python3.
You want to check what the user is saying for the "Right?" prompt:
x = input("Enter any number of your choice: ")
print("the number you picked is", x)
yes = input(" right? : ") # capture the user input
if yes == "yes": # check if the user said yes
print("ok")
else:
print("you liar")