Python beginner here. Practicing user input control.
Trying to make user input loop to the beginning if anything but a whole number between 1 and 10 is used. Been trying for hours, tried using Try and Except commands but couldn't do it correctly. What am i doing wrong? Thank you.
Edit:
Thank you very much for your help everyone, however the problem is still not solved (but very close!) I'm trying to figure out how to loop back to the beginning if anything BUT a whole number is typed. Agent Biscuit (above) gave a great answer for floating numbers, but any word or letter that is typed still produces an error. I´m trying to understand how to loop when anything random (except whole numbers between 1 and 10) is typed. None of the above examples produced corrcct results. Thank you for your help
while True:
print("Enter a number between 1 and 10")
number = int(input())
if (number > 0) and (number < 10):
print("Thank you, the end.")
break
else number != (> 0 and < 10):
print("It has to be a whole number between 1 and 10.")
print("Please try again:")
I have identified some problems.
First, the input statement you are using would just raise an error if a float value is entered, because the int at the start requires all elements of the input to be a number, and . is not a number.
Second; your else statement. else is just left as else:, and takes no arguments or parameters afterwards.
Now, how to check if the number is not whole? Try this:
while True:
print("Enter a number between 1 and 10")
number = float(input())
if (number > 0) and (number < 10) and (round(number)==number):
print("Thank you, the end.")
break
else:
print("It has to be a whole number between 1 and 10.")
print("Please try again:")
This accepts a float value, but only accepts it if it is equal to a whole number, hence the (round(number)==number).
Hope that answers your question.
First of all, you can't use a condition in a else statement. Also, you need to use or operator instead of and if one of the conditions is acceptable.
So, your code needs to be like this
while True:
print("Enter a number between 1 and 10")
number = int(input())
if (number > 0) and (number < 10):
print("Thank you, the end.")
break
elif number < 0 or number >10:
print("It has to be a whole number between 1 and 10.")
print("Please try again:")
Thanks to ack (above) for pointing me to a useful link. By studying another thread, I found the solution. It may not be perfect code, but it works 100%:
while True:
try:
print("Enter a number between 1 and 10")
number = float(input())
if (number > 0) and (number < 10) and (round(number)==number):
print("Thank you, the end.")
break
else:
print("\n")
print("It has to be a whole number between 1 and 10.")
print("Please try again:")
print("\n")
continue
except ValueError:
print("It has to be a whole number between 1 and 10.")
print("Please try again:")
print("\n")
Related
I am trying to write a program as follows:
Python generates random multiplications (factors are random numbers from 1 to 9) and asks to the users to provide the result
The user can quit the program if they input "q" (stats will be calculated and printed)
If the user provides the wrong answer, they should be able to try again until they give the correct answer
if the user responds with a string (e.g. "dog"), Python should return an error and ask for an integer instead
It seems I was able to perform 1) and 2).
However I am not able to do 3) and 4).
When a user gives the wrong answer, a new random multiplication is generated.
Can please somebody help me out?
Thanks!
import random
counter_attempt = -1
counter_win = 0
counter_loss = 0
while True:
counter_attempt += 1
num_1 = random.randint(1, 9)
num_2 = random.randint(1, 9)
result = str(num_1 * num_2)
guess = input(f"How much is {num_1} * {num_2}?: ")
if guess == "q":
print(f"Thank you for playing, you guessed {counter_win} times, you gave the wrong answer {counter_loss} times, on a total of {counter_attempt} guesses!!!")
break
elif guess == result:
print("Congratulations, you got it!")
counter_win += 1
elif guess != result:
print("Wrong! Please try again...")
counter_loss += 1
Hi my Idea is to put the solving part in a function:
import random
counter_attempt = -1
counter_win = 0
counter_loss = 0
def ask(num1, num2, attempt, loss, win):
result = str(num1 * num2)
guess = input(f"How much is {num1} * {num2}?: ")
if guess == "q":
print(
f"Thank you for playing, you guessed {win} times, you gave the wrong answer {loss} times, on a total of {attempt} guesses!!!")
return attempt, loss, win, True
try:
int(guess)
except ValueError:
print("Please insert int.")
return ask(num1, num2, attempt, loss, win)
if guess == result:
print("Congratulations, you got it!")
win += 1
return attempt, loss, win, False
elif guess != result:
print("Wrong! Please try again...")
loss += 1
attempt += 1
return ask(num1, num2, attempt, loss, win)
while True:
num_1 = random.randint(1, 9)
num_2 = random.randint(1, 9)
counter_attempt, counter_loss, counter_win, escape = ask(num_1, num_2, counter_attempt, counter_loss, counter_win)
if escape:
break
Is that what you asked for?
Note that everything withing your while loop happens every single iteration. Specifically, that includes:
num_1 = random.randint(1, 9)
num_2 = random.randint(1, 9)
So you are, indeed, generating new random numbers every time (and then announcing their generation to the user with guess = input(f"How much is {num_1} * {num_2}?: "), which is also within the loop).
Assuming you only intend to generate one pair of random numbers, and only print the "how much is...?" message once, you should avoid placing those within the loop (barring the actual input call, of course: you do wish to repeat that, presumably, otherwise you would only take input from the user once).
I strongly recommend "mentally running the code": just go line-by-line with your finger and a pen and paper at hand to write down the values of variables, and make sure that you understand what happens to each variable & after every instruction at any given moment; you'll see for yourself why this happens and get a feel for it soon enough.
Once that is done, you can run it with a debugger attached to see that it goes as you had imagined.
(I personally think there's merit in doing it "manually" as I've described in the first few times, just to make sure that you do follow the logic.)
EDIT:
As for point #4:
The usual way to achieve this in Python would be the isdigit method of str:
if not guess.isdigit():
print('Invalid input. Please enter an integer value.')
continue # Skip to next iteration
An alternative method, just to expose you to it, would be with try/except:
try:
int(guess) # Attempt to convert it to an integer.
except ValueError: # If the attempt was unsuccessful...
print('Invalid input. Please enter an integer value.')
continue # Skip to next iteration.
And, of course, you could simply iterate through the string and manually ensure each of its characters is a digit. (This over-complicates this significantly, but I think it is helpful to realise that even if Python didn't support neater methods to achieve this result, you could achieve it "manually".)
The preferred way is isdigit, though, as I've said. An important recommendation would be to get yourself comfortable with employing Google-fu when unsure how to do something in a given language: a search like "Python validate str is integer" is sure to have relevant results.
EDIT 2:
Make sure to check if guess == 'q' first, of course, since that is the one case in which a non-integer is acceptable.
For instance:
if guess == "q":
print(f"Thank you for playing, you guessed {counter_win} times, you gave the wrong answer {counter_loss} times, on a total of {counter_attempt} guesses!!!")
break
elif not guess.isdigit():
print('Invalid input. Please enter an integer value.')
continue # Skip to next iteration
elif guess == result:
...
EDIT 3:
If you wish to use try/except, what you could do is something like this:
if guess == "q":
print(f"Thank you for playing, you guessed {counter_win} times, you gave the wrong answer {counter_loss} times, on a total of {counter_attempt} guesses!!!")
break
try:
int(guess)
except ValueError:
print('Invalid input. Please enter an integer value.')
continue # Skip to next iteration
if guess == result:
...
You are generating a new random number every time the user is wrong, because the
num_1 = random.randint(1, 9)
num_2 = random.randint(1, 9)
result = str(num_1 * num_2)
Is in the while True loop.
Here is the fixed Code:
import random
counter_attempt = 0
counter_win = 0
counter_loss = 0
while True:
num_1 = random.randint(1, 9)
num_2 = random.randint(1, 9)
result = str(num_1 * num_2)
while True:
guess = input(f"How much is {num_1} * {num_2}?: ")
if guess == "q":
print(f"Thank you for playing, you guessed {counter_win} times, you gave the wrong answer {counter_loss} times, on a total of {counter_attempt} guesses!!!")
input()
quit()
elif guess == result:
print("Congratulations, you got it!")
counter_win += 1
break
elif guess != result:
print("Wrong! Please try again...")
counter_loss += 1
I'm new to the coding world. I have a problem with adding up all of the users' input values, as I don't know how many there will be. Any suggestions?
This is how far I've gotten. Don't mind the foreign language.
import math
while(True):
n=input("PERSONS WEIGHT?")
people=0
answer= input( "Do we continue adding people ? y/n")
if answer == "y" :
continue
elif answer == "n" :
break
else:
print("You typed something wrong , add another value ")
people +=1
limit=300
if a > limit :
print("Cant use the lift")
else:
print("Can use the lift")
You don't need to import math library for simple addition. Since you did not mention that what error are you getting, so I guess that you need a solution for your problem. Your code is too lengthy. I have write a code for you. which has just 6 lines. It will solve your problem.
Here is the code.
sum = 0;
while(True):
n = int(input("Enter Number.? Press -1 for Exit: "))
if n == -1:
break
sum = sum+n
print(sum)
Explanation of the Code:
First, I have declared the variable sum. I have write while loop, inside the while loop, I have prompt the user for entering number. If user will enter -1, this will stop the program. This program will keep on taking user input until unless user type "-1". In the end. It will print total sum.
Output of the Code:
Here's something for you to learn from that I think does all that you want:
people = 0
a = 0
while True:
while True:
try:
n = int(input("PERSONS WEIGHT?"))
break
except ValueError as ex:
print("You didn't type a number. Try again")
people += 1
a += int(n)
while True:
answer = input("Do we continue adding people ? y/n")
if answer in ["y", "n"]:
break
print("You typed something wrong , add another value ")
if answer == 'n':
break
limit = 300
if a > limit:
print("Total weight is %d which exceeds %d so the lift is overloaded" % (a, limit))
else:
print("Total weight is %d which does not exceed %d so the lift can be operated" % (a, limit))
The main idea that was added is that you have to have separate loops for each input, and then an outer loop for being able to enter multiple weights.
It was also important to move people = 0 out of the loop so that it didn't keep getting reset back to 0, and to initialize a in the same way.
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
I'm currently a few weeks into my first programming course. The language is Python and the assignment was to write a program that will take two numbers from user input and provide the sum. If the sum is >100, print a message saying it's a big number and don't print the value. If the sum is <100, add the two numbers the input provides and print the sum value.
Here's my code for that which seems to fit what the assignment asked for:
print("Please enter a number between 1 and 100: ")
num1 = int(input())
if num1 > 99:
print("That number is greater than 100. Please try again.")
elif num1 < 1:
print("That number is less than 1. Please try again.")
print("Again, please type any number between 1-100")
num2 = int(input())
if num2 > 99:
print("That number is greater than 100. Please try again.")
elif num2 < 1:
print("That number is less than 1. Please try again.")
sum = num1 + num2
if sum > 100:
print("They add up to a big number")
elif sum < 100:
print("Sum of ", num1, " and ", num2, " is = ", sum)
With this code however, if I for example input '0' as a value for example, it'll print to try again but of course proceed to the next instruction of num2.
In every programming assignment, the instructor gives bonus points for going the extra mile and learning on your own how to somehow better the code, which I always try and achieve. In this example, I'm trying to make it so that if I for example as stated above input the value '0', it'll print to try again and then loop back to the first input instruction rather than proceeding to num2.
I'm not looking for someone to do my homework, but rather a step in the right direction. I've done some research and am not sure what works best here, but it seems like a while loop might work? I'm unsure how to start implementing it with my code already existing.
In such cases it's better to use boolean flags.
bool lock = true;
while(lock):
print("Please enter a number between 1 and 100: ")
num1 = int(input())
if num1 > 99:
print("That number is greater than 100. Please try again.")
elif num1 < 1:
print("That number is less than 1. Please try again.")
else:
lock = false
It'll make sure that till the time a valid input is not entered the loop iterates and asks the user to input the same number again and again.
You could repeat it for the second number too.
I am new to python and I am taking a summer online class to learn python.
Unfortunately, our professor doesn't really do much. We had an assignment that wanted us to make a program (python) which asks the user for a number and it determines whether that number is even or odd. The program needs to keep asking the user for the input until the user hit zero. Well, I actually turned in a code that doesn't work and I got a 100% on my assignment. Needless to say our professor is lazy and really doesn't help much. For my own knowledge I want to know the correct way to do this!!! Here is what I have/had. I am so embarrassed because I know if probably very easy!
counter = 1
num = 1
while num != 0:
counter = counter + 1
num=int(input("Enter number:"))
while num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)
There are a couple of problems with your code:
You never use counter, even though you defined it.
You have an unnecessary nested while loop. If the number the user inputs is even, then you're code will continue to run the while loop forever.
You are incorrectly using the else clause that is available with while loops. See this post for more details.
Here is the corrected code:
while True:
# Get a number from the user.
number = int(input('enter a number: '))
# If the number is zero, then break from the while loop
# so the program can end.
if number == 0:
break
# Test if the number given is even. If so, let the
# user know the number was even.
if number % 2 == 0:
print('The number', number, 'is even')
# Otherwise, we know the number is odd. Let the user know this.
else:
print('The number', number, 'is odd')
Note that I opted above to use an infinite loop, test if the user input is zero inside of the loop, and then break, rather than testing for this condition in the loop head. In my opinion this is cleaner, but both are functionally equivalent.
You already have the part that continues until the user quits with a 0 entry. Inside that loop, all you need is a simple if:
while num != 0:
num=int(input("Enter number:"))
if num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)
I left out the counter increment; I'm not sure why that's in the program, since you never use it.
Use input() and If its only number specific input you can use int(input()) or use an If/else statement to check
Your code wasn't indented and you need to use if condition with else and not while
counter = 1
num = 1
while num != 0:
counter = counter + 1
num = int(input("Enter number:"))
if num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)
Sample Run
Enter number:1
Odd 1
Enter number:2
Even 2
Enter number:3
Odd 3
Enter number:4
Even 4
Enter number:5
Odd 5
Enter number:6
Even 6
Enter number:0
Even 0
I am making a simple 'guess a number between one and ten' game. I have used some basic error handling and am printing the number generated by the random module for testing purposes.
However I would like to know if there is a less verbose way to write this.
This is the code:
import random
while True:
"""Variable declaration"""
number_of_attempts = 1
number = random.randrange (1,11)
print (number)
print("Time to play a guessing game! Muhahaha...")
"""Error handling and main game code/while loop"""
while True:
try:
guess = int(input("Guess a number between one and ten."))
except ValueError:
print("Input a whole number between one and ten silly!")
continue
if guess >= 1 and guess <= 10:
pass
else:
print("Input a number between one and ten silly!")
continue
if guess == number:
print("You were successful and it took you", number_of_attempts, "attempts!!!")
break
else:
print("Try again!")
number_of_attempts = number_of_attempts +1
"""Game Exit/Restart"""
play_again = input("Would you like to play again, y/n?")
if "y" in play_again or "yes" in play_again:
continue
else:
break
Thanks,
Ben
if guess >= 1 and guess <= 10:
Can be written as:
if 1 <= guess <= 10:
Also, your first conditional can simply be written as:
if not 1 <= guess <= 10:
print("Input a number between one and ten silly!")
continue
But this can also be put inside the try bit, saving you from writing continue twice:
try:
guess = int(input("Guess a number between one and ten."))
if not 1 <= guess <= 10:
print("Input a number between one and ten silly!")
continue
except ValueError:
print("Input a whole number between one and ten silly!")
continue
Finally your last conditional can simply be:
if play_again not in ('y', 'yes'):
break
The continue isn't needed.
You may also want to wrap this all up into a function as well, to get rid of those infinite while loops and to prevent you from using continue and break so much.
Why not put the actual conditions on the while loops so you don't have to hunt for breaks to understand the loops? It would make your code clearer and smaller.
if guess == number:
print("You were successful and it took you", number_of_attempts, "attempts!!!")
break
For instance if you put guess == number as the while loop conditional then the print would be the first thing after the loop. Initialize guess to -1 so it always works the first time. The play again if statement could also disappear into the loop conditional as well.