Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
123 views
in Technique[技术] by (71.8m points)

Is there a way to return to input if condition is not met in python?

What i am trying to do do is this.

1.User Inputs a number (for example a SSN or any Identification number) 2.If the user is not 14 digits, return to the input and try again 3.If Input is 14 digits, continue in program. 4.Check if SSN starts with 1 or 2 (in my scenario all male ID start with 1 and all female ID start with 2 5. If 1 print male if 2 print female.

My last code is:

ssn=str(input("SSN: "))
x=len(ssn)
while x != 14:
        print("Wrong digits")
        break
else:
        print("Thank you")
y=str(ssn[0])
if y == 1:
        print("Male")
else:
        print("ok")*

In execution i get:

SSN: 12345 Wrong digits ok

The problem is that this does not break if i input 12 digits. It does say wrong digits but continues to in the execution. Second problem is that it prints ok even though i added 1234 which starts with 1 and it should be male.

Any ideas on this please?

question from:https://stackoverflow.com/questions/66051317/is-there-a-way-to-return-to-input-if-condition-is-not-met-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First str(input(...)) is unnecessary, as input already returns a string (why convert string to a string ?). Second, you update neither ssn nor x. Third, while x != 14 will run only as long as x is unequal 14. But you want it to do some processing when x is equal 14. Fourth, 1 == "1" will always be False. Following code should work:

while True: # endless loop
    ssn = input("SSN : ")
    if not ssn.isdigit(): # if the ssn is not a number, stop
        print("not a number")
        continue # let the user try again
    l = len(ssn)
    if len(ssn) != 14:
        print("Wrong digits")
        continue # let the user try again
    else:
        print("Thank you")
        if ssn[0] == "1":
            print("Male")
        else: # This will print Female even if first ID digit is 3 or 4 or whatever, should use elif ssn[0] == "2"
            print("Female")
        break # stop asking again

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...