[英]String variable won't change in function
我正在 python 中制作游戏,我决定在 function 中制作大部分游戏。 如果您查看我的代码,它应该会更改变量的值,但不会。
s1 = 'John'
s2 = 'Carl'
s3 = 'Mark'
def game(name,slot):
slot = int(input())
if slot == 1:
name = s1
if slot == 2:
name = s2
if slot == 3:
name = s3
game('John', 1)
要更改在 function 之外声明的变量,您可以使用global
关键字,它允许您访问 function 之外的变量。 在这里,我修改了您的代码以显示如何实现global
关键字。
s1 = 'John'
s2 = 'Carl'
s3 = 'Mark'
def game(name,slot):
global s1
global s2
global s3
if slot == 1:
s1 = name
if slot == 2:
s2 = name
if slot == 3:
s3 = name
game('John Wick', 1)
print(f'{s1=}')
打印出来:
s1='John Wick'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.