0

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;)")

2 Answers 2

3

You have three basic options:

  1. 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('...'))
    
  2. 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')
    
  3. 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
    
Sign up to request clarification or add additional context in comments.

Comments

1
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.