How do I repeat the code form the top after a while loop?

Question:

I want this code to repeat from the top. Im trying to build a calculator app and when I say "Do you want to continue (y) or go back to home (n): " I want it so that if the user says "n" then it will start the code from the beggining. Here is the code I want to do this in.

# Importing stuff
import math
import random
import time
import numpy as np


def startup():
  global ask
  print("Welcome to this math python program")
  ask = input(
    "Do you wnat to solve 1, add, 2, subtract, 3, multiply, divide, or 5 other complex problems? (answer with 1, 2, 3, 4, or 5: "
  )


startup()
# Some stuff to make it look better
print("  ")
print("  ")


def add():
  print("Addition")
  num1 = int(input("First number: "))
  num2 = int(input("Second Number: "))
  num = num1 + num2
  print("The answer is " + str(num))


# Subtract


def subtract():
  print("Subtraction")
  num3 = int(input("First number: "))
  num4 = int(input("Second Number: "))
  num5 = num3 - num4
  print("The answer is " + str(num5))
  print("  ")


def multiply():
  print("Multiplication")
  num6 = int(input("First number: "))
  num7 = int(input("Second Number: "))
  num8 = num6 * num7
  print("The answer is " + str(num8))
  print("  ")


def divide():
  print("Division")
  num9 = int(input("First number: "))
  num10 = int(input("Second Number: "))
  num11 = num9 / num10
  print("The answer is " + str(num11))
  print("  ")


def squareRoot():
  print("Square Root")
  asksqrt = int(
    input("What number would you like to find the square root of: "))
  answer1 = math.sqrt(asksqrt)
  print("The square root of " + str(asksqrt) + " is: " + str(answer1))
  print("  ")


def cubeRoot():
  print("Cube root")
  num12 = int(input("What number do you want to find the cube root of: "))
  cube_root = np.cbrt(num12)
  print("Cube root of ", str(num12), " is ", str(cube_root))
  print("  ")


def exponent():
  print("Exponents")
  num13 = int(input("First you are going to tell me the number: "))
  num14 = int(input("Next you are going to tell me the exponent: "))
  num15 = num13**num14
  print(str(num13) + " to the power of " + str(num14) + " is " + str(num15))
  print("  ")


# While loops
while ask == "1":
  print("  ")
  add()
  ask4 = input("Do you want to continue (y) or go back to home (n): ")
  while ask4 == "y":
    add()

while ask == "2":
  print("  ")
  subtract()
  ask5 = input("Do you want to continue (y) or go back to home (n): ")
  while ask5 == "y":
    add()

while ask == "3":
  print("  ")
  multiply()
  ask6 = input("Do you want to continue? (y/n) ")
  while ask6 == "y":
    add()

while ask == "4":
  print("  ")
  divide()
  ask7 = input("Do you want to continue (y) or go back to home (n): ")
  while ask7 == "y":
    add()

while ask == "5":
  ask2 = input(
    "Do you want to do a 1, square root equation, 2, cube root equation, or 3 an exponent equation? (1, 2, 3): "
  )

  print("  ")
  while ask2 == "1":
    print("  ")
    squareRoot()
    ask8 = input("Do you want to continue (y) or go back to home (n): ")
    while ask8 == "y":
      add()

  while ask2 == "2":
    print("  ")
    cubeRoot()
    ask9 = input("Do you want to continue (y) or go back to home (n): ")
    while ask9 == "y":
      add()

  while ask2 == "3":
    print("  ")
    exponent()
    ask10 = input("Do you want to continue (y) or go back to home (n): ")
    while ask10 == "y":
      add()

I’m a begginer so I dont know a lot. If you could tell me what I can do better that would be much appreciated.

Asked By: Abhay Kapatkar

||

Answers:

In this case, it’s good to take a step back and think of what your main entrypoint, desired exit scenario and loop should look like. In pseudo-code, you can think of it like this:

1. Introduce program
2. Ask what type of calculation should be conducted
3. Do calculation
4. Ask if anything else should be done
5. Exit

At points 2 and 4, your choices are either exit program or do a thing. If you want to ‘do a thing’ over and over, you need a way of going from 3 back into 2, or 4 back into 3. However, steps 2 and 4 are basically the same, aren’t they. So let’s write a new main loop:

EDIT: Decided to remove match/case example as it’s an anti-pattern

if __name__ == "__main__":                  # Defines the entrypoint for your code
    current_task = 'enter'
    while current_task != 'exit':
        current_task = ask_user_for_task()  # The user will input a string, equivalent to your startup()
        if current_task == 'add':           # If its 'add', run add()
            add()
        elif current_task == 'subtract':
            subtract()
        else:               
            current_task = 'exit'           # If its 'exit' or anything else not captured in a case, set current_task to 'exit'. This breaks the while loop

ask_user_for_task() will be an input() call where the user gives the name of the function they want to execute:

def ask_user_for_task():
    return input("Type in a calculation: 'add', 'subtract', ...")

This answer is not perfect – what if you don’t want to exit if the user accidentally types in ‘integrate’. What happens if the user types in "Add", not ‘add’? But hopefully this gives you a starting point.

Answered By: PeptideWitch

What you want to do can be greatly simplified. The number you choose correlates to the index of the operation in funcs. Other than that, the program is so simple that each part is commented.

Using this method eliminates the need for excessive conditions. The only real condition is if it is a 2 argument operation or a 1 argument operation. This is also very easily extended with more operations.

import operator, math, numpy as np
from   os import system, name

#SETUP

#function to clear the console
clear   = lambda: system(('cls','clear')[name=='posix'])

"""
this is the index in `funcs` where we switch from 2 arg operations to 1 arg operations
more operations can be added to `funcs` 
simply changing this number accordingly will fix all conditions
"""
I = 6

"""
database of math operations - there is no "0" choice so we just put None in the 0 index.
this tuple should always be ordered as:
    2 argument operations, followed by
    1 argument operations, followed by
    exit
"""
funcs   = (None, operator.add, operator.sub, operator.mul, operator.truediv, operator.pow, math.sqrt, np.cbrt, exit)

#operation ranges
twoarg = range(1,I)
onearg = range(I,len(funcs))

#choice comparison
choices = [f'{i}' for i in range (1,len(funcs)+1)]

#this is the only other thing that needs to be adjusted if more operations are added
menu    = """
choose an operation:
    1:add
    2:subtract
    3:multiply
    4:divide
    5:exponent
    6:square root
    7:cube root
    8:quit
>> """

#IMPLEMENT

while 1:
    clear()
    print("Supa' Maffs")
    
    #keep asking the same question until a valid choice is picked
    while not (f := input(menu)) in choices: pass
    
    f = int(f)
    
    #vertical space
    print("")
    
    if   f in twoarg: x = (int(input("1st number: ")), int(input("2nd number: ")))
    elif f in onearg: x = (int(input("number: ")), )
    else            : funcs[f]() #exit
        
    #unpack args into operation and print results
    print(f'answer: {funcs[f](*x)}n')
    input('Press enter to continue')
Answered By: OneMadGypsy

if you want to, you can see the code below:

while(input("want to continue (y/n)?") == 'y'):
operation = input("operation: ")
num_1 = float(input("first num: "))
num_2 = float(input("second num: "))
match operation:
    case "+":
        print(num_1 + num_2)
    case "-":
        print(num_1 - num_2)
    case "*":
        print(num_1 * num_2)
    case "/":
        print(num_1 / num_2)
    case other:
        pass

  

make sure you have the version 3.10 or later of python

Answered By: FrankAyra
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.