我正在为学校做一个简单的代码阻塞,我的问题是为什么当我在程序中使用两个函数时,只有一个起作用或根本不起作用。 one_player_#是我的函数的名称。我想使用if-语句来调用用户选择游戏模式的函数。我的游戏模式是一名玩家和两名玩家。因此,我将游戏代码设为函数,以便用户可以通过if-语句选择游戏模式,但是当您选择游戏模式时,它不起作用。我试图做些什么吗?希望有道理请解释我错了,谢谢。
(async () => {
var _response = await fetch('https://reqres.in/api/users?page=2').then(res => res.json());
console.log(_response);
})()
我希望它允许用户选择游戏模式并运行它,而不是给我空白的答复
答案 0 :(得分:1)
您的脚本从上至下阅读。 首先定义函数,然后调用它们。另外,在输入前使用“ int”。
#One player Function
def one_player_op():
# I put game code for 1st play here
#Two player function
def two_player_op():
# I put game code for two player here
#code endsenter code here
# choose your game mode
op = int(input("Choose gamemode - Two player = 2 One player = 1 : "))
if op == 2:
print (two_player_op())
if op == 1:
print(one_player_op())
答案 1 :(得分:1)
如果要获得True结果,则需要确保将一个int与另一个int进行比较。请记住要处理的数据类型。同样在python中,必须在运行函数的代码之前定义函数。不是定义它们的代码,而是实际执行该功能的代码。 因此,在您的情况下:
#One player Function
def one_player_op():
# I put game code for 1st play here
#Two player function
def two_player_op():
# I put game code for two player here
# choose your game mode
op = int(input("Choose gamemode - Two player = 2 One player = 1 : "))
if op == 2 :
print (two_player_op())
if op == 1:
print(one_player_op())
#code ends
如果要清楚地表明只运行一种游戏模式(出于代码可读性的目的),并确保将来可能添加的任何附加条件选项能够按照您的意图执行,您可以编写注释条件为:
if op == 2 :
print (two_player_op())
elif op == 1:
print(one_player_op())
#code ends
答案 2 :(得分:0)
您需要处理用户添加的其他选项,而不仅仅是(1或2)
# choose your game mode
op = input("Choose gamemode - Two player = 2 One player = 1 : ")
try:
user_input = int(op)
except ValueError:
# handles characters added in input e.g "one", "play"
print("Please enter values between 1 or 2 only ")
if user_input == 2 :
print (two_player_op())
elif user_input== 1:
print(one_player_op())
else:
print("Please enter values between 1 or 2 only ")
#One player Function
def one_player_op():
# I put game code for 1st play here
#Two player function
def two_player_op():
# I put game code for two player here
#code ends
答案 3 :(得分:-1)
需要将input
字符串转换为int。
op = int(input(“ ........'))