def set_values():
cycle_num = input("Cycle Amount: ")
probability = input("Probability: ")
main_menu()
return cycle_num, probability
def display_values(cycle_num, probability):
print(cycle_num)
print(probability)
def main_menu():
user_choice = input("Choose option 1 or 2")
if user_choice == "1":
set_values()
else:
display_values(cycle_num, probability)
if __name__ == main_menu():
main_menu()
我正在努力使用另一个函数中设置的变量。我必须指明我是python的新手。我怎么能做这个工作。提前谢谢。
答案 0 :(得分:3)
有一些错误:
if __name__=='__main__'
main_menu()
set_values
时进行递归
set_values
中返回两个值但不使用它们global
关键字来实现这一点,这在很多时候都是一个坏主意尝试这样的事情:
def set_values():
cycle_num = input("Cycle Amount: ")
probability = input("Probability: ")
return cycle_num, probability
def display_values(cycle_num, probability):
print("Cycle Amount: ", cycle_num)
print("Probability: ", probability)
def main_menu():
cycle_num=0
probability=0
while True:
user_choice = input("Choose option 1, 2 or 3")
if user_choice == "1":
cycle_num, probability=set_values()
elif user_choice == "2":
display_values(cycle_num, probability)
else:
break
if __name__ == '__main__':
main_menu()
答案 1 :(得分:2)
您对scope的概念存在疑问。当您调用函数set_values()
时,您将分配两个变量,并将它们返回到调用它们的原始函数。这部分是正确的。
您遇到问题的地方是main_menu()
函数不对这些值执行任何操作。由于你不存储它们,它们就会消失。一个简单的解决方案是:
def set_values():
cycle_num = input("Cycle Amount: ")
probability = input("Probability: ")
return cycle_num, probability
def display_values(cycle_num, probability):
print(cycle_num)
print(probability)
def main_menu():
while True:
user_choice = input("Choose option 1 or 2 (ctrl-c exits): ")
if user_choice == "1":
cycle_num, probability = set_values()
elif user_choice == "2":
display_values(cycle_num, probability)
if __name__ == '__main__':
main_menu()