这段python代码有问题吗?
我的问题是,当 run_again() 执行并在我键入“n”时要求输入时,一切正常,但是当我键入“y”时,run() 函数不执行。 为什么会这样?
我尝试在不创建函数的情况下执行 run_again() 过程,但它显示了相同的错误。
import random
print("Welcome to the Snake water gun game!")
chance = 1
counter = 10
player_p = 0
comp_p = 0
choices = ["Snake", "Water", "Gun"]
def run():
global choices
global chance
global player_p
global comp_p
global counter
while chance > 0 and chance <= 10:
a = random.choice(choices)
counter -= 1
print("Choose one from below:\n1.Snake(s)\n2.Water(w)\n3.Gun(g)")
decision = input("Type here:")
if decision == "s" and a == "Snake":
chance += 1
print(f"Draw. {counter} times left.")
elif decision == 's' and a == "Water":
chance += 1
print(f"You Won! {counter} times left.\n-------------------------------")
player_p += 1
elif decision == "s" and a == "Gun":
chance += 1
print(f"You lost. {counter} times left.\n-------------------------------")
comp_p += 1
elif decision == "w" and a == 'Snake':
chance += 1
print(f"You lost. {counter} times left.\n-------------------------------")
comp_p += 1
elif decision == "w" and a == "Water":
chance += 1
print(f"Draw. {counter} times left.\n-------------------------------")
elif decision == "w" and a == "Gun":
chance += 1
print(f"You Won! {counter} times left.\n-------------------------------")
player_p += 1
elif decision == "g" and a == "Snake":
chance += 1
print(f"You Won! {counter} times left.\n-------------------------------")
player_p += 1
elif decision == "g" and a == "Water":
chance += 1
print(f"You lost. {counter} times left.\n-------------------------------")
comp_p += 1
elif decision == "g" and a == "Gun":
chance += 1
print(f"Draw. {counter} times left.\n-------------------------------")
run()
print("Your score:", player_p)
print("Computer's score:", comp_p)
def winner():
if player_p > comp_p:
print("------------------------\nYou Won! Congratulations")
elif player_p < comp_p:
print("------------------------\nComputer Won! Better luck next time.")
else:
print("---------------\nIt's a DRAW!")
winner()
def run_again():
q = input("Do you want to play again(y/n):")
if q == 'n':
print("Oh, okay")
elif q == 'y':
run()
run_again()
答案 0 :(得分:1)
您的代码有效
def run_again():
q = input("Do you want to play again(y/n):")
if q == 'n':
print("Oh, okay")
elif q == 'y':
run()
def run():
print("Hi")
run_again()
答案 1 :(得分:0)
在给定的代码中没有你创建的run()函数,那怎么调用呢?您必须根据给定的代码创建一个名为 run() 的函数。请参阅以下代码以更好地理解:-
def run():
print("Let's play again")
def run_again():
q = input("Do you want to play again(y/n):")
if q == 'n':
print("Oh, okay")
elif q == 'y':
run()
run_again()
您可以根据自己的选择在更新后的代码中编辑 run() 函数。