首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
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

Stack Overflow用户

发布于 2014-05-24 07:06:15

我将提出四个建议,这些建议旨在使您的代码更简洁和更简单:

  1. 计算出“幻数”6,然后从它中进行计数,而不是根据它来计算;
  2. 使用for而不是while,这样您就不必手动增加/减少guesses的数量,并使用else来确定循环break的值(即猜测之外);
  3. 使用if: elif: else:而不是单独的if;以及
  4. 使用str.format

这将使代码类似于:

代码语言:javascript
运行
复制
attempts = 6
for attempt in range(attempts, 0, -1):
    print("You have {0} attempts left.".format(attempt))
    number = int(input(...))
    if number < random:
        # too low
    elif number > random:
        # too high
    else:
        if attempt > (attempts // 2):
            # great
        else:
            # OK
        break
else:
    # out of guesses
票数 1
EN
查看全部 4 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23842115

复制
相关文章

相似问题

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