python - 关于密码python游戏的问题
问题描述
我想知道我的代码发生了什么,因为如果我们找到了密码,我想在最后打印出来,但我每次都得到它。
import random
answer = random.randint(1, 101)
user_winner = False
attempts = 0
attempt_word = ""
#Game Loop( the body of the loop inside)
while user_winner != True:
#User input
guess = input("Can you guess a number between 1 and 100? ")
#Check The user Input
try:
guess_number = int(guess)
except:
print("You should write a number!")
quit()
#Increase attempt count
attempts += 1
#check the user answer against the secret number
if guess_number == answer:
user_winner = True
elif guess_number > answer:
print("The number is Smaller!!")
else:
print("The number is Bigger!!")
#Get the spelling of the "attempt" word
if attempts == 1:
attempt_word = " attempt"
else:
attempt_word = " attempts"
#Display the result
print("Congratulations!! You did it in " + str(attempts) + attempt_word)
除非我们得到正确的结果,否则我们不应该看到它(打印)
解决方案
如果您尝试从上到下模拟循环中的代码,您会看到最后print
一行总是在最后读取,因为没有什么可以阻止它到达该点。您将想要将其包裹在一个条件(例如if/else
)周围:
if user_winner == True:
print( "Congratulations!! You did it in " + str( attempts ) + attempt_word )
您还可以考虑将该行放在您编写print
的已经存在的语句下:if
if guess_number == answer:
print( "Congratulations!! You did it in " + str( attempts ) + attempt_word )
elif ...
但是,由于 Python 从上到下读取它,您还需要移动处理attempt_word
变量的代码块。
推荐阅读
- javascript - 如何从 Firebase 云功能中获取 Firebase 用户 ID
- powershell - 为什么我从开始作业与仅运行代码在 Powershell 中得到不同的输出?
- prolog - 什么是统一术语顺序有关系吗?
- angular - Angular Material Drag & Drop - 重复主框图像
- python - pyplot.bar 用于长尺度
- spring - 需要一个找不到的 'org.springframework.security.authentication.AuthenticationManager' 类型的 bean。春天安全的消息
- python - 如何在 Kivy 的特定屏幕上通过下拉菜单构建?
- jquery - 拖放不断打开选项卡中的图像
- python - PIP:尝试下载 scipy 时出现“启动器中的致命错误”
- sql - 在 SQL 中获取当前日期和上一个日期的值