![](/img/trans.png)
[英]How do I keep track of a user's guesses in Python? attempts= attempts + 1 is not working
[英]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")
我將提出四個建議,以使您的代碼更簡潔一些:
6
並從中倒數而不是增加; for
而不是while
,因此您不必手動增加/減少guesses
的數量,而使用else
確定循環是否break
(即,沒有猜測)。 if: elif: else:
而不是if
和 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.