showing result of try except integer check as a string - 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

Related

How do I continue looping, even through an error? Python

I have two conditions in my story using the question that I made to ask the users.
The first condition is true and second condition is false. In the first condition, if it's true, I want the program to finish. In the second condition, if it's false, I want to loop back to the question that I asked.
I have the following code, but so far it will loop back if the first is true and the second is false.
Any ideas?
invalid = ValueError
def age():
user_input = input("Enter your Age")
try:
val = int(user_input)
print("Input is an integer number. Number = ", val)
except ValueError:
print("No.. input is not a number. It's a string")
while invalid:
age()
I'd make things easier and just use a boolean as your continuation flag, rather than the ValueError:
ask_again = True
def age():
user_input = input("Enter your Age")
try:
val = int(user_input)
print("Input is an integer number. Number = ", val)
ask_again = False
except ValueError:
print("No.. input is not a number. It's a string")
while ask_again:
age()
Does that look like what you want? Happy Coding!
The simplest way to execute a while loop is to just use while True and then break from the loop once the condition is satisfied
def age():
while True:
try:
val = int(input("Enter your Age"))
print("Input is an integer number. Number = ", val)
break
except ValueError:
print("No.. input is not a number. It's a string")
age()

How to identify operators using isdigit in python?

I am making a program to check if the input given by user is positive or negative.
I have used isdigit to print "wrong choice/input".If user inputs a string.
Program is working fine... but one block is not working that is of negative number.
Whenever I give a negative value it shows wrong choice because isdigit checks for integers in a string but not symbols.
How can I fix this?
You could first check the first character and if it's a minus sign only apply isdigit() to the rest of the string, ie:
# py2/py3 compat
try:
# py2
input = raw_input
except NameError:
# py3
pass
while True:
strval = input("please input a number:").strip()
if strval.startswith("-"):
op, strval = strval[0], strval[1:]
else:
op = "+"
if not strval.isdigit():
print("'{}' is not a valid number".format(strval))
continue
# now do something with strval and op
But it's much simpler to just try and pass strval to int(), which will either return an integer or raise a ValueError if the string is not a valid representation of an integer:
# py2/py3 compat
try:
# py2
input = raw_input
except NameError:
# py3
pass
while True:
strval = input("please input a number:")
try:
intval = int(strval.strip())
except ValueError:
print("'{}' is not a valid number".format(strval))
continue
# now do something with intval

validate user input and loop until correct

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

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.

Resources