Python 3.x 稍后在python上调用本地定义的变量
稍后,我试图回忆这些局部定义的变量(p1、p2、w1、w2)。在我的程序中,我这样做,如果用户输入的不是数字,程序会提示用户他们输入的响应不正确。然而,这导致我的变量在本地定义,我不知道以后如何使用这些本地定义的变量。任何帮助都将不胜感激,谢谢Python 3.x 稍后在python上调用本地定义的变量,python-3.x,local-variables,Python 3.x,Local Variables,稍后,我试图回忆这些局部定义的变量(p1、p2、w1、w2)。在我的程序中,我这样做,如果用户输入的不是数字,程序会提示用户他们输入的响应不正确。然而,这导致我的变量在本地定义,我不知道以后如何使用这些本地定义的变量。任何帮助都将不胜感激,谢谢 fp=input("\nWhat percentage do you want to finish the class with?") def main(): p1 = get_number("\nWhat is your 1st marki
fp=input("\nWhat percentage do you want to finish the class with?")
def main():
p1 = get_number("\nWhat is your 1st marking period percentage? ")
w1 = get_number("\nWhat is the weighting of the 1st marking period? ")
p2 = get_number("\nWhat is your 2nd marking period percentage? ")
w2 = get_number("\nWhat is the weighting of the 2nd marking period? ")
def get_number(prompt):
while True:
try:
text = input(prompt)
except EOFError:
raise SystemExit()
else:
try:
number = float(text)
except ValueError:
print("Please enter a number.")
else:
break
return number
def calculate_score(percentages, weights):
if len(percentages) != len(weights):
raise ValueError("percentages and weights must have same length")
return sum(p * w for p, w in zip(percentages, weights)) / sum(weights)
if __name__ == "__main__":
main()
mid=input("\nDid your have a midterm exam? (yes or no)")
if mid=="yes":
midg=input("\nWhat was your grade on the midterm?")
midw=input("\nWhat is the weighting of the midterm exam?")
elif mid=="no":
midw=0
midg=0
fw=input("\nWhat is the weighting of the final exam? (in decimal)")
fg=(fp-(w1*p1)-(w2*p2)-(midw*midg))/(fw)
print("You will need to get a", fg ,"on your final to finish the class with a", fp)
将变量从一个作用域传递到另一个作用域的一种方法是
从函数返回它们:
def main():
p1 = get_number("\nWhat is your 1st marking period percentage? ")
w1 = get_number("\nWhat is the weighting of the 1st marking period? ")
p2 = get_number("\nWhat is your 2nd marking period percentage? ")
w2 = get_number("\nWhat is the weighting of the 2nd marking period? ")
return p1, w1, p2, w2
然后,在调用main
函数时,将该函数的输出指定给相应的名称:
if __name__ == "__main__":
p1, w1, p2, w2 = main()
请注意,您不必调用它们p1
、w1
、p2
、和w2
。在此阶段,您可以将它们指定给在您工作的范围内有意义的任何名称。这就是在函数外部将事物划分为函数的能力,您不必担心遵循函数内部使用的相同命名约定(您甚至可能不知道)。您还可以将四个输出一起分配/引用为元组
,即调用:
if __name__ == "__main__":
numbers = main()
然后将它们称为数字[0]
,数字[1]
,数字[2]
和数字[3]