This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 14 days ago.
i'm new in python
and for practice i make this codes but i have a problem :when you choose a number more than 100 it says you entered a wrong number and you must enter another number then if you enter a right number you wont get the awnser
this is outout
please enter a number between 0 and 100 =>123
you have entered a number more than 100 or less than 0 !
so please enter a number between 0 and 100 =>12
and nothing !!!
but if you enter a wrong number for two times or more it will work perfectly
this is my code
print("welcome to or simple test")
def number_choosing_1():
number_1=int(input("please enter a number between 0 and 100 "))
if 0<number_1 and number_1<100 and number_1%2==0:
print("the number you have entered is even ")
elif 0<number_1 and number_1<100 and number_1%2==1:
print("you have entered a odd number ")
else :
if number_1>100 or number_1<0:
wrong_number_choosing_1()
elif 0<number_1 and number_1<100:
number_choosing_1()
def number_choosing_2():
number_1=int(input("that's it now fore make me sure reenter your number "))
if 0<number_1 and number_1<100 and number_1%2==0:
print("the number you have entered is even ")
elif 0<number_1 and number_1<100 and number_1%2==1:
print("you have entered a odd number ")
else :
if number_1>100 or number_1<0:
wrong_number_choosing_1()
elif 0<number_1 and number_1<100:
number_choosing_1()
def wrong_number_choosing_1():
number_1=int(input("""you have entered a number more than 100 or less than 0 !
so please enter a number between 0 and 100 """))
while number_1>100 or number_1<0:
number_1=int(input(" come on again !! please enter a number between 0 and 100 "))
if 0<number_1 and number_1<100:
number_choosing_2()
number_choosing_1()
any help appreciated .
just use a loop to ask for an input until a valid answer is given, then break the loop
while True:
number = int(input("Enter a number between 0 and 100: "))
if 0 <= number <= 100:
break
else:
print("Wrong number, try again")
# then check if the number is even or odd
parity = "odd" if number % 2 else "even"
print(f"The number {number} is {parity}")
Related
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 4 months ago.
I am coding a guessing game where the user inputs an integer between 1 and 100 to try and guess the correct number (26). I have to count the number of guesses the user takes to get the correct number. I want to use try and except blocks to allow the user to keep trying until they guess it right.
Right now, my code only allows the user to input one ValueError. I don't want this, I want to keep inputting until I guess the number. Attached is my code. Any help is greatly appreciated!
ex:
I want to input errors ("a", 4.20, "hello") and still have them count as guesses until I guess the number
"a" > 4.20 > "hello" > 26 => Guessed it in 3 tries
def guess(n):
secret_number = 26
if n < secret_number:
return print("Too low!")
elif n > secret_number:
return print("Too high!")
def try_exp():
try:
n = int(input("What is your guess? "))
return n
except ValueError:
n = int(input("Bad input! Try again: "))
return n
def counter():
print("Guess the secret number! Hint: it's an integer between 1 and 100... ")
n = try_exp()
i = 0
while n != 26:
guess(n)
i += 1
n = try_exp()
print(f"You guessed it! It took you {i} guesses.")
counter()
Instead of making try_exp like that, you can use a while loop that will first ask for input, and if the input is valid, then it will break out of the while loop. This is one way to implement it:
def try_exp():
first_input = True
while True:
try:
if first_input:
n = int(input("What is your guess? "))
return n
else:
n = int(input("Bad input! Try again: "))
return n
except ValueError:
first_input = False
In this, we go through an infinite loop, and we have a flag that designates whether it is the first guess or if they have already guessed before. If it is the first guess, we ask them for input, and if it is the second guess, we tell them that they gave incorrect input and ask for more input. After receiving correct input, the function returns n. If the input is incorrect which is when it is not an integer, we set first_input as false. Then, the while loop loops again. It will keep on waiting for input until they submit an integer.
I have to create a program that generates a five digit number which a user has to guess by getting different clues like how many digits they have correct and how many are in the correct position.
The function i have written out now it to find the unique letters aka the letters that each string has in common. Now this works if the length is exactly 5 letters. But i need to have a statement written out (this is too short or long) when the user exceeds a length of 5 or is lower than 5. It says this but counts what is right and adds it to the previous number. This shouldnt be there. Also the numbers shouldnt add only state the right amount in that attempt. Heres it visually:
rannum remove : 24510
enter number: 24511
4
enter number: 12
this is too short
6
heres the code:
while not userguess:
guess = str(input("enter number: "))
if len(guess) < 5:
print("this is too short")
for i in list(set(secretString) & set(guess)):
uniquedigits_found += 1
print(uniquedigits_found)
is there anyway to fix this problem?
You should try resetting your unique digits variable in each iteration of the while loop, and separate the for loop to check matching digits in an else statement:
while not userguess:
uniquedigits_found = 0
guess = str(input("enter number nerd: "))
if len(guess) < 5:
print("this is too short")
elif len(guess) > 5:
print("this is too long")
else:
for i in list(set(secretString) & set(guess)):
uniquedigits_found += 1
print(uniquedigits_found)
Enter an integer between 1 to 10: 11
You did not enter a number between 1 and 10!!!
Please, try again.
Enter an integer between 1 to 10: ten
You did not enter an integer!!!
Please, try again.
Enter an integer between 1 to 10: .3
You did not enter an integer!!!
Please, try.
Enter an integer between 1 to 10: 0
Oops, you entered zero.
Please, try again.
Enter an integer between 1 to 10: 3
The Reciprocal of your number is 0.33333333333333333.
here is what i have right now for the first part, its working but i cant seem to figure out the rest
try:
num = int(input("Enter a number between 1 to 10: "))
if num in range(1, 11):
print(num)
else:
print("You did not enter a number between 1 and 10!!!\nPlease, try again.")
except ValueError:
print("You did not enter an integer between 1 to 10. Try again")
move the conversion to int into the if/else area, use a try/except to handle if they enter a string, then search from a list of strings that could be 'ten" being entered. I am sure there are more elegant solutions...
VariantsOfTen=['ten','Ten','tEn','TEn','tEN','teN','TEN']
num = input("Enter a number between 1 to 10: ")
try:
if int(num) in range(1, 11):
print(num)
else:
print("You did not enter a number between 1 and 10!!!\nPlease, try again.")
except:
if (num in VariantsOfTen):
print('that is ten, but not really..')
else:
print('you entered a string, but nothing useful')
Iv been asked to write a program wich asks the user to enter an integer that is over 500. Then I need to work out the square root of that number and display it to 2 decimal places.
So far I have:
import math
mumber= int(input("Please enter a number over 500")
if number<500:
print ("That's too low")
else:
print (math.sqrt(number))
Everything works but where do I place the print(round(number,2)) ?
EDIT:
I typed the code, so YES the indenting is wrong.
You could do something like this:
import math
number = -1
while number < 500:
number= int(input("Please enter a number over 500: "))
if number < 500:
print("Number entered is too low. Please enter a number that is larger than 500.")
print(round(math.sqrt(number), 2))
Basically, it keeps asking for user input until the value is larger than 500.
If you later want to add checking to not allow float numbers to be entered but only have them enter integer values you can do this by just changing the loop a little:
# Same as before
while number < 500:
try:
number= int(input("Please enter a number over 500: "))
except ValueError:
print("An integer value was not entered.")
# Same as before
Credits to u/e4c5 for the round(math.sqrt(number), 2))
Make sure 'mumber' is fixed to say 'number' and instead of
print(math.sqrt(number))
use
print(round(math.sqrt(number),2))
I created a Mastermind code and when I attempt to run it on my Mac it just says "logout". If anyone knows why, that would be extremely helpful! Here is the code:
def masterMind():
number = random.ranint(10000,99999) #the computer chooses 5 random numbers
userGuess = raw_input("Guess my 5 digit password:") #asking the user to input their guess
tries = 10 # telling the computer number of tries the user is allowed
while tries < 0: # 10 attempts is the maximum amount
if number != userGuess: # if the computer's password does not equal the user's guess then it equals to one attempt
tries += 1
userGuess = input("Guess my 5 digit password:")
else: #if the user and the computer's answers align
print "Win: ", userGuess
print number
tries = 10
while tries < 0:
will never enter the loop.
You may want to reverse the sense of the comparison, using > instead.
You'll also need to decrement tries within the loop rather than incrementing it.
more "pythonic" (2.x) way. fixes answers like "00000", fixes int to str compair.
def masterMind():
number = "%05d" % random.randint(0, 99999) #the computer chooses 5 random numbers
for tries in range(10):
user_guess = raw_input("Guess my 5 digit password:") #asking the user to input their guess
if number == user_guess:
print "Win on the %d try" % (tries + 1)
break
print "answer was:", number