在 Python 中编写“猜数字”游戏的正确方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12967649/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Correct way of coding a 'Guess the Number' game in Python
提问by fdama
I'm new to python and programming in general and I've written some code for a Guess the Number game in Python. It allows the user 6 attempts at guessing a random number. It works, however I am not sure if this is the best way or most efficient way of writing it and would appreciate it of I could get get some constructive feedback on it.
我是 Python 和编程的新手,我已经为 Python 中的猜数字游戏编写了一些代码。它允许用户 6 次尝试猜测一个随机数。它有效,但是我不确定这是否是编写它的最佳方式或最有效的方式,如果我能得到一些建设性的反馈,我将不胜感激。
Code:
代码:
#Guess my Number - Exercise 3
#Limited to 5 guesses
import random
attempts = 1
secret_number = random.randint(1,100)
isCorrect = False
guess = int(input("Take a guess: "))
while secret_number != guess and attempts < 6:
if guess < secret_number:
print("Higher...")
elif guess > secret_number:
print("Lower...")
guess = int(input("Take a guess: "))
attempts += 1
if attempts == 6:
print("\nSorry you reached the maximum number of tries")
print("The secret number was ",secret_number)
else:
print("\nYou guessed it! The number was " ,secret_number)
print("You guessed it in ", attempts,"attempts")
input("\n\n Press the enter key to exit")
回答by Blender
I'd refactor your code to use a forloop instead of a whileloop. Using a forloop removes the need to manually implement a counter variable:
我会重构您的代码以使用for循环而不是while循环。使用for循环消除了手动实现计数器变量的需要:
import random
attempts = 5
secret_number = random.randint(1, 100)
for attempt in range(attempts):
guess = int(input('Take a guess: '))
if guess < secret_number:
print('Higher...')
elif guess > secret_number:
print('Lower...')
else:
print()
print('You guessed it! The number was ', secret_number)
print('You guessed it in', attempts, 'attempts')
break
if guess != secret_number:
print()
print('Sorry you reached the maximum number of tries')
print('The secret number was', secret_number)

