我正在制作一个基本的骰子游戏,并创建了一个过程,玩家可以在其中确认或重命名。而且我用来存储玩家名称的p1变量仅在该函数内起作用,但我想在整个程序中使用它
我已经尝试过在函数之前定义变量,但该变量不起作用,并尝试在函数中先写入Global,但提示“语法无效”
#Functions
p1 = ""
def P1Start():
print("Player 1 type your name")
p1 = str(input())
print("Are you sure this is your name", p1)
time.sleep(timesleep)
print("Type YES to confirm")
time.sleep(timesleep)
print("Type NO to decline")
def P1Creation():
P1confirmation = str(input())
if P1confirmation =="yes":
print("carry on")
#elif P1confirmation == "NO" or "no":
#P1Start()
print(p1)
else:
print("Restarting the Player 1 Name Collection")
time.sleep(1)
P1Start()
#End of Functions
print("Welcome to the Dice game")
time.sleep(timesleep)
P1Start()
time.sleep(timesleep)
P1Creation()
print(p1)
或
#Functions
p1 = ""
def P1Start():
print("Player 1 type your name")
global p1 = str(input())
print("Are you sure this is your name", p1)
time.sleep(timesleep)
print("Type YES to confirm")
time.sleep(timesleep)
print("Type NO to decline")
def P1Creation():
P1confirmation = str(input())
if P1confirmation =="yes":
print("carry on")
#elif P1confirmation == "NO" or "no":
#P1Start()
print(p1)
else:
print("Restarting the Player 1 Name Collection")
time.sleep(1)
P1Start()
#End of Functions
print("Welcome to the Dice game")
time.sleep(timesleep)
P1Start()
time.sleep(timesleep)
P1Creation()
print(p1)
将Global放在前面只会显示“无效语法” 我应该怎么做才能使这项工作?
答案 0 :(得分:1)
您不能一次完成global
和一项作业。代替这个:
global p1 = str(input())
执行以下操作:
global p1
p1 = str(input())
答案 1 :(得分:0)
您可以在函数本身中将其定义为全局。 只是一个例子:
package.json