简体   繁体   中英

How to define input variable in python?

Error message reads, that number is not defined in line 5:

if number < int(6):

Using Qpython on android.

looper = True
def start() :
    names = ["Mari", "Muri", "Kari"]
    number = input("Whoms name to you want to know?")
    number = int(number)
if number < int(6):
    print(names[number])
else: 
    print("There arent that many members")
while looper :
   start()

First of all, 6 is already an integer . There's no reason to type-cast it as one.

Next, you call start() after your if statement. Python reads code top-down, so the first thing it reads is your function definition, and then your if statement. Given that start() needs to be called for number to be defined, number represents nothing and cannot be compared to 6 .

Well besides how you need to call the function before using the variable, you also have a simple issue of global and local variables. Number is a local variable in the start() function and can only be used within it. If you want to use the number variable outside the function, you can use the 'global' keyword in front of it, which should allow you to use it externally. For example:

def func ():
    global var
    var = 10
func ()
print (var)

outputs 10

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM