繁体   English   中英

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

[英]How to tell user how many attempts left in Python

我正在尝试在python中制作随机数字游戏,其中计算机必须生成1到20之间的数字,而您必须猜测它。 我将猜测的数量限制为6个。当用户猜错时,如何打印用户留下的猜测数量? 这是我的代码:

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)

谢谢,非常感谢您的帮助!

print('attempts left: ', 6 - attempts)
print(6 - attempts, "attempts left")

您的attempts变量将计算使用的尝试次数。 由于限制是6,因此6 - attempts是剩余的尝试次数:

print(6 - attempts, "attempts left")

(无需将其包装为int调用。我不知道您为什么这样做。)

顺便说一句,始终将最大尝试次数写为6可能会使6含义模糊不清,并且如果您想将限制更改为例如7,则很难找到所有需要更改的位置。可能值得用描述性名称:

max_attempts = 6
...
while attempts < max_attempts:
    ...
    print(max_attempts - attempts, "attempts left")

我将提出四个建议,以使您的代码更简洁一些:

  1. 剔除“幻数” 6并从中倒数而不是增加;
  2. 使用for而不是while ,因此您不必手动增加/减少guesses的数量,而使用else确定循环是否break (即,没有猜测)。
  3. 使用if: elif: else:而不是if
  4. 使用str.format

这将使代码类似于:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM