How to make a program exit upon receiving invalid input? - python

I am trying to make a program where it converts imperial to metric. The part I am having trouble with is that with any input that is an invalid number (any negative) I am supposed to terminate the program without using exit, break, or system exit.
print('Hello, Please input the Imperial values!')
#Miles
Miles = float(input('Miles to Kilometers: '))
totalKilometers = (1.6 * Miles)
if Miles < 0:
print('Please no negative numbers')
else:
if Miles > 0:
print("The metric conversion is ", totalKilometers)
#Fahrenheit
Fahrenheit = float(input('Fahrenheit to Celsius: '))
totalCelcius = ((Fahrenheit - 32) * 5/9 )
if Fahrenheit < 0 or Fahrenheit > 1000:
print('Please check your Fahrenheit number, It must be greater than 0 and
less than 1000')
else:
if Fahrenheit > 0 or Fahrenheit < 1000:
print("The metric conversion is ", totalCelcius)
#Gallons
Gallons = float(input('Gallons to Liters: '))
totalLiters = (3.9 * Gallons)
if Gallons < 0:
print('Please no negative numbers')
else:
if Gallons > 0:
print("The metric conversion is ", totalLiters)
#Pounds
Pounds = float(input('Pounds to Kilograms: '))
totalKilograms = (.45 * Pounds)
if Pounds < 0:
print('Please no negative numbers')
else:
if Pounds > 0:
print("The metric conversion is ", totalKilograms)
#Inches
Inches = float(input('Inches to Cenitmeters: '))
totalCentimeters = (2.54 * Inches)
if Inches < 0:
print('Please no negative numbers')
else:
if Inches > 0:
print("The metric conversion is ", totalCentimeters)

Since you can't exit out of the program, define all of the code you already have as a function and use return. The code would look something like this:
def imp-met():
print('Hello, Please input the Imperial values!')
#Miles
Miles = float(input('Miles to Kilometers: '))
totalKilometers = (1.6 * Miles)
if Miles < 0:
print('Please no negative numbers')
return
(rest of code using return when needed)
imp-met()

Related

Exception handling for different inputs in Python

i am a beginner in python and i've tried to create a BMICalculator program and i am currently facing an issue
first up when you open the program it asks the user for their height and weight input
and i have created a try-exception handling for when a user tries to put a string into their Height/Weight input
But the problem is, when a user enters their Height properly, and then uses a string for their Weight, my ValueError exception does show up, but makes the user enter their Height again which is not user friendly,
So what i want to do but don't know how is:
To ask the user again for their Weight input not Height, as they have already entered that
My Code:
import math
import time
def BMICalculator():
print("BMI Calculator!")
try:
Height = float(input("Enter your Height: "))
Weight = float(input("Enter your Weight: "))
Result = Weight / (Height / 100) ** 2
print("Your BMI is: ", round(Result, 1))
if Result <= 18.5:
print("You are underweight")
elif Result <= 24.9:
print("You are healthy")
elif Result <= 29.9:
print("You are overweight")
elif Result > 29.9:
print("You are obese")
except ValueError:
print("Please enter a valid number")
BMICalculator_NoWelcomingMessage()
def BMICalculator_NoWelcomingMessage():
try:
Height = float(input("Enter your Height: "))
Weight = float(input("Enter your Weight: "))
Result = Weight / (Height / 100) ** 2
print("Your BMI is: ", round(Result, 1))
if Result <= 18.5:
print("You are underweight")
elif Result <= 24.9:
print("You are healthy")
elif Result <= 29.9:
print("You are overweight")
elif Result > 29.9:
print("You are obese")
except ValueError:
print("Please enter a valid number")
BMICalculator_NoWelcomingMessage()
def enter_again():
user = input("Do you want to enter again?: ").lower()
while user not in ['yes', 'y', 'no', 'n']:
print("Please enter a valid input")
user = input("Do you want to enter again?: ").lower()
if user not in ['yes', 'y']:
print("Have a nice day!")
time.sleep(1)
elif user not in ['no','n']:
BMICalculator_NoWelcomingMessage()
enter_again()
BMICalculator()
enter_again()
Well, the reason that happens is because you have a single catch statement for both the inputs, and if either of them throws an error, you restart the entire process.
You can fix this with a minor modification, have the two inputs in separate catch blocks, and have a while true loop to keep asking for a valid input till you get one.
Here's what I said in code:
def BMICalculator():
print("BMI Calculator!")
while True:
try:
Height = float(input("Enter your Height: "))
break
except ValueError:
print("Please enter a valid number")
while True:
try:
Weight = float(input("Enter your Weight: "))
break
except ValueError:
print("Please enter a valid number")
Result = Weight / (Height / 100) ** 2
print("Your BMI is: ", round(Result, 1))
Note: You can probably parse the input in a separate function, and call that function when taking input for weight and height, would make the code cleaner. Something like this perhaps:
def parse_input(InputName):
while True:
try:
value = float(input(f"Enter your {InputName}: "))
break
except ValueError:
print("Please enter a valid number")
return value
def BMICalculator():
print("BMI Calculator!")
Height = parse_input("Height")
Weight = parse_input("Weight")
Result = Weight / (Height / 100) ** 2
print("Your BMI is: ", round(Result, 1))

My python code does what it is intended to do, but breaks/keeps going with the try/catch blocks?

#A 0-50 Units is multiplied by $0.59 (multiply by 0.59)
#B Up to 150 Units (minus 50 and multiply remaning by 0.65)
#C Greater than 150 Units(minus 150(first 150 = $94.50) and multiply remaining by 0.68)
#D All Residential charges are fixed # $13.00(always add $13)
print (" * SKELEC Electricity Bill Calculator * ")
def main():
while True:
try:
prev_month = float(input("Enter the meter reading for the previous month\n"))
break
except ValueError:
print("Invalid value entered. Please try again.")
continue
if prev_month < 0:
print("Please enter a valid reading.")
main()
while True:
try:
pres_month = float(input("Enter the meter reading for the current month\n"))
break
except ValueError:
print("Invalid value entered. Please try again.")
continue
if pres_month < 0:
print("Please enter a valid reading.")
main()
if pres_month < prev_month:
print("Present month value is lower than previous month value")
main()
units_kwh = pres_month - prev_month #Variable for the subtraction of present month and previous month
print("Usage = ", units_kwh,"kw/h")
if units_kwh <= 50: #Argument for 0-50 kwh units
Energy_charge = units_kwh * 0.59
print("Your charge for the month is, $", Energy_charge)
elif units_kwh > 50 and units_kwh <= 150: #Argument for units up to 150kwh
units_fifty = units_kwh - 50
Energy_charge = (units_fifty * 0.65 + 29.50) + 13.00
print("Your charge for the month is, $", Energy_charge)
elif units_kwh > 150: #Argument for units over 150kwh
Energy_charge = ((units_kwh - 150) * 0.68 + 94.50) + 13.00
print("Your charge for the month is, $", Energy_charge)
print("Residential Charge of $13.00 added")
main()
Everything works well, but if an incorrect value is entered at first(such as characters), the code unwantedly loops once it gives the final result. I've tried moving the try/catch blocks outside of the loop, double checking my conditional statements and proofreading to see how the code could loop in such a way. I'm convinced the problem lays in the try/catch blocks, but I'm fairly new to coding with Python so I am unsure of how to fix this?
You can make a couple changes to improve the code:
If the user enters a negative number, raise an exception
Add an outer while loop for the pres_month < prev_month condition
Try this code:
def main():
while True: # pres_month < prev_month
while True:
try:
prev_month = float(input("Enter the meter reading for the previous month\n"))
if prev_month < 0: raise ValueError()
break
except ValueError:
print("Invalid value entered. Please try again.")
while True:
try:
pres_month = float(input("Enter the meter reading for the current month\n"))
if pres_month < 0: raise ValueError()
break
except ValueError:
print("Invalid value entered. Please try again.")
if pres_month < prev_month:
print("Present month value is lower than previous month value")
else:
break # data is valid

Making a Calculator which take input from user until user enter 0 but not working correctly

I am a newbie in python and trying to make a calculator but no getting how to make it
I am making a Calculator which will take input from the user until the user enters 0 and then do the operations
but I am stuck here
if anyone can help me doing this work I will be very thankful to him/her.
num = None
# Asking Users for the Specific Operations
print(("1. For Addition \n 2. For Subtraction. \n 3. For Multiplication. \n 4. For Division \n 5.For Exit"))
options = int(input("Enter Your Choice: "))
# For Addition or Option 1
if options == 1:
total = 0
while(num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total + num
print("Your Calculated Number is: {} ".format(total))
# For Subtraction or Option 2
elif options == 2:
total = 0
while (num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total - num
print("Your Calculated Value is: {}".format(total))
# Multiplication for Option 3
elif options == 3:
total = 1
while (num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total * num
print("Your Calculated Value is: {}".format(total))
# Division for Option 4
elif options == 4:
total = 1
while (num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total / num
print("Your Calculated Value is: {}".format(total))
# When User Wants to Exit
else:
print("Thank You for Using the Calculator")
Here is a better approach using itertools.reduce. Instead of repeating the same code for inputting a number multiple times, put it into a function. This will also help avoid the errors in your code and clarify the logic. A second generator function can be used to get the series of values until the user enters zero.
from functools import reduce
import operator
def input_number():
while True:
try:
return float(input("(Enter '0' When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
def input_series():
while True:
n = input_number()
if n == 0:
return
yield n
operations = {
1: operator.add,
2: operator.sub,
3: operator.mul,
4: operator.truediv
}
# Asking Users for the Specific Operations
print(("1. For Addition \n 2. For Subtraction. \n 3. For Multiplication. \n 4. For Division \n 5.For Exit"))
option = int(input("Enter Your Choice: "))
# For Addition or Option 1
if option == 5:
print("Thank You for Using the Calculator")
else:
total = reduce(operations[option], input_series())
print("Your Calculated Value is: {}".format(total))
Instead of
elif options == 2:
total = 0
while (num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total - num
use (the changes are only in the 2nd line and in the last one)
elif options == 2:
total = None
while (num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total - num if total is not None else num
The same method you may use for the elif options == 4: branch.
The problem with subtraction is that the variable total is not initialized.
The problem with multiplication and division is that when the user inputs "0", the variable total is multiplied or divided by zero before it is checked in the while statement. what I would normally do is this:
elif options == 3:
total = 1
while True:
try:
num = float(input("(Enter '0' When Complete.) Enter Number ")) # No need to escape single quotes when your string uses double quotes
if num == 0:
break
except ValueError:
print("Error, Enter Valid Number")
continue
total = total * num
print("Your Calculated Value is: {}".format(total))
However, if you wanted a quick fix, you can have the user input 1 instead of 0 for multiplication and division:
elif options == 4:
total = 1
while (num != 1):
try:
num = float(input("(Enter '1' When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total / num
print("Your Calculated Value is: {}".format(total))
Edit: If you want division to work the way you specified, you could do something like this:
elif options == 2:
total = 1
try:
first_number = float(input("(Enter '0' When Complete.) Enter Number "))
if first_number == 0:
print("Your Calculated Value is: 0")
exit()
except ValueError:
print("Error, Enter Valid Number")
continue
total = 1
while True:
try:
num = float(input("(Enter '0' When Complete.) Enter Number "))
if num == 0:
break
except ValueError:
print("Error, Enter Valid Number")
continue
total = total * num
print("Your Calculated Value is: {}".format(total + first_number))

How to remove a set of characters from a user inputted float - Python

I just started picking up python and I want to know how to do what I said in the title. The only background in programming I have is a semester long C++ class that I had in high school that I got a C in and forgot almost everything from. Here's my code:
while True:
try:
height_m = float(input("Enter your height in meters: "))
except ValueError:
print ("Please enter a number without any other characters.")
continue
else:break
while True:
try:
weight_kg = float(input("Enter your weight in kilograms: "))
except ValueError:
print ("Please enter a number without any other characters.")
continue
else:break
bmi = weight_kg / (height_m ** 2)
print ("Your bmi is",(bmi),".")
if bmi < 18.5:
print ("You are underweight.")
elif 18.5 <= bmi <=24.9:
print ("You are of normal weight.")
elif 25 <= bmi <= 29.9:
print ("You are overweight.")
else:
print ("You are obese.")
As you can see, it's just a basic BMI calculator. However, what I wanted to do was make it so that if someone were to input "1.8 m", "1.8 meters" or "1.8 ms" and the equivalent for kilograms, the program would remove the extra input and process it as if they hadn't added that. Also, any extra tips you have for me would be great. Thanks!
Replace the third line with this:
height_m = float(''.join([e for e in input("Enter your height in meters: ") if not e.isalpha()]))
It works by removing all alphabets before converting to float.
In general, this works
Height_List = []
Height = input("What is your height")
for i in Height:
if i in "1234567890.":
Height_List.append(i)
Actual_Height = float("".join(Height_List))

The loop for 10 times is not working, displaying a text, and having an exception error in python

My program wants to repeat it 10 times which I tried to do by putting in for i in range(10):, it doesnt do it 10 times
Also I need to have an exception error like if a user enters forty instead of 40, I can display "error, you must enter the value as an integer" but my cmd prompt says I have an inconsistent use of tabs and indentation.
my last one is that when I try to display my conversions to a text, it says the variable isn't defined which makes no sense... for example outfile.write(str(miles) + "\n"), my cmd prompt states that the name miles is not defined and i define miles in the code
Here's my code:
# constants for the menu choices
Mi_to_km_choice=1
F_to_C_choice=2
Gallons_to_liters_choice=3
Pounds_to_Kilograms_choice=4
Inches_to_Centimeters_choice=5
Quit_choice=6
#open a new file named conversions.txt
outfile= open("conversions.txt" , "w")
#the main function
def converting():
for i in range(10):
#a.converting Miles to Kilometers
#choice variable controls the loop
choice=0
while choice != Quit_choice:
#display the menu
display_menu()
#get the user's choice
choice= int(input("Enter your choice:"))
#perform the selected action
#miles to km
if choice == Mi_to_km_choice:
counter = 1
miles = int(input("Enter a value for miles "))
while miles < 0:
print("Error, you can't enter a negative value for miles")
miles = eval(input("Enter the correct value for miles "))
counter+=1
if counter > 3:
break
if counter <= 3:
kilometers= miles * 1.6
print(miles , "miles is", kilometers , "kilometers")
except ValueError:
print("Error: Miles must be an integer")
else:
print("You have the exceeded error count")
#b.converting Fahrenheit to Celsius
elif choice == F_to_C_choice:
counter = 1
fahrenheit = int(input("Enter a value for fahrenheit "))
while fahrenheit > 1000:
print("Error, you can't enter a value above 1000 degrees fahrenheit")
fahrenheit = eval(input("Enter the correct value for fahrenheit "))
counter+=1
if counter > 3:
break
if counter <= 3:
celsius= (fahrenheit-32) * 5/9
print(fahrenheit , "degrees fahrenheit is", celsius , "degrees celsius")
else:
print("You have exceeded the error count")
#c.converting Gallons to Liters
elif choice == Gallons_to_liters_choice:
counter=1
gallons= int(input("Enter a value for gallons "))
while gallons < 0:
print("Error, you can't enter a negative for gallons")
gallons = eval(input("Enter the correct value for gallons "))
counter+=1
if counter > 3:
break
if counter <= 3:
liters= gallons * 3.9
print(gallons , "gallons is", liters , "liters")
else:
print("You have exceeded the error count")
#d. converting Pounds to Kilograms
elif choice == Pounds_to_Kilograms_choice:
counter=1
pounds= int(input("Enter a value for pounds "))
while pounds < 0:
print("Error, you can't enter a negative for pounds")
pounds = eval(input("Enter the correct value for pounds "))
counter+=1
if counter > 3:
break
if counter <= 3:
kilograms= pounds * .45
print(pounds , "pounds is", kilograms , "kilograms")
else:
print("You have exceeded the error count")
#e.converting Inches to Centimeters
elif choice == Inches_to_Centimeters_choice:
counter=1
inches= int(input("Enter a value for inches "))
while inches < 0:
print("Error, you can't enter a negative negative value for inches")
inches=eval(input("Enter the correct value for inches "))
counter+=1
if counter > 3:
break
if counter <=3:
centimeters= (inches * 2.54)
print(inches, "inches is", centimeters, "centimeters")
else:
print("You have exceeded the error count")
elif choice == Quit_choice:
print("Exiting the program...")
else:
print("Error: invalid selection. ")
#display the menu
def display_menu():
print(" Menu")
print("1) Miles to Kilometers")
print("2) Fahrenheit to Celsius")
print("3) Gallons to Liters")
print("4) Pounds to Kilograms")
print("5) Inches to Centimeters")
print("6) Quit")
#write the conversions to the file
outfile.write(str(miles) + "\n")
outfile.write(str(kilometers) + "\n")
outfile.write(str(gallons) + "\n")
outfile.write(str(liters) + "\n")
outfile.write(str(pounds) + "\n")
outfile.write(str(kilograms) + "\n")
#close the file
outfile.close()
print("Data written to conversions.txt")
#call the main function
converting()
Your prompt is telling you exactly what's wrong...
Your indentation is wrong, you have different amounts of indentation in different parts of the program.
In Python indentation matters, so you will need to go through your program and see that you have the right amount of spaces. Normally one level of indentation is 4 spaces. Most Python editors will handle this for you.
And your indentation fault is that your except ValueError is one space wrong to the left:
if counter <= 3:
kilometers= miles * 1.6
print(miles , "miles is", kilometers , "kilometers")
except ValueError:
print("Error: Miles must be an integer")
Start by making the indentation right, it will help your error searching for the rest of the program.
The range function you are using will set i in to 0,1,2...9 so it will run 10 times.
In your write function miles (and the others) are not defined because they are defined in another function, in another scope, so your display function cannot reach them, hence the error.

Categories

Resources