Python Programming/Decision Control/Solutions
Appearance
From Wikibooks, open books for an open world
This is the current revision of this page, as edited by DannyS712 (discuss | contribs) at 06:22, 16 April 2020 (Update syntaxhighlight tags - remove use of deprecated <source> tags). The present address (URL) is a permanent link to this version.
Write a program that has a user guess your name, but they only get 3 chances to do so until the program quits.
name = raw_input("What's my name? ") answer = "Jack" attempt = 0 if name == answer: print("That's correct!") else: while name != answer and attempt < 2: attempt = attempt + 1 name = raw_input("That's incorrect. Please try again: ") if name == answer: print("That's correct!") elif attempt == 2: print("You've exceeded your number of attempts.")
Another solution that uses the sys library.
importsys count = 0 while count < 3: guess = raw_input("Guess my name: ") if guess == "joe": print ("Good guess!") sys.exit() elif count < 2: print ("\nTry again!\n") if count == 2: print ("Too many wrong guesses, terminating") count = count + 1
better way
name = "roger" x=0 while x < 3: guess = raw_input("What's my name?: ") if(guess != name): print "Wrong" x += 1 if(x==3): print "You've reached the max attempt!" else: print "Correct" break