我很好奇这个程序是如何读取的。你有foo功能。 "东西"是一个全局变量。它设置了" Thing"等于100到"项目"现在也等于100.返回"项目" == 0是我不太确定的。 "项目"那么等于0?然后下到flag = False。所以"当没有标记时:"被叫,它要求用户输入,无论出于何种原因,直到你输入" 0"国旗变为真和"事情"现在等于0.如果有人可以解释这是如何工作的,我会很感激
def foo(item):
global thing
thing = item
return item == 0
thing = 100
flag = False
while not flag:
flag = foo(int(input("Give me what I want here: ")))
print(thing)
答案 0 :(得分:0)
item
设置为用户在提示Give me what I want here
时响应的任何内容,转换为整数。反过来,thing
也会设置为该值(thing = item
将全局thing
绑定到item
个点。
因此,如果用户输入0
,item
设置为0
,则thing
设置为0
,item == 0
返回{ {1}},结束True
循环。
答案 1 :(得分:0)
def foo(item): # 3: item is the int(user_input)
global thing # 4 :means you are modifying the global variabl 'thing'
thing = item # 5: you set the global variable 'thing' to equal the int(user_input)
return item == 0 # 6: you evaluate the int(user_input) to 0, if int(user_input) == 0 it will return True,
# else return false
thing = 100
flag = False
while not flag: # 1: while not flag(False) which is the same as while True, a infinite loop
flag = foo(int(input("Give me what I want here: "))) # 2: takes user input, turns it into a int and call foo with
# that value
# 7 : flag is set to the whatever is returned from foo, either True if the user input is 0, or false, if not.
print(thing) # 8 if the loop ends(if the int(user_input) == 0) you will print the thing, which is 0, set on set 5.
查看程序流程的一个好方法是打印程序的每一行,也许是一些变量,如下所示:
print ("#1")
def foo(item):
global thing
thing = item
print ("#4 thing=%r, flag=%r,item=%r" % (thing, flag,item))
return item == 0
thing = 100
flag = False
print ("#2 thing=%r, flag=%r"%(thing,flag))
while not flag:
print ("#3 thing=%r, flag=%r" % (thing, flag))
flag = foo(int(input("Give me what I want here: ")))
print ("#5 thing=%r, flag=%r" % (thing, flag))
print ("#6 thing=%r, flag=%r" % (thing, flag))
print(thing)
输出:
#1
#2 thing=100, flag=False
#3 thing=100, flag=False
Give me what I want here: 1
#4 thing=1, flag=False,item=1
#5 thing=1, flag=False
#3 thing=1, flag=False
Give me what I want here: 0
#4 thing=0, flag=False,item=0
#5 thing=0, flag=True
#6 thing=0, flag=True
0