我刚刚开始使用 python 编码,之前没有编程经验。我可以获得有关我的代码以及如何改进它的建议吗?
import random
# - Write a program where the computer picks a random number between 1 and 100.
# - The user has to guess the number, with the program providing hints ("too high" or "too low").
# - Use loops to allow multiple guesses and conditionals to check user inputs.
# - Bonus: Add a scoring system based on the number of guesses.
def guess_game():
get_guess = random.randint(1,100)
guesses = 0
while True:
guess = input("Guess number: ")
guess = int(guess)
guesses += 1
if guesses == 3:
print(f"You are out of guesses! The number is {get_guess}")
break
if guess < get_guess:
print("Too low")
elif guess > get_guess:
print("Too high")
elif guess == get_guess:
print(f"yes {guess} is the correct number!")
break
guess_game()
我尝试创建一个 for in range 函数来计算猜测值,直到有 3 个不正确的猜测值为止,但发现猜测值 += 1 和 if 猜测值 == 3:工作容易得多。任何建议都会很棒。
如果想限制玩家猜3次,原则上可以替换
guesses = 0
while True:
guesses += 1
if guesses == 3:
break
# ... rest of code
由
for guesses in range(3):
# ... rest of code
现在的问题是,仅当 3 次迭代结束而没有正确猜测时才显示“You are out of猜测”,而不是如果玩家猜测正确则不显示。您不能简单地在循环下方执行此操作,因为无论哪种情况都会显示它。
要解决这个问题,您有两种可能性(可能更多,但我会展示这些):
使用最初设置为
False
的“标志”变量,并设置为True
来记录是否有正确的猜测:
correct = False
for guesses in range(3):
guess = ...
# handle too low/too high ...
if guess == get_guess:
correct = True
print("You guessed correctly")
break
if not correct:
print("You are out of guesses")
使用
else
语句的可选 for
部分。仅当循环中未遇到 break
时才会执行:
for guesses in range(3):
guess = ...
# handle too low/too high ...
if guess == get_guess:
print("You guessed correctly")
break
else:
print("You are out of guesses")
您可以使用
else
关键字在循环完成后运行代码,而不会被 break
语句提前终止。 (流利的 Python,第 464 页)
def guess_game():
get_guess = random.randint(1, 100)
correct = False
for i in range(3):
guess = int(input("Guess number: "))
if guess < get_guess:
print("Too low")
elif guess > get_guess:
print("Too high")
elif guess == get_guess:
print(f"{guess} is the correct number!")
break
else: # will not be executed if we `break` from the loop
print(f"You are out of guesses! The number is {get_guess}")