validate user input and loop until correct - python-3.x

I have looked on here for an idea in order to loop the user's invalid input and I haven't found one.
Ok, I know how to loop the first_number and second_number together but I am a bit confused on how to loop the separately if need be. So if the user inputs a bad second_number and loops that instead of the whole thing again.
I've attached the part I need help with (yes this is a school assignment):
def get_numbers():
first_number = 0.0
second_number = 0.0
while True:
try:
first_number = float(input("Please enter the first number: "))
second_number = float(input("Please enter the second number: "))
except ValueError:
print("Not a valid input, please try again.")
continue
return first_number, second_number

To use 1 loop, you may need to recognize the differences:
You use 2 simple variables for the results though you could use 1 list.
The input string is almost the same except for "first" and "second" words.
Concept:
First you want a list.
Then use a for loop to use "first", then "second" words.
Then use a while loop which processes the inputs and uses the list to extend with the replies. Use break to get out of the while loop after each good reply.
def get_numbers():
result = []
for item in ("first", "second"):
while True:
try:
number = float(input("Please enter the " + item + " number: "))
except ValueError:
print("Not a valid input, please try again.")
else:
result += [number]
break
return tuple(result)
Returning as a tuple as you have done.

First, you want to use two loops, one for each number, and break if the input is valid instead of continuing if it's invalid. Then you need to move the return statement to immediately following the second loop.
By the way, you can leave out the initial assignments to first_number and second_number (commented out below). Assigning them to float(input(...)) is enough.
def get_numbers():
#first_number = 0.0
#second_number = 0.0
while True:
try:
first_number = float(input("Please enter the first number: "))
break
except ValueError:
print("Not a valid input, please try again.")
while True:
try:
second_number = float(input("Please enter the second number: "))
break
except ValueError:
print("Not a valid input, please try again.")
return first_number, second_number

Related

Really basic python3 user input type

I want to ask a user for a number(among other things) and if they input anything other than an int, it should tell them to try again.
I'm still getting use to python syntax, what's the best way to do this?
excerpt below of what I tried:
try:
num = int(i)
except ValueError:
while type(num) != int:
num = input("Please input an actual number or q to quit: ")
while True:
num = input("Input a number. ")
if num.isdigit()==False:
print("Try again.")
else:
break
This should work unless if there's a negative value entered in which case you need to make a check if the first character is a - sign.

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

How to verify if input is not a letter or string?

I'm writing a basic program in IDLE with a menu choice with options from 1 to 4.
If a user input anything else then a number, it gives a ValueError: invalid literal for int() with base 10: 'a'
How can I check if the input is not a letter, and if it is, print a error message of my own?
def isNumber (value):
try:
floatval = float(value)
if floatval in (1,2,3,4):
return True
else:
return False
except:
return False
number_choice = input('Please choose a number: 1, 2, 3 or 4.\n')
while isNumber(number_choice) == False:
number_choice = input('Please choose a number: 1, 2, 3 or 4.\n')
else:
print('You have chosen ' + number_choice + '.\n')
This will check if the number is 1,2,3 or 4 and if not will ask the user to input the number again until it meets the criteria.
I am slightly unclear on whether you wish to test whether something is an integer or whether it is a letter, but I am responding to the former possibility.
user_response = input("Enter an integer: ")
try:
int(user_response)
is_int = True
except ValueError:
is_int = False
if is_int:
print("This is an integer! Yay!")
else:
print("Error. The value you entered is not an integer.")
I am fairly new to python, so there might very well be a better way of doing this, but that is how I have tested whether or not input values are integers in the past.
isalpha() - it is a string method which checks that whether a string entered is alphabet or words(only alphabets, no spaces or numeric) or not
while True:
user_response = input("Enter an integer : ")
if user_response.isalpha():
print("Error! The value entered is not an integer")
continue
else:
print("This is an integer! Yay!")
break
This program is having infinite loop i.e. until you enter an integer this program will not stop. I have used break and continue keyword for this.

showing result of try except integer check as a string

I need a function to check that different user input variables are integers.
The results should be confirmed to the user at the end.
The check works in that it keeps looping until integer is typed in,
but cannot get the results to display...
def chkint(msg):
while True:
try:
n = input(msg)
return(int(n))
except ValueError:
print("Please enter an actual integer.")
number1 = input (chkint("Please enter first value:"))
number2 = input (chkint("Please enter second value:"))
results = (number1, number2)
print ("I have accepted: " + str (results))
No answer, so I just played about with this and hey presto, it works...
def chkint(msg):
while 1:
try:
n = input(msg)
return(int(n))
except ValueError:
print("Please enter an integer.")
number1 = chkint("Please enter first value:")
number2 = chkint("Please enter second value:")
results = [number1, number2]
print ("I have accepted: " + str (results))
Casting it to int() in a try: block is a good way to check a number. In your original attempt you were asking for an input whose message relied on further input.
Simplified version of the mistake:
def getMessage():
return input() # this asks the user what to ask the user for
input(getMessage()) # this waits for getmessage to finish before asking the user
Removing the input() statements was the easiest fix, as you did.
But a more readable fix would be to make chkint(msg) do nothing but return true or false based on whether or not the string was a number, like this
def chkint(msg): # returns true if the string can be converted, false otherwise
try:
int(msg)
except ValueError:
return False
return True

Resources