I'm new to python and am trying to check if startmiles and endmiles are input as integer only and gallons are input as float. When I enter alpha the program crashes. Thank You
#!/usr/bin/env python
import os
import sys
import subprocess
import datetime
clear = lambda: os.system('clear')
clear()
t = datetime.datetime.now()
from time import gmtime, strftime
strftime("%a, %d %b %Y %X +0000", gmtime())
today = strftime("%a, %d %b %Y ")
print(today,'\n')
def main():
startmiles = input("Enter Your Start Miles = ")
endmiles = input("Enter Your Ending Miles = ")
gallons = input("Enter Your Gallons = ")
mpg = (int(endmiles) - int(startmiles)) / float(gallons)
print("Miles Per Gallon =", round(mpg, 2))
answer = input("\n Go Again Y or n ").lower()
if answer == 'y': print('\n'), main()
if answer != 'y': print('\n Thank You Goodbye')
if __name__=="__main__":
main() # must be called from last line in program to load all the code
Convert your inputs to int/float as soon as they are entered, wrapped in a try/except block in a loop to catch exceptions and immediately prompt again for more input:
while True:
try:
startmiles = int(input("Enter Your Start Miles = "))
break
except ValueError:
print('that is not an integer, please try again')
Or just wrap your final calculation in a try/except:
try:
mpg = (int(endmiles) - int(startmiles)) / float(gallons)
except ValueError:
print('some error message')
But this way you can't easily ask for more input, and you don't know exactly which value caused the error.
In Python 2.x the input should result in an integer anyways, unless you use raw_input. It looks like your mpg variable is taking the integer of the endmiles anyways.
In Python 3.x
startmiles = int(input("Enter Your Start Miles = "))
It sounds like you're saying certain characters crash the program, which means you need to do some exception handling. See this question response for more detail, but you need to find a way to handle your exceptions instead of crashing. Here's an example below forcing proper entry of the variable.
while True:
try:
# Note: Python 2.x users should use raw_input, the equivalent of 3.x's input
age = int(input("Please enter your age: "))
except ValueError:
print("Sorry, I didn't understand that.")
#better try again... Return to the start of the loop
continue
else:
#age was successfully parsed!
#we're ready to exit the loop.
break
if age >= 18:
print("You are able to vote in the United States!")
else:
print("You are not able to vote in the United States.")
Related
I am new to Python programming. Following is the code written and it works fine when I print any numeric digit and give me the desired result as expected but the problem comes when I enter string (anything other than integer/float) instead of giving me just the except statement, it also gives me an error which I don't want. So, what I want is when a user enter anything other than numeric digits, he should be prompted with a message i.e., "Invalid input. Enter a number please" instead of an error which I am getting after the except print statement in the end. Please help.
hours_string = input("Enter Hours: ")
rate_string = input("Enter Rate: ")
try:
hours_float = float(hours_string)
rate_float = float(rate_string)
except:
print("Invalid input. Enter a number please.")
result = hours_float * rate_float
print("Pay",result)
This is the error I am getting. If I enter string, I should simply get an except statement. That's it. Not any other error. How can I accomplish to get there?
Enter Hours: 9
Enter Rate: entered string by mistake
Invalid input. Enter a number please.
Traceback (most recent call last):
File "<string>", line 9, in <module>
NameError: name 'rate_float' is not defined
For a particular Error you can do a particular Exeption like in the Code below. Also note that each question is in a whileloop that you need to acomplish the task before you get to the next one.
while True:
try:
hours_string = input("Enter Hours: ")
hours_float = float(hours_string)
except ValueError:
print("Invalid input. Enter a number please.")
else:
break
while True:
try:
rate_string = input("Enter Rate: ")
rate_float = float(rate_string)
except ValueError:
print("Invalid input. Enter a number please.")
else:
break
result = hours_float * rate_float
print("Pay",result)
hours_float = None
rate_float = None
while hours_float is None:
hours_string = input("Enter Hours: ")
try:
hours_float = float(hours_string)
except ValueError:
print("Invalid input. Enter a number please.")
while rate_float is None:
rate_string = input("Enter Rate: ")
try:
rate_float = float(rate_string)
except ValueError:
print("Invalid input. Enter a number please.")
result = hours_float * rate_float
print("Pay", result)
In the while loop we repeatedly ask user for input, while they don't enter a valid number, separately for hours and rate.
Valid input changes the initially set None value to something else, which finishes the corresponding loop.
Since this is a expected situation and it can be treated as a test I would recommend instead of trying to execute the operation with wathever input the user provided you could ask the user for the input and while it is not an integer you ask for the input again.
def get_input(name, var_type):
userin = None
while userin is None:
userin = input(f'Input {name}: ')
try:
userin = var_type(userin)
except ValueError:
print(f'{name} must be {str(var_type)}, not {str(type(userin))}')
userin = None
return userin
hours = get_input('hours', int)
rate = get_input('rate', float)
result = hours * rate
print('Pay', result)
The function get_input tries to cast the input input value to the type you want and if it is not as desired it will keep asking until the type matches.
I need help with this code I am trying to apply, a short time ago I ran a bmi calculator in index and now I am trying to update that code with exception handling. So far the portions don't give me errors they just run strangely together. For example, when it prompts "Enter the user's name or '0' to quit" it doesn't actually end the process it continues on to the exception process. Can someone help me write this more efficiently. here is my code this is updated, the issue I am specifically having now is the program is not terminating when the user enters '0':
def bmi_calculator():
end = False
print("Welcome to the BMI Calculator!")
while end == False:
user = input("Enter student's name or '0' to quit: ")
if user == "0":
print("end of report!")
end = True
else:
print("Lets gather your information,", user)
break
flag='yes'
while flag != 'no':
#Exception block for catching non integer inputs
try:
#Prompting user to input weight
weight = int(input('Enter your weight in pounds : '))
if weight == 0:
raise ValueError
except ValueError:
print ('Oops!! Kindly enter non-zero numbers only.')
flag = input('Do you want to try again? yes/no : ')
continue
try:
#Prompting user to input height
height = float(input('Enter your height in inches : '))
if height == 0:
raise ValueError
except ValueError:
print ('Oops!! Kindly enter non-zero numbers only.')
flag = input('Do you want to try again? yes/no : ')
continue
#Formula for calculating BMI
BMI = round(weight * 703/(height*height), 2)
return (BMI)
print(" Your bmi is:", bmi_calculator())
This question already has answers here:
Python check for integer input
(3 answers)
Closed 5 years ago.
I am trying to do a program that asks the user his name, age, and the number of times he wants to see the answer. The program will output when he will turn 100 and will be repeated a certain number of times.
What is hard for me is to make the program asks a number to the user when he enters a text.
Here is my program:
def input_num(msg):
while True:
try :
num=int(input(msg))
except ValueError :
print("That's not a number")
else:
return num
print("This will never get run")
break
name=input("What is your name? ")
age=int(input("How old are you? "))
copy=int(input("How many times? "))
year=2017-age+100
msg="Hello {}. You will turn 100 years old in {}\n".format(name, year)
for i in range(copy):
print(msg)
When you're prompting your user for the age: age=int(input("How old are you? ")) you're not using your input_num() method.
This should work for you - using the method you wrote.
def input_num(msg):
while True:
try:
num = int(input(msg))
except ValueError:
print("That's not a number")
else:
return num
name = input("What is your name? ")
age = input_num("How old are you? ") # <----
copy = int(input("How many times? "))
year = 2017 - age + 100
msg = "Hello {}. You will turn 100 years old in {}\n".format(name, year)
for i in range(copy):
print(msg)
This will check if the user input is an integer.
age = input("How old are you? ")
try:
age_integer = int(age)
except ValueError:
print "I am afraid {} is not a number".format(age)
Put that into a while loop and you're good to go.
while not age:
age = input("How old are you? ")
try:
age_integer = int(age)
except ValueError:
age = None
print "I am afraid {} is not a number".format(age)
(I took the code from this SO Answer)
Another good solution is from this blog post.
def inputNumber(message):
while True:
try:
userInput = int(input(message))
except ValueError:
print("Not an integer! Try again.")
continue
else:
return userInput
break
I asked a related question here about this. However, I still have one problem.
import sys
import calendar
trueVal = 'yes'
while trueVal == 'yes' :
yy = int(input("Enter year: "))
mm = int(input("Enter month: "))
break
except ValueError:
print "Oops! That was not an integer. Try again..."
print(calendar.month(yy, mm))#returns the result
cmd=input("Would you like to view another calendar? Type yes if you do, no to exit program")
if cmd != trueVal :
sys.exit()
Apparently, my prof wants me to put an error message for users who input strings. So I put that except function but it doesn't recognize it.
You need to use a try/except block, always together:
while trueVal == 'yes' :
try:
yy = int(input("Enter year: "))
mm = int(input("Enter month: "))
break
except ValueError:
print("Oops! That was not an integer. Try again...")
There are some errors in your code:
you didn't add "try" at the beginning of the block
even if you answered yes or no your program will have an error!
Here is the code you need, so you can get your deadline ;)
Updated! Because you are using Python 3 so print statement must have parentheses and you have to just use input() instead of raw_input().
import sys
import calendar
trueVal = "yes"
while trueVal == "yes":
try:
yy = int(input("Enter year: "))
mm = int(input("Enter month: "))
print(calendar.month(yy, mm))#returns the result
trueVal = input("Would you like to view another calendar? Type yes if you do, no to exit program: ")
except ValueError:
print("Oops! That was not an integer. Try again...")
Here's my code:
print('Welcome To The Balance Tracker!')
balance = float(input('Enter Your Starting Balance: ')
This is at the start of the program. How would I make it so the user cannot proceed unless the balance is a float, and if they enter anything else it shows an error message?
I know it probably has to be in a while loop. I'm just not a 100% sure on the execution.
Catching the ValueError that is raised if float fails will solve your problem.
print('Welcome To The Balance Tracker!')
balance = None
while balance is None:
try:
balance = float(input('Enter Your Starting Balance: '))
except ValueError:
print("HEY! '{}' is not a float!".format(balance))
This will print a message if it's not float and while loop will not let user to go through!
You can try
#!/usr/bin/env python3
is_balance_not_float = True
print('Welcome To The Balance Tracker!')
while (is_balance_not_float):
try:
balance = float(input('Enter Your Starting Balance: '))
except ValueError:
print("You are suppose to enter a number. ")
else:
is_balance_not_float = False
print("Balance : %s" % balance)
The best thing to do is to try to convert the input to a float, and if it fails, then try again. Reasons for failure could include a string that is not convertible to float, or an EOF on stdin.
For instance:
balance = None
while balance is None:
try:
balance = float(input('Enter Your Starting Balance: '))
except Exception:
print('Balance must be a (floating point) number')
As a point of interest, if the user hits Control-C, it raises KeyboardInterrupt, which is not a subclass of Exception, and so will not get caught by the except, and will cause the program to exit.