简体   繁体   中英

How can I replace this while loop with a for loop?

How do I make this while loop a for loop?

correctpassword = "pa55word"
guesses = 0
guess = ""
while guess != correctpassword:
  guess = input("Try guess the password: ")
  guesses = guesses + 1
  print("Password guessed correctly")
if guesses == 1:
  print("That took 1 guess" )
else:
  print("That took you " + str(guesses) + " goes")

.........................................................................................

You can run an infinite for loop using iter and break out of it when guess == correctanswer. Check the code below:

correctpassword = "pa55word"
guesses = 0
guess = ""
for i in iter(int, 1):
    guess = input("Try guess the password: ")
    guesses = guesses + 1
    if guess == correctpassword:
        print("Password guessed correctly")
        break
if guesses == 1:
  print("That took 1 guess" )
else:
  print("That took you " + str(guesses) + " goes")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM