Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

Need help adding controlled loops in my python code

I am doing this for a school project, but I haven't been able to figure out how to do this last part and get it to work properly. This is quite simple so I would appreciate any quick help.

I am coding a system that randomly generates a three-digit code, and the user has to guess what it is. They have unlimited tries, and I figured out how to get it to loop, but it won't stop looping when they guess the code right. How do I do this?

Current Code (With Error):

import random
NUMBERS1 = ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9")
NUMBERS2 = ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9")
NUMBERS3 = ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9")
code = random.choice(NUMBERS1) + random.choice(NUMBERS2) + random.choice(NUMBERS3)
print(code)
while True:
  codeguess = input('Guess the 3 Digit Code: ')
  if codeguess == (code):
    print('Good Job! The Code was ' + code)
  else:
    print('Wrong! Try Again!')
while False:
  print('Eyyyyy')

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

1 Reply

0 votes
by (71.8m points)

You need to add a break statement in the if condition in order to break the loop when the user enters correct code, just like this:

import random
NUMBERS1 = ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9")
NUMBERS2 = ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9")
NUMBERS3 = ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9")
code = random.choice(NUMBERS1) + random.choice(NUMBERS2) + random.choice(NUMBERS3)
print(code)
while True:
  codeguess = input('Guess the 3 Digit Code: ')
  if codeguess == (code):
    print('Good Job! The Code was ' + code)
    break
  else:
    print('Wrong! Try Again!')

And you don't need the while False: loop. That is a separate infinite loop and will start only after the first while loop ends.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...