首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何告诉用户Python中还有多少次尝试

如何告诉用户Python中还有多少次尝试
EN

Stack Overflow用户
提问于 2014-05-24 06:47:45
回答 4查看 11.2K关注 0票数 1

我试图在python中做一个随机数游戏,在那里计算机必须生成一个介于1到20之间的数字,你必须猜出来。我已经将猜测的数量限制在6。如果用户猜错了,如何打印用户的猜测?这是我的代码:

代码语言:javascript
运行
复制
import random

attempts = 0

name = input("What is your name? ")
random = random.randint(1, 20)
print(name + ",","I'm thinking of a number between 1 and 20, What is it?")

while attempts < 6:
    number = int(input("Type your guess: "))
    attempts = attempts + 1
    int(print(attempts,"attemps left")) #This is the code to tell the user how many attempts left
    if number < random:
        print("Too low. Try something higher")
    if number > random:
        print("Too high. Try something lower")
    if number == random:
        break
if number == random:
    if attempts <= 3:
        print("Well done,",name + "! It took you only",attempts,"attempts")
    if attempts >= 4:
        print("Well done,",name + "! It took you",attempts,"attempts. Athough, next time try to get three attempts or lower")
if number != random:
    print("Sorry. All your attempts have been used up. The number I was thinking of was",random)

谢谢,任何帮助都是非常感谢的!

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2014-05-24 06:51:43

您的attempts变量计算使用的尝试次数。由于6是限制,所以6 - attempts是剩下的尝试数:

代码语言:javascript
运行
复制
print(6 - attempts, "attempts left")

(不需要将其封装在int调用中。我不知道你为什么那样做。)

顺便说一句,为尽可能多的尝试编写6可能会模糊6的含义,如果要将限制更改为7,则很难找到需要更改的所有位置。可能值得用描述性名称创建一个变量:

代码语言:javascript
运行
复制
max_attempts = 6
...
while attempts < max_attempts:
    ...
    print(max_attempts - attempts, "attempts left")
票数 1
EN

Stack Overflow用户

发布于 2014-05-24 06:50:14

代码语言:javascript
运行
复制
print('attempts left: ', 6 - attempts)
票数 2
EN

Stack Overflow用户

发布于 2014-05-24 06:51:41

代码语言:javascript
运行
复制
print(6 - attempts, "attempts left")
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23842115

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档