如何从函数内部减少分数
How do I reduce a score from inside a function
正在尝试让我的第一个程序运行。我正在尝试根据用户输入减去分数。但我的分数不会改变现在的样子。你能帮我弄清楚哪里出了问题吗?
下面你可以看到我正在尝试的代码 运行:
score = 75
def round_1(score):
shots_1 = input("What did you score: ")
if shots_1 == 1:
return score - 1
elif shots_1 == 2:
return score - 2
elif shots_1 == 3:
return score - 3
else:
return score
input
returns 一个字符串,所以所有这些 if
都是假的:
if shots_1 == 1:
return score - 1
elif shots_1 == 2:
return score - 2
elif shots_1 == 3:
return score - 3
您可以这样做:
if shots_1 == '1':
return score - 1
elif shots_1 == '2':
return score - 2
elif shots_1 == '3':
return score - 3
命令行 input
始终采用 string
格式。您必须根据用户的输入转换为所需的格式。
def round_1(score):
shots_1 = int(input("What did you score: "))
print(shots_1)
if shots_1 == 1:
return score - 1
elif shots_1 == 2:
return score - 2
elif shots_1 == 3:
return score - 3
else:
return score
print(round_1(75))
您可以在此处阅读有关类型转换的更多信息。 https://www.geeksforgeeks.org/taking-input-from-console-in-python/
您的问题与数据类型有关。您必须将 shots_1 转换为 int。或者输入 shots_1 == '1':
当您要求输入时,它会自动将输入作为字符串,因此您也应该将选项转换为字符串,因为您的代码在 def 函数中,您需要先 运行 它:
score = 75
def round_1(score):
shots_1 = input("What did you score: ")
if shots_1 == '1':
print(score-1)
elif shots_1 == '2':
print(score-2)
elif shots_1 =='3':
print(score-3)
else:
print(score)
round_1(75)
正在尝试让我的第一个程序运行。我正在尝试根据用户输入减去分数。但我的分数不会改变现在的样子。你能帮我弄清楚哪里出了问题吗?
下面你可以看到我正在尝试的代码 运行:
score = 75
def round_1(score):
shots_1 = input("What did you score: ")
if shots_1 == 1:
return score - 1
elif shots_1 == 2:
return score - 2
elif shots_1 == 3:
return score - 3
else:
return score
input
returns 一个字符串,所以所有这些 if
都是假的:
if shots_1 == 1:
return score - 1
elif shots_1 == 2:
return score - 2
elif shots_1 == 3:
return score - 3
您可以这样做:
if shots_1 == '1':
return score - 1
elif shots_1 == '2':
return score - 2
elif shots_1 == '3':
return score - 3
命令行 input
始终采用 string
格式。您必须根据用户的输入转换为所需的格式。
def round_1(score):
shots_1 = int(input("What did you score: "))
print(shots_1)
if shots_1 == 1:
return score - 1
elif shots_1 == 2:
return score - 2
elif shots_1 == 3:
return score - 3
else:
return score
print(round_1(75))
您可以在此处阅读有关类型转换的更多信息。 https://www.geeksforgeeks.org/taking-input-from-console-in-python/
您的问题与数据类型有关。您必须将 shots_1 转换为 int。或者输入 shots_1 == '1':
当您要求输入时,它会自动将输入作为字符串,因此您也应该将选项转换为字符串,因为您的代码在 def 函数中,您需要先 运行 它:
score = 75
def round_1(score):
shots_1 = input("What did you score: ")
if shots_1 == '1':
print(score-1)
elif shots_1 == '2':
print(score-2)
elif shots_1 =='3':
print(score-3)
else:
print(score)
round_1(75)