python - Python中的确定循环和不确定循环
问题描述
我需要在此代码上显示“确定循环”和“不确定循环”。(嵌套)
这是一个简单的代码,选择一个随机数,并给你 2 次猜测数字的机会,如果你不能,它会让你知道魔法数字是什么,然后重新开始游戏。
问题:还有其他方法可以让游戏重新开始吗?像一个while或嵌套循环。如果足够,我可以得到意见吗?
代码的问题是,每次你猜测时,它都会打印
"Can you guess the magic number?"
它怎么能只在代码的开头打印,然后只打印:
"try a lower number"
"try a higher number"
感觉代码嵌套不够,反正我能把它做得更专业吗?
repeat_the_game = True
def start():
import random
magic_number = random.randint(1, 10)
trying = 0
limit = 2
while trying < limit:
guess = int(input("can you guess the magic number?"))
trying += 1
if guess > magic_number:
print("try a lower number")
elif guess < magic_number:
print("try a higher number")
elif guess == magic_number:
print("wow, you are right")
break
else:
print("sorry, the magic number was", magic_number)
while repeat_the_game:
start()
解决方案
将文本移出循环到打印语句。然后你仍然可以在循环中继续获取输入:
repeat_the_game = True
def start():
import random
magic_number = random.randint(1, 10)
trying = 0
limit = 2
print("can you guess the magic number?")
while trying < limit:
trying += 1
guess = int(input())
if guess > magic_number:
print("try a lower number")
elif guess < magic_number:
print("try a higher number")
elif guess == magic_number:
print("wow, you are right")
break
else:
print("sorry, the magic number was", magic_number)
while repeat_the_game:
start()
但是,如果第二次猜测仍然错误,您可能不想打印“尝试更低/更高的数字”。如果你第二次猜对了,你确实想打印“哇,你是对的”。在额外检查所有尝试是否已经用完之后,我会放置“尝试更低/更高的数字”。您可以在检查之前移动“哇,你是对的”部分:
while trying < limit:
guess = int(input())
trying += 1
if guess == magic_number:
print("wow, you are right")
break
if trying == limit:
continue
if guess > magic_number:
print("try a lower number")
elif guess < magic_number:
print("try a higher number")
else:
print("sorry, the magic number was", magic_number)
推荐阅读
- javascript - 单击 chrome 扩展中的按钮时启动后台线程
- powershell - Powershell - convertTo-JSON 时添加“数据”块
- django - 如何在任何时间登录 Django 2.2 后更新 sqlite3?
- python-3.x - Scrapy爬虫响应网址与请求网址
- java - 为什么即使代码最初工作,计数器变量也无法访问?
- javascript - 反应:触发另一个孩子从数组映射中单击按钮
- azure - Azure 容器实例与 Azure Functions
- python - MySQL搜索AWS python中的空格
- mysql - 用外键解决 laravel 迁移问题
- java - Spring Security - 公共页面重定向到使用无效会话 ID 登录