Reputation: 165
I have multiple inputs here but I want to restrict the input to only integers and display an error message when user inputs a character other than input. And keep asking the user to input the right value before going to the next item.Here is my code:
print ("welkom bij de munten teller")
cent= int(input("vul het aantal 1 centjes in: "))
stuiver= int(input("vul het aantal stuivers in: "))
dubbeltje= int(input("vul het aantal dubbeltjes in: "))
kwartje= int(input("vul het aantal kwartjes in: "))
SRD= int(input("vul het aantal 1 SRD's in: "))
dalla= int(input("vul het aantal 2,50's in: "))
totaal = int ()
fin_cent= cent * 0.01
fin_stuiver = stuiver* 0.05
fin_dubbeltje = dubbeltje * 0.10
fin_kwartje = kwartje * 0.25
fin_SRD = SRD*1
fin_dalla = dalla * 2.50
totaal = fin_cent + fin_stuiver + fin_dubbeltje + fin_kwartje + fin_SRD + fin_dalla
print ("Het totaal is: ", totaal)
#print (totaal)
input("Druk op enter om het programma te beindigen;)")
Upvotes: 0
Views: 6341
Reputation: 60994
You have three basic options:
Attempt to convert the input to an integer and let any errors raised propagate naturally. The user will be shown a ValueError: invalid literal for int() with base 10: <your input>
value = int(input('...'))
Wrap the code that may raise an exception in a try..except
block. This allows you to catch the error and raise your own.
try:
value = int(input('...'))
except ValueError:
raise ValueError('Make sure you input integers')
Wrap that try
block in a loop, so it keeps asking until it gets a correct input
while True:
try:
value = int(input('...'))
except ValueError:
print('Please enter a valid integer')
continue
break
Upvotes: 3
Reputation: 1792
cent= getInt("vul het aantal 1 centjes in: ")
stuiver= getInt("vul het aantal stuivers in: ")
def getInt(msg):
var = input(msg)
if not var.isdigit():
print("Number Only")
exit()
return int(var)
You have to accept them as string first. Then check if they're digit or not using .isdigit()
function. Since you have a lot of inputs, creating a function is easier.
Upvotes: 1