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!
Related
I am trying to create a function that would take a user inputted number and determine if the number is an integer or a floating-point depending on what the mode is set to. I am very new to python and learning the language and I am getting an invalid syntax error and I don't know what to do. So far I am making the integer tester first. Here is the code:
def getNumber(IntF, FloatA, Msg, rsp):
print("What would you like to do?")
print("Option A = Interger")
print("Option B = Floating Point")
Rsp = int(input("What number would like to test as an interger?"))
A = rsp
if rsp == "A":
while True:
try:
userInput = int(input("What number would like to test as an interger"))
except ValueError as ve:
print("Not an integer! Try again.")
continue
else:
return userInput
break
The problem with the code you shared is :
The syntax error you mentioned is probably because the except clause has to be at the same indentation level as try, and same for if and else of the same if/else clause. All the code in the function should be indented 1 level too. Python requires all this to identify blocks of code.
You don't need to give 4 arguments to the getNumber() function if you're not using them. This isn't really a problem, but you'll have to pass it some 4 values each time you call it (for example getNumber(1,2,3,4) etc...) to avoid missing argument errors; and these won't matter because you're not doing anything with the given values inside the function - so it's a little wasted effort. I rewrote it in the example below so that you aren't dealing with more variables than you need - it makes the code clearer/simpler.
You also don't need break after a return statement because the return will exit the enitre function block, including the loop.
Try this and see if it makes sense - I've changed a lot of the code :
def getNumber():
while True:
try:
userInput = int(input("What number would like to test as an integer ? "))
return userInput
except ValueError as ve:
print("Not an integer! Try again.")
continue
print("What would you like to do?")
print("Option A = Interger")
print("Option B = Floating Point")
chosen_option = input()
if chosen_option == 'A':
integer_received = getNumber()
print(integer_received, "was an int !")
else:
print("You did not choose 'A' or 'B'")
To determine whether a number is a float or integer, you can use this approach
float is nothing but the integer with floating-point(.).
to determine this we first need to convert it to string and find does it contain a point or not.
number = input("Enter a numbeer\n")
if number.find(".") == -1:
# find will return -1 when the value is not in string
print("it is integer")
else:
print("it is float")
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))
Either I'm not using the right search string or this is buried deep within the interwebs. I know we aren't supposed to ask for homework answers, but I don't want the code answer, I want to know where to find it, cause my GoogleFu is busted.
Assignment is to create a program that will roll two 6-sided dice n times, with n being user-defined, between 1 and 9. The program then displays the results, with "Snake Eyes!" if the roll is 1-1, and "Boxcar!" if the roll is 6-6. It also has to handle ValueErrors (like if someone puts "three" instead of "3") and return a message if the user chooses a number that isn't an integer 1-9.
Cool, I got all that. But he also wants it to ask the user if they want to save the output to a text file. Um. Yeah, double-checked the book, and my notes, and he hasn't mentioned that AT ALL. So now I'm stuck. Can someone point me in the right direction, or tell me what specifically to search to find help?
Thanks!
Check out the input function:
https://docs.python.org/3.6/library/functions.html#input
It will allow you to request input from a user and store it in a variable.
You can do something like this to store your final output to a text file.
def print_text(your_result):
with open('results.txt', 'w') as file:
file.write(your_result)
# Take users input
user_input = input("Do you want to save results? Yes or No")
if(user_input == "Yes"):
print_text(your_result)
I hope this helps
Well, it's not pretty, but I came up with this:
def print_text():
with open('results.txt', 'w') as file:
file.write(str(dice))
loop = True
import random
min = 1
max = 6
dice = []
while loop is True:
try:
rolls = int(input("How many times would you like to roll the dice? Enter a whole number between 1 and 9: "))
except ValueError:
print("Invalid option, please try again.")
else:
if 1 <= rolls <= 9:
n = 0
while n < rolls:
n = n + 1
print("Rolling the dice ...")
print("The values are:")
dice1 = random.randint(min, max)
dice2 = random.randint(min, max)
dice.append(dice1)
dice.append(dice2)
print(dice1, dice2)
diceTotal = dice1 + dice2
if diceTotal == 2:
print("Snake Eyes!")
elif diceTotal == 12:
print("Boxcar!")
else: print("Invalid option, please try again.")
saveTxt = input("Would you like to save as a text file? Y or N: ")
if saveTxt == "Y" or saveTxt == "y":
print_text()
break
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
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)")