如何使while循环分配变量?

时间:2016-11-30 22:17:13

标签: python function python-3.x variables

def valid():
    while True:
        hiOrLo = input("Type 'h' for higher and 'l' for lower.")
        if hiOrLo == "h" or hiOrLo == "l":
            return 
        else:
            print("Invalid, try again")

hiOrLo = 0
valid()

print(hiOrLo)

我的理解是Python不会通过"输入"来改变变量。而在while循环中,所以当打印hiOrLo仍然是" 0",但我需要hiOrLo才能成为" h"或者" l",无论我选择哪一个,我如何保持它的功能呢?

2 个答案:

答案 0 :(得分:7)

让函数返回该值,然后保存对它的引用。

def valid():
    while True:
        hiOrLo = input("Type 'h' for higher and 'l' for lower.")
        if hiOrLo == "h" or hiOrLo == "l":
            return hiOrLo
        else:
            print("Invalid, try again")

hiOrLo = valid()

print(hiOrLo)

答案 1 :(得分:0)

您需要全局关键字:

def valid():
    global hiOrLo
    while True:
        hiOrLo = input("Type 'h' for higher and 'l' for lower.")
        if hiOrLo == "h" or hiOrLo == "l":
            return 
        else:
            print("Invalid, try again")

hiOrLo = 0
valid()

print(hiOrLo)