Skip to content Skip to sidebar Skip to footer

Continuos Loop With User Input Condition In Python?

I just learn my first python and try to make a continuous loop that has a user input condition. #Make the calculating func def data_cal(): pennies = int(input('What's your penn

Solution 1:

You have to ask the user inside of the while loop, if he wants to try again (whatever is done in data_cal()). Otherwise the given answer can never change.

answer = ['yes','YES','Yes','y','Y']
repeat = 'yes'

#Loop for answer
whilerepeatin answer
    data_cal()
    repeat = input("Do you want to try again?")
else: print("Bye then")

Solution 2:

#Make the calculating func
repeat = ""
def data_cal():
    pennies = int(input("What's your pennies?"))
    dollars = pennies // 100
    cents = pennies % 100print("You have $", dollars, "and", cents, "cents")
    repeat = input("Do you want to try again?")
    returnrepeatrepeat = data_cal()
#User inputfor answer
answer = ['yes','YES','Yes','y','Y']
#Loop for answer

whilerepeatin answer:
    repeat = data_cal()
else:
    print("Bye then")

From the code format you have written, just move the repeat assignment line to data_cal(), and return the value so that you can use that in the while loop.

Solution 3:

You can use continue and breake to control your loop,then you can write like this

#Make the calculating funcdefdata_cal():
    pennies = int(input("What's your pennies?"))
    dollars = pennies // 100
    cents = pennies % 100print("You have $", dollars, "and", cents, "cents")

answer = ['yes','YES','Yes','y','Y']
#Loop for answerwhileTrue:
    data_cal()
    repeat = input("Do you want to try again?")
    if repeat in answer:
        data_cal()
        continueelse:
        print("Bye then")
        break

Solution 4:

You can use the while loop inside the function.

#Make the calculating func
    repeat = "yes"
    answer = ['yes','YES','Yes','y','Y']

    def data_cal():
        global repeatwhilerepeatin answer:
            pennies = int(input("What's your pennies?"))
            dollars = pennies // 100
            cents = pennies % 100print("You have $", dollars, "and", cents, "cents")
            repeat = input("Do you want to try again?")

    data_cal()
    print("Bye then")

Post a Comment for "Continuos Loop With User Input Condition In Python?"