"Try" and "Except" in my program (python) - python-3.x

while True: #code should only allow integers to be inputed
try:
rolls = int(input("Enter the number of rolls: "))
break
except:
print("You did not enter a valid Integer")
output works for characters like "b" and "d"
but when I put a zero in, I still get the ZeroDivisionError
I want the code to only allow an integer.
later on in the code I tried this
if rolls <= 0:
print("You must enter at least one roll")
print()
but it doesnt stop the code from running and the error still pops up.

There is no division in the posted code and it will not throw a ZeroDivisionError.
The exception is likely thrown when xyz / rolls is done later (outside that try/catch), when rolls evaluates to 0.
Fix the logic so as to not even allow such invalid division to occur! Maybe "0" means to exit the game? Or maybe "0" means that the user should be asked for another roll?
FWIW, here is modified code to read input that won't accept "0":
while True: #code should only allow integers to be inputed
try:
rolls = int(input("Enter the number of rolls: "))
if rolls > 0:
break
except:
pass # don't do anything here, because we print below for
# exceptions and when the if guarding the break failed.
print("You must enter a valid roll (> 0)")

Related

How can I not allow letters, and only allow numbers in an input on python 3?

I am a beginner. I'm making a survey, and one of the questions asks the users age. How can I make it so that if the user enters a letter or symbol, it shows a print() message?
The issue seems to be that the computer reads the first if statement of "if age < 10:" and then sends an error message in the terminal if I enter a string.
This is the code right now, I want it so that if the user inputs a letter(s) or symbol(s), it sends a print() message, and asks for the input again, is that possible?
c = 3
while c == 3:
age = int(input('How old are you (enter a number)? '))
if age < 10:
print("Wow, you're quite young!")
break
elif age > 60 and age <= 122:
print("Wow, you're quite old!")
break
elif age > 122:
print('Amazing! You are the oldest person in history! Congrats!')
break
elif age >= 14 and age <= 18:
print('Really? You look like a college student!')
break
elif age >= 10 and age <= 13:
print('Really? You look like a 10th grader!')
break
elif age > 18 and age <= 60:
print('Really? No way! You look younger than that, could have fooled me!')
break
Define each operation in your survey as a different function. Then you can use a statement like this one:
try:
int(input_variable)
except ValueError:
function()
To check if they gave you an integer, and if they didn't they have to input again. You seem to be a beginner so I can answer questions if you have any.
for simple solution, simply loop until integers are received.
while True:
try:
age = int(input('How old are you (enter a number)? '))
except ValueError:
print('input should be integer!')
continue
break

Creating a continues loop with try | Python3

I'm trying to receive user input that has to be between 2 and 10 and then return a message if the input is in fact between 2 and 10.
What I'm struggling with:
if the user inputs something other than a number, I get a ValueError
How I'm trying to resolve it:
I use the try except finally method.
Issue I'm unable to resolve:
When the user inputs a letter, the first time around, it will bring up the try: but if the user then inputs a letter a second time, it will give an error once again.
How can I make this loop so the user can give as many wrong answers as he wants and get it to it's final destination once he inputs a value between 2 and 10?
My code so far
try:
user_input = input("give a number between 2 and 10: ")
while 10 < int(user_input) or int(user_input) < 2:
user_input = input("No no, a number between 2 and 10!: ")
except ValueError:
print(f"That wasn\'t a number! Try again.")
user_input = input("give a number between 2 and 10: ")
while 10 < int(user_input) or int(user_input) < 2:
user_input = input("No no, a number between 2 and 10!: ")
finally:
print("Good, welcome to the dark side.")
Would appreciate the help!
Thanks.
This example works, while making minimal changes to your code:
while True:
try:
user_input = input("give a number between 2 and 10: ")
while 10 < int(user_input) or int(user_input) < 2:
user_input = input("No no, a number between 2 and 10!: ")
break
except ValueError:
print(f"That wasn\'t a number! Try again.")
print("Good, welcome to the dark side.")
The main differences are removing the while loop from within the except and the finally portion, and using a while True loop to continue asking the question until the conditions are met that lead to the break (i.e. user enters a value between 2 and 10, inclusive). My test of this code works.

finding largest and smallest number in python

I am very new to programming, please advise me if my code is correct.
I am trying to write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number.
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == 'done':
break
try:
fnum = float(num)
except:
print("Invalid input")
continue
lst = []
numbers = int(input('How many numbers: '))
for n in range(numbers):
lst.append(num)
print("Maximum element in the list is :", max(lst), "\nMinimum element in the list is :", min(lst))
Your code is almost correct, there are just a couple things you need to change:
lst = []
while True:
user_input = input('Enter a number: ')
if user_input == 'done':
break
try:
lst.append(int(user_input))
except ValueError:
print('Invalid input')
if lst:
print('max: %d\nmin: %d' % (max(lst), min(lst)))
Also, since you said you're new to programming, I'll explain what I did, and why.
First, there's no need to set largest and smallest to None at the beginning. I actually never even put those values in variables because we only need them to print them out.
All your code is then identical up to the try/except block. Here, I try to convert the user input into an integer and append it to the list all at once. If any of this fails, print Invalid input. My except section is a little different: it says except ValueError. This means "only run the following code if a ValueError occurs". It is always a good idea to be specific when catching errors because except by itself will catch all errors, including ones we don't expect and will want to see if something goes wrong.
We do not want to use a continue here because continue means "skip the rest of the code and continue to the next loop iteration". We don't want to skip anything here.
Now let's talk about this block of code:
numbers = int(input('How many numbers: '))
for n in range(numbers):
lst.append(num)
From your explanation, there is no need to get more input from the user, so none of this code is needed. It is also always a good idea to put int(input()) in a try/except block because if the user inputs something other than a number, int(input()) will error out.
And lastly, the print statement:
print('max: %d\nmin: %d' % (max(lst), min(lst)))
In python, you can use the "string formatting operator", the percent (%) sign to put data into strings. You can use %d to fill in numbers, %s to fill in strings. Here is the full list of characters to put after the percent if you scroll down a bit. It also does a good job of explaining it, but here are some examples:
print('number %d' % 11)
x = 'world'
print('Hello, %s!' % x)
user_list = []
while True:
user_input = int(input())
if user_input < 0:
break
user_list.append(user_input)
print(min(user_list), max(user_list))

Why does this code not let me just check for an invalid input

This is not the whole code but the code I am experimenting with to get a solution for the whole code. I also need an answer for dealing with invalid string inputs.
def menu_payment():
burger_count= (input("Please input the number of Racquet Burgers (Cheese Burgers) you would like: "))
if (burger_count !=int) or (burger_count<=0):
print("You must eneter a positive whole number for your order. Please try again.")
menu_payment()
Try doing this:
def menu_payment():
burger_count = input("How many burgers would you like:")
try:
burger_count = int(burger_count)
valid_number = 1
except:
print(burger_count, " is not a valid number")
valid_number = 0
if valid_number == 1 and burger_count > 0:
print ("I will get your burgers right away")
else:
print("Please put a valid number and no negetives")
The issue with checking for a valid string is coming from your if statement. I would suggest first, checking if the value is an int, then check the value for it. That is the easiest and least confusing way to fix that issue.
Input will always convert the user input to string. Therefore, entering "1" is the string of "1", not the integer.
You could try wrapping your input with an int function like:
burger_count = int(input("Please input the number of Racquet Burgers (Cheese Burgers) you would like: "))
However, this would throw a ValueError if anything other than an integer is entered.
Also, I don't think checking the variable type works like that. You can do something like:
if type(burger_count) is not int:
<do something>
Probably super inefficient (pre coffee scripting is bad) but here's how I would handle this:
def menu_payment():
while True:
try:
burger_count = int(input("burgers: "))
except ValueError:
print("You must eneter a number for your order. Please try again.")
continue
else:
if burger_count <= 0:
print("You must eneter a number for your order. Please try again.")
continue
else:
return burger_count

Clashing Strings and Integers

I'm having some trouble, I've finished this part of the program, and it works as planned, it stores the variables and checks all the validations successfully, but I need it to validate so that only digits can be entered. As soon as you press a alpha key, the program crashes.
I know I need to use selection.isdigit somewhere, I have tried it in a few different places, but when I do put it in what seems like the right place, the program crashes because isdigit only works with strings, and given the numeric validations in the program, the program crashes when they try and work with strings. Could someone help me out?
while True:
if amountwanted > 0:
selection = int(input("What flavour pizza would you like? (1-12): "))
if selection < 1 or selection > 12:
print("You must enter a pizza between 1 and 12")
print("")
else:
if selection <= 7:
orderedstandardpizzas.append(selection)
else:
orderedgourmetpizzas.append(selection)
amountwanted = amountwanted - 1
else:
break
Your use of int() throws the error, as it will only accept strings that can be interpreted as numbers.
You could catch the exception instead of checking each character in the input:
try:
selection = int(input("What flavour pizza would you like? (1-12): "))
except ValueError:
print "You must enter a number!"
break
The above snippet replaces your old selection = ... line, which has been indented 4 more spaces to match the new try/except block I inserted. The full code ends up like this:
while True:
if amountwanted > 0:
try:
selection = int(input("What flavour pizza would you like? (1-12): "))
except ValueError:
print "You must enter a number!"
break
if selection < 1 or selection > 12:
print("You must enter a pizza between 1 and 12")
print("")
else:
if selection <= 7:
orderedstandardpizzas.append(selection)
else:
orderedgourmetpizzas.append(selection)
amountwanted = amountwanted - 1
else:
break
Try this:
selection = raw_input("What flavour pizza would you like? (1-12): ");
if (selection.isdigit())
numSelection = int(selection);
if (numSelection < 1 or numSelection > 12:
// carry on
else:
// else case
else:
//print error message. Break out of loop here if required.
Consider the line
selection = int(input("What flavour pizza would you like? (1-12): "))
The input(...) function returns a string based on the user's input; this is then converted to an integer via int(...). [As others have pointed out, input in 3.x is the equivalent of raw_input on 2.x.]
So you have essentially two choices. First, you could treat the non-digit input as an actual error, which you could catch, and use continue to go back to the start of the loop in case of an error:
try:
selection = int(input("What flavour pizza would you like? (1-12): "))
except ValueError:
print "Error message"
continue
This is probably the most appropriate and pythonic strategy.
Conversely, you could check that the input is indeed made of digits, though it's a little more complicated than that, as the current version allows whitespace before and after, so you could do something like
string_selection = input("What flavour pizza would you like? (1-12): ")
if not string_selection.strip().isdigit():
continue
selection = int(string_selection)
But this is more complicated!

Resources