3

I'm new to python, and I was wondering how I could recall a function until the user gives invalid input. Here's a sample of code:

start = input("For sum of squares, type 'squares'. For sum of cubes, type 'cubes'. "
              "\nIf you would like to raise a number to something other than 'squares' or 'cubes', type 'power'. "
              "\nIf you would like to exit, type 'exit':")

def main_function(start):
    while start.lower() != "exit":
        if start.lower() in "squares":
            initial = input("What is the initial constant for the sum of the squares: ")
            terms = input("Number of terms: ")

        if start.lower() in "cubes":
            initial = input("What is the initial constant for the the sum of the cubes: ")
            terms = input("Number of terms: ")



           if start.lower() in "power":
                initial = input("What is the initial constant for the the sum: ")
                terms = input("Number of terms: ")

        else:
            print("Program halted normally.")
            quit()

main_function(start)

What I am trying to get it to do is to reprompt 'start' if the user inputs a proper input, and then get it to run through the function again. I have tried putting 'start' within the function above and below the 'else' statement, but it never accepts the new input.

Veyronvenom1200
  • 95
  • 1
  • 1
  • 9

1 Answers1

2

I would do it like this, define the start input in a method and call it inside the loop, when it's equal to "exit" than break the loop.

Also use elif, this way if the first condition statement is True than you won't check the others, unless that what you want of course.

def get_start_input():
    return input("For sum of squares, type 'squares'. For sum of cubes, type 'cubes'. "
              "\nIf you would like to raise a number to something other than 'squares' or 'cubes', type 'power'. "
              "\nIf you would like to exit, type 'exit':")

def main_function():
    while True:
        start = get_start_input()
        if start.lower() == "squares":
            initial = input("What is the initial constant for the sum of the squares: ")
            terms = input("Number of terms: ")

        elif start.lower() == "cubes":
            initial = input("What is the initial constant for the the sum of the cubes: ")
            terms = input("Number of terms: ")

        elif start.lower() == "power":
            initial = input("What is the initial constant for the the sum: ")
            terms = input("Number of terms: ")

        elif start.lower() == "exit":
            print("Program halted normally.")
            break

main_function()

EDIT:

As dawg wrote in comment, it's preferred to use here == instead of in because you can have several matches and ambiguous meanings.

omri_saadon
  • 10,193
  • 7
  • 33
  • 58