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")
Related
I am making a text based adventure game in python 3 and I was wondering what the simplest loop is. Using the code I have, it continues to print "whats the number" even when you put the correct number, also giving 9 as input doesnt work. It also doesn't work when I give ("8","9"). Here is my code :
print("whats the number?")
required_number = ("8" or "9")
while True:
number = input()
if number == required_number:
print ("GOT IT")
else: print ("Wrong number try again")
Try this :
print("whats the number?")
required_number = [8,9]
while True:
number = int(input())
if number in required_number :
print('GOT IT')
break
else:
print('Wrong number try again')
Sample output in shell :
whats the number?
5
Wrong number try again
2
Wrong number try again
4
Wrong number try again
8
GOT IT
print("whats the number?")
required_number = [8,9]
while True:
number = input()
if number in required_number:
print ("GOT IT")
break
else:
print ("Wrong number try again")
The word you are looking for in place of == is in since required_number is a tuple you're looking to see if the input is in required_number. Also the correct syntax for the tuple would be using a comma not or.
I also would make required_number plural to be a more accurate description of what it holds, and you probably want to use integers and not strings.
required_numbers = (8, 9)
while True:
number = int(input("whats the number?"))
if number in required_numbers:
print("GOT IT")
break #Stop asking
else:
print ("Wrong number try again")
If your required_number or the input will accommodate a string, then you can use this:
required_number = [8,9]
required_number = str(required_number)
number = None
while True:
number = input("Write a number: ")
if number in required_number:
print ("GOT IT")
else:
print ("Wrong number try again")
Output:
Write a number: 3
Wrong number try again
Write a number: 8
GOT IT
Write a number: Hi
Wrong number try again
input treats it as a str in Python 3.x
Preferably use a list for the required numbers
Using in to check for the number in the required_numbers
Put it in a try block to catch value error exceptions.
Hence:
required_number = [8,9] # a list of integer types
while True:
try:
number = int(input("whats the number? ")) # Using `int` to convert the `str`
if number in required_number:
print ("GOT IT")
break # break out when the number is found
else:
print ("Wrong number try again")
except ValueError:
print("Invalid Input, Please enter an integer only.")
Note: == determines if the values are equal, while in operator iterates over the list of elements and returns True or False.
OUTPUT:
whats the number? g
Invalid Input, Please enter an integer only.
whats the number? abc
Invalid Input, Please enter an integer only.
whats the number? 3
Wrong number try again
whats the number? 9
GOT IT
Try this Method
print('Enter a Number:')
required_number = ['8','9']
while True:
number = input()
if number in required_number:
print ("GOT IT")
break
else:
print ("Wrong number try again")
I am trying to write a game that generates a random integer and the user has to guess it.
The problem is that if the user input is not a digit it crashes. So I tried to use isdigit, and it works at the beginning, but if the user decides to input not a number after the first input was a digit, it still crashes. I don't know how to make it check isdigit for every input.
import random
x =(random.randint(0,100))
print("The program draws a number from 0 to 100. Try to guess it!")
a = input("enter a number:")
while a.isdigit() == False :
print("It is not a digit")
a = input("enter a number:")
if a.isdigit() == True :
a = int(a)
while a != x :
if a <= x :
print("too less")
a = input("enter a number:")
elif a >= x :
print("too much")
a = input("enter a number")
if a == x :
print("good")
I would suggest doing the following:
completed = False
while not completed:
a = input("enter a number: ")
if a.isdigit():
a = int(a)
if a < x:
print("too little")
elif a > x:
print("too much")
else:
print("good")
completed = True
else:
print("It is not a digit")
If your code crashed because the user entered not a number, then either make sure the user enters a number, or handle an error while trying to compare it with a number.
You could go over all chars in the input and ensure that they are all digits.
Or you could use a try/except mechanism. That is, try to convert to the numerical type you wish the user to enter and handle any error throwen. Check this post:
How can I check if a string represents an int, without using try/except?
And also:
https://docs.python.org/3/tutorial/errors.html
The typical pythonic way to tackle that would be to "ask for forgiveness instead of looking before you leap". In concrete terms, try to parse the input as int, and catch any errors:
try:
a = int(input('Enter a number: '))
except ValueError:
print('Not a number')
Beyond that, the problem is obviously that you're doing the careful checking once at the start of the program, but not later on when asking for input again. Try to reduce the places where you ask for input and check it to one place, and write a loop to repeat it as often as necessary:
while True:
try:
a = int(input('Enter a number: '))
except ValueError: # goes here if int() raises an error
print('Not a number')
continue # try again by restarting the loop
if a == x:
break # end the loop
elif a < x:
print('Too low')
else:
print('Too high')
print('Congratulations')
# user vs randint
import random
computer = random.randint(0,100)
while True:
try:
user = int(input(" Enter a number : "))
except (ValueError,NameError):
print(" Please enter a valid number ")
else:
if user == computer:
print(" Wow .. You win the game ")
break
elif user > computer:
print(" Too High ")
else:
print(" Too low ")
I think this can solve the issues.
In your code you want to check whether the user has input no or string since your not using int() in your input it will take input as string and furthur in your code it wont be able to check for <= condition
for checking input no is string or no
code:-
a = input ("Enter no")
try:
val = int(a)
print("Yes input string is an Integer.")
print("Input number value is: ", a)
except ValueError:
print("It is not integer!")
print(" It's a string")
You probably will have to learn how to do functions and write your own input function.
def my_input(prompt):
val = input(prompt)
if val.isdigit():
return val
else:
print('not a number')
# return my_input(prompt)
I'm trying to take user-input but I need the input to be an integer, AND be between 1 and 9. I tried putting "in range(1,10)" in a few places in the code but it didn't work. I need the program to keep asking the user for the right input until they give the correct input. So far I've only been able to make sure their input is an integer with he following code. I will be taking input by using int(input("...")), rather than using input("...").
while True:
try:
ui1 = int(input("Player 1, Your move. Select your move. "))
break
except ValueError:
print("You have to choose a number between 1 and 9")
continue
Add a check before the break and move the error message to the end of the loop.
while True:
try:
ui1 = int(input("Player 1, Your move. Select your move. "))
if 1 <= ui1 <= 9:
break
except ValueError:
pass
print("You have to choose a number between 1 and 9")
Why not just check isdigit() and in range ?
while True:
ui1 = input("Player 1, Your move. Select your move. ")
if ui1.isdigit() and int(ui1) in range(1,10):
break
print("You have to choose a number between 1 and 9")
# Continue code out of the loop
# beJeb
# Stack overflow -
# https://stackoverflow.com/questions/51202856/how-to-check-user-input-for-multiple-conditions-within-same-loop-or-function-in
# Our main function, only used to grab input and call our other function(s).
def main():
while True:
try:
userVar = int(input("Player 1, Your move. Select your move: "))
break
except ValueError:
print("Incorrect input type, please enter an integer: ")
# We can assume that our input is an int if we get here, so check for range
checkRange = isGoodRange(userVar)
# Checking to make sure our input is in range and reprompt, or print.
if(checkRange != False):
print("Player 1 chooses to make the move: %d" %(userVar))
else:
print("Your input is not in the range of 1-9, please enter a correct var.")
main()
# This function will check if our number is within our range.
def isGoodRange(whatNum):
if(whatNum < 10) & (whatNum > 0):
return True
else: return False
# Protecting the main function
if __name__ == "__main__":
main()
Note: I tested a couple inputs so I believe this should be enough to help you understand the process, if not please comment, message, etc. Also, if this answer helps you, please select it as answered to help others.
Let the number be the input you are taking from the user.
while(1): #To ensure that input is continuous
number = int(input())
if number>=1 and number<=10 and number.isdigit():
break #if the input is valid, you can proceed with the number
else:
print("Enter a valid Number")
The number can be used for further operations.
I'm very new to python and trying to write some code so that the user enters something. If it's an integer it's sorted into the Numbers list, if it's a string it goes into the String list.
I want to be able to find the mean of all the numbers that are in the list and print out the result.
And in the String section I want to be able to print out everything within the string and its length.
User types 'save' to exit and if input is valid that's caught.
Numbers = []
String = []
while(True):
user_input = input("What's your input? ")
if user_input == "save":
break
elif user_input.isdigit():
Numbers.append(user_input)
for i in range(len(Numbers)):
Numbers[i] = int(Numbers[i])
print(sum(Numbers)/len(Numbers)
elif isinstance(user_input, str):
String.append(user_input)
print(String)
print (len(String)-1)
else:
print("Invalid input.")
break
#use isalpha to check enterted input is string or not
#isalpha returns a boolean value
Numbers = []
String = []
while(True):
user_input = input("input : ")
if user_input == "save":
break
elif user_input.isdigit():
Numbers.append(int(user_input))
print(sum(Numbers)/len(Numbers))
elif user_input.isalpha():
String.append(user_input)
print(String)
print (len(String))
else:
print("Invalid input.")
break
There is good thing called statistics.mean:
from statistics import mean
mean(your_list)
You are using Length, which has not been defined. I think what you wanted was
print(sum(Numbers)/len(Numbers))
and you probably don't want it inside the loop, but just after it (although that might be another typo).
I found other more convenient way to produce the mean: Use statistics model and output the mean.
#import useful packages
import statistics
#Create an empty list
user_list = []
#get user request
user_input = input("Welcome to the average game. The computer is clever enough to get the average of the list of numbers you give. Please press enter to have a try.")
#game start
while True:
#user will input their number into a the empty list
user_number = input("Type the number you want to input or type 'a' to get the average and quit the game:")
#help the user to get an average number
if user_number == 'a':
num_average = statistics.mean(user_list)
print("The mean is: {}.".format(num_average))
break #Game break
else:
user_list.append(int(user_number))
print(user_list)
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