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")
Related
Currently using 3.8.1.
I was wondering how I could make a while True: loop like in the example below, but using a number that the user inputted instead of a word (for example any number equal to or lower then 100 would print something different. I've looked on this website, but I couldn't understand the answers for questions similar to mine.
while True:
question = input("Would you like to save?")
if question.lower() in ('yes'):
print("Saved!")
print("Select another option to continue.")
break
if question.lower() in ('no'):
print ("Select another option to continue.")
break
else:
print("Invalid answer. Please try yes or no.")
How about including less than / great than clauses in your if statements?
while True:
# get user input:
user_input = input("Would you like to save? ")
# convert to int:
number = int(user_input)
if number <= 100:
print("Saved!")
print("Select another option to continue.")
break
elif number > 100:
print ("Select another option to continue.")
break
else:
print("Invalid answer. Please try yes or no.")
you need to extract the number from the input and then run your conditional evaluation of the inputed value.
while True:
input_val = input("Enter a #?")
try:
num=int(input_val)
except ValueError:
print("You have entered an invalid number. please try again")
continue
if num == 1:
print("bla bla")
elif num ==2:
print("bla bla 2")
else:
...
input takes the user's input and outputs a string. To do something with numbers, check if the string is numeric, cast it to an int and do whatever you want
while True:
answer = input("How many dogs do you have?")
if answer.isnumeric():
num_dogs = int(answer)
else:
print("Please input a valid number")
I think you maybe want a list instead of a tuple.
Could this work:
while True:
number = input("Enter a number?")
if int(number) in list(n for n in range(100)):
print("lower!")
elif int(number) in [100]:
print ("exact")
else:
print("higher")
I'm new to coding (Python) and am trying to learn loops. I have had some difficulty with a little complex while and for loops. Here I'm trying to create a function and use the while loop. Could I get some ideas on how to fix this code and get some explaintion on what i did wrong?
What I'm trying to achieve with this code is that I have some numbers stored in a list which are secret. And until the user doesn't type in one of these numbers the loop will continue asking. As soon as the user types in one of the numbers, the loop will exit preferibly without using exit() from sys.
def hell_hole():
print("You have just fallen through the hell hole.")
print("You must guess the right number to stop falling otherwise this program will keep repeating.")
print("The right numbers are between 1 - 10 ")
password = [4,9,8]
while True:
typed_in = input("What is the passing code?\n> ")
if typed_in != password:
print("Wrong, try again!")
elif typed_in == password:
print("Well done! You have stopped falling.")
else:
print("Say what?")
I know that this problem can be solved if i changed the if-statment to this:
while True:
typed_in = input("\nWhat is the passing code?\n> ")
if "4" in typed_in or "8" in typed_in or "9" in typed_in:
print("Well done! You have stopped falling.")
exit()
else:
print("Wrong, try again!")
But I want to try to fix the inital code if possible.
You will find below a working version of your code!
As it war already posted, if you want to check if the number entered by the user is IN the list of passwords, you can use the keyword in to do that. Furthermore, as the passwords are integer, you need to convert the input to this type.
In order to exit the while loop, you can use break, which allows you to exit the more nested loop!
Hope it helps!
def hell_hole():
print("You have just fallen through the hell hole.")
print("You must guess the right number to stop falling otherwise this program will keep repeating.")
print("The right numbers are between 1 - 10 ")
password = [4,9,8]
while True:
typed_in = int(input("What is the passing code?\n> "))
if typed_in in password:
print("Well done! You have stopped falling.")
break
else:
print("Wrong, try again!")
You can use in statement:
password = ['4','9','8']
while True:
typed_in = input("\nWhat is the passing code?\n> ")
if typed_in in password:
print("Well done! You have stopped falling.")
break
else:
print("Wrong, try again!")
Instead of sys.exit() you can use either break that will break your loop (here the while loop) or return that will return from your function.
Note that you can return a value from your function to use it out of it by using return yourValue but in your case it's not useful.
Also, an other useful control flow keyword is continue which allow you to skip an iteration of your loop. All those keywords work for both while and for loops.
To make your if statement better, i think you should either check if the password is one of the values you want it to be :
if typed_in in ["4","8","9"]:
or check if one of those values are in the inputted string, just as you seem to do :
if any(x in typed_in for x in ["4", "8", "9"]):
Cast the user input to an int, since you're comparing it to an array of int
Use in and not in to check whether the entered number is in password
Use break instead of exit(). break will simply exit the while loop.
Working implementation:
while True:
typed_in = int(input("What is the passing code?\n> "))
if typed_in not in password:
print("Wrong, try again!")
elif typed_in in password:
print("Well done! You have stopped falling.")
break
else:
print("Say what?")
Demo: https://repl.it/#glhr/55450907
note: you are trying to compare input (string) with whole list:
if typed_in != password
instead of that, check if input is in the list
Fastest way to check if a value exist in a list:
if typed_in in password:
Also in your list (password = [4,9,8] )you have integers, input() is returning string
because of that you need to convert input into integer:
int(input("What is the passing code?\n> "))
The return statement can be used as a kind of control flow. By putting one (or more) return statements in a function the return statement allows you to terminate the execution of a function
password = [4,9,8] # List of numbers
while True:
typed_in = int(input("What is the passing code?\n> "))
if typed_in not in password: # Check if input is IN the list
print("Wrong, try again!")
elif typed_in in password: # Check if input is NOT in the list
print("Well done! You have stopped falling.")
return # Exit function
else:
print("Say what?")
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 4 years ago.
Python newbie here so sorry for what I'm sure is a stupid question, but I can't seem to solve the following challenge in a tutorial that is asking me to use a while loop to check for valid user input.
(using Python2.7)
Here's my code, but it's not working properly:
choice = raw_input('Enjoying the course? (y/n)')
student_surveyPromptOn = True
while student_surveyPromptOn:
if choice != raw_input('Enjoying the course? (y/n)'):
print("Sorry, I didn't catch that. Enter again: ")
else:
student_surveyPromptOn = False
The above prints out to the console:
Enjoying the course? (y/n) y
Enjoying the course? (y/n) n
Sorry, I didn't catch that. Enter again:
Enjoying the course? (y/n) x
Sorry, I didn't catch that. Enter again:
Enjoying the course? (y/n)
Which obviously isn't correct — the loop should end when the user enters either 'y' or 'n' but I'm not sure how to do this. What am I doing wrong here?
Note: the challenge requires me to use both the != operator and the loop_condition
You can use the condition
while choice not in ('y', 'n'):
choice = raw_input('Enjoying the course? (y/n)')
if not choice:
print("Sorry, I didn't catch that. Enter again: ")
A shorter solution
while raw_input("Enjoying the course? (y/n) ") not in ('y', 'n'):
print("Sorry, I didn't catch that. Enter again:")
What your code is doing wrong
With regard to your code, you can add some print as follow:
choice = raw_input("Enjoying the course? (y/n) ")
print("choice = " + choice)
student_surveyPromptOn = True
while student_surveyPromptOn:
input = raw_input("Enjoying the course? (y/n) ")
print("input = " + input)
if choice != input:
print("Sorry, I didn't catch that. Enter again:")
else:
student_surveyPromptOn = False
The above prints out:
Enjoying the course? (y/n) y
choice = y
Enjoying the course? (y/n) n
choice = y
input = n
Sorry, I didn't catch that. Enter again:
Enjoying the course? (y/n) x
choice = y
input = x
Sorry, I didn't catch that. Enter again:
Enjoying the course? (y/n)
As you can see, there is a first step in your code where the question appears and your answer initializes the value of choice. This is what you are doing wrong.
A solution with != and loop_condition
If you have to use both the != operator and the loop_condition then you should code:
student_surveyPromptOn = True
while student_surveyPromptOn:
choice = raw_input("Enjoying the course? (y/n) ")
if choice != 'y' and choice != 'n':
print("Sorry, I didn't catch that. Enter again:")
else:
student_surveyPromptOn = False
However, it seems to me that both Cyber's solution and my shorter solution are more elegant (i.e. more pythonic).
The very simple solution for this is to initialize some variable at the before the loop kicks in:
choice=''
#This means that choice is False now
while not choice:
choice=input("Enjoying the course? (y/n)")
if choice in ("yn")
#any set of instructions
else:
print("Sorry, I didn't catch that. Enter again: ")
choice=""
What this while conditional statement means is that as long as choice variable is false--doesn't have any value means choice=''-- ,then proceeds #with the loop
If the choice have any value then proceed with enters the loop body and check
the value for specific input, if the input doesn't fulfill the required value
then reset the choice variable to False value again to continue prompts user
until a correct input is supplied
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
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.