如何在if语句global(python3)中创建变量?

时间:2017-07-21 01:29:47

标签: python-3.x

有没有办法在整个程序的if语句中创建一个变量?在下面的代码中,我想将我喜欢的颜色更改为紫色,但它只对if语句执行。例如,Apple的Siri知道你的名字。让我们说出于某种原因想要改变它,所以你说" Siri将我的名字改为Bob"。然后从那时起,Siri称你为bob。我试图用同样的颜色来塑造相同的东西。

color = "red"
command = input()#the variables have been defined

if command == "What is my favorite color":
    print(color, "is your favorite color")#this prints red

if command == "Change my favorite color":
color = input()
    print(color, "is your new favorite color")#this prints whatever 
                                            #color I put, purple
#now if I ask what is my favorite color again, it will still say red, but I want it to say purple from now until I change it to another color and so on

3 个答案:

答案 0 :(得分:0)

我不确定你的问题是什么。简化一下:

color = 'red'

if True:
    color = 'green'
    print(color) # Prints green

print(color) # Prints green

如您所见,更改if块中的变量也会在封闭函数的范围内更改它。

这可能是Python范围规则的一个很好的介绍 - Short Description of the Scoping Rules?

答案 1 :(得分:0)

我认为你没有传递适当的输入

color = "red"
command = input()#the variables have been defined

if command == "What is my favorite color":
    print(color, "is your favorite color")#this prints red
    command = input()

if command == "Change my favorite color":
   color = input()
   print(color, "is your new favorite color")#this prints whatever 
   command = input()

if command == "What is my favorite color":
    print(color, "is your favorite color")

执行顺序

我最喜欢的颜色是什么 红色是你最喜欢的颜色

更改我最喜欢的颜色

紫 紫色是你最喜欢的颜色

我最喜欢的颜色是什么 紫色是你最喜欢的颜色

答案 2 :(得分:0)

其他答案并未完全涵盖您的问题,因为他们认为您只执行了一次整个代码,并以某种方式让这两个print被解雇(这意味着您必须拥有更改了command之间if之间color的内容。

您的问题是您多次运行该程序,并期望while command != "exit": # your code goes here 的新值以某种方式(神奇地?)传播到下次运行程序时。

为了多次运行相同的代码,你应该把它放在一个循环中。例如:

command is not defined

不要忘记缩进循环内部的代码。

但是,如果这就是你所做的一切,你仍然会遇到问题(实际上是两个,但我们会在一秒内修复color错误),因为你的代码集的第一行{ {1}}到"red",并且每次循环时都会将color变量设置回"red"

要解决这部分问题,你想在循环之外初始化你的变量(你知道什么,这也解决了另一个问题)。

Python有一个特殊的None可以很好地适应这种情况,所以让我们使用它:

command = None # initialized but contains nothing
favcolor = input("What is your favorite color?") # let's initialize this with some user data
while command != "exit"
    command = input("Please enter a command:")
    # the rest of your code goes here

如果你真的需要退出程序并让上次用户数据回来,你必须将这些数据保存到文件或数据库或其他东西,然后在下次运行时将其加载回程序

希望这能为你解决一些问题。