dimanche 23 octobre 2016

How can I restrict an if statement to specific characters?

Before beginning it is worth mentioning I am relatively new to Python.

I am creating a binary to decimal converter at the moment, and have used conditional if statements in an attempt to allow only zeroes and ones to be entered.

value = input("Enter the binary value to convert to a decimal number.")
    #Prints the message in double quotes and prompts user for an input. This input is then set to the variable value.
    for i in value:
        if not (i in "01"):
            print ("Please enter only zeroes and ones.")
            break
    for i in value:
        if (i in "01"):
#rest of code

I can enter anything that doesn't contain zeroes and ones, i.e: 789 and the error message will display correctly, and user asked for input again. However, if I enter 7890, the error message still displays and the value still converted to decimal value.

What is the way to circumvent this and if value contains anything other than zeroes and ones at all, to not convert to decimal number and ask the user for another input?

Aucun commentaire:

Enregistrer un commentaire