决定难度级别的功能是存储错误的值并给出不需要的输出



我正在编写一个用于猜测数字游戏的代码。计划使用函数来决定难度级别。游戏有两个级别,我认为如果用户在这个阶段输入错误,程序不会结束,这将是一个好主意。因此,我相应地格式化了函数。在输入了错误的级别输入并最终输入了正确的级别输入后,我得到了多个输出消息。你能帮我理解多行输出背后的逻辑吗。请注意,我已经通过移动print语句解决了这个问题,该语句显示if和elif语句中可用的尝试。这个问题的意图是理解为什么print语句在if语句之外不起作用。

import random

print("Welcome to the game!")
the_number = random.choice(range(100))
print(the_number)

def decide_difficulty_level():
difficulty_level = input("Please select a difficulty level. 'easy' or 'hard'    :").lower()
number_of_attempts = 0
if difficulty_level == "easy":
number_of_attempts = 10
elif difficulty_level == "hard":
number_of_attempts = 5
else:
print("Please select a proper difficulty level. ")
decide_difficulty_level()
print(f"You have {number_of_attempts} attempts to guess the number. Best of luck!")
decide_difficulty_level()

。.

这是上面详细说明的代码的输出。

Welcome to the game!
94
Please select a difficulty level. 'easy' or 'hard'    :1
Please select a proper difficulty level. 
Please select a difficulty level. 'easy' or 'hard'    :2
Please select a proper difficulty level. 
Please select a difficulty level. 'easy' or 'hard'    :3
Please select a proper difficulty level. 
Please select a difficulty level. 'easy' or 'hard'    :easy
You have 10 attempts to guess the number. Best of luck!
You have 0 attempts to guess the number. Best of luck!
You have 0 attempts to guess the number. Best of luck!
You have 0 attempts to guess the number. Best of luck!

Process finished with exit code 0

不要使用递归进行数据验证。你的函数应该有一个目的,它应该返回其目的的结果,并让调用者决定如何处理它

此外,不要执行random.choice(range(xxx))。这迫使Python创建整个范围。相反,只需使用random.randrangerandom.randint

import random

print("Welcome to the game!")
the_number = random.randrange(1,100)
print(the_number)
def decide_difficulty_level():
while 1:
difficulty_level = input("Please select a difficulty level. 'easy' or 'hard'    :").lower()
if difficulty_level == "easy":
return 10
elif difficulty_level == "hard":
return 5
else:
print("Please select a proper difficulty level. ")
level = decide_difficulty_level()
print(f"You have {level} attempts to guess the number. Best of luck!")

最新更新