简体   繁体   中英

How do I use a function multiple times in Python?

I am having some trouble with some code. When I use a function once calling it again doesn't appear to call the function again.

credit=0
x=1
d=1
def sum1():
    global x
    global credit
while x>0:
    g=int(input("Press 1 to continue inputting money or press 0 to select    and item"))
    if g==1:
        inpt=int(input("Please insert 10p, 20p, 50p, or £1 (100p) coins   into the machine."))
        credit=credit+inpt
    else:
        print("You have "+str(credit)+" pence in your credit balance")
        x=0
sum1()
print("something")
sum1()

This is part of my code, running the function once seems to make the other one not work. Thanks for any help.

I guess you are trying to write the following code:

credit=0
x=1
d=1
def sum1():
    global x
    global credit
    while x>0:
        g=int(input("Press 1 to continue inputting money or press 0 to select    and item"))
        if g==1:
            inpt=int(input("Please insert 10p, 20p, 50p, or £1 (100p) coins   into the machine."))
            credit=credit+inpt
        else:
            print("You have "+str(credit)+" pence in your credit balance")
            x=0
sum1()
print("something")
sum1()

When you call sum1() for the first time, based on your input (when you press 0), value of x is set to zero (x = 0). So next time, when you call sum1(), the condition inside while loop is False (while x > 0), so you don't see anything.

If you use a print statement immediately after defining the function, you will see that it works twice (the function gets called twice).

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