Program not returning to the beginning when choosing option 1

Question:

Can anyone tell me where I have a mistake that my program ends when choosing option 1 and doesn’t take me back to the beginning?

I think I have a mistake somewhere in the operation line. The program needs to by as defensive as possible so many wrong input can be thrown as an exception.

import math


def main():
    print("*****Welcome*****")
    print("Please enter two number and operation you want to perform : n")

while True:

    try:
        num1 = float(input("> Enter first number : "))
        break
    except ValueError:
        print("Oops!  That was no valid number.  Try again...")


while True:

    try:
        num2 = float(input("> Enter secend number : "))
        break
    except ValueError:
        print("Oops!  That was no valid number.  Try again...")

while True:

    try:
        operation = input("> Enter operation (+, -, *, /): ")

        if operation == '+':
            result = num1 + num2

        elif operation == '-':
            result = num1 - num2

        elif operation == '*':
            result = num1 * num2

        elif operation == '/':
            if num2 == 0:
                raise ZeroDivisionError
            result = num1 / num2
        else:
            print("Oops! Operation must be +, -, * or / Try again...")
            continue
        with open("test.txt", "a") as f:
            f.write(f"{num1} {operation} {num2} = {result}n")
            print(f"{num1} {operation} {num2} = {result}")
            print("Input and result saved to file.")
    except ZeroDivisionError:
        print("Invalid input: division by zero")
        continue

    print("nNow you have two options: n")
    print("Do you want to perform another operation? (press 1)n")
    print("Read equations from a file (press 2)n")

    while True:
        try:
            choice = int(input(" "))
            if choice == 1 or choice == 2:
                break
            else:
                print("Invalid input. Try again...")
        except ValueError:
            print("Invalid input. Try again...")

    if choice == 1:
        main()
        

    if choice == 2:
        while True:
            try:
                file_name = input("Enter file name: ").lower()
                with open(file_name, "r") as f:
                    print(f.read())
                    break
            except FileNotFoundError:
                print("File not found. Try again...")

    print("Thank you for using this calculator. Goodbye!")
    break
Asked By: Mike

||

Answers:

Your program is not properly structured with functions, and it is not looping correctly when the user selects option 1. Plus there an indent issue as well

Try the below as it should fix the issue

import math

def main():
    while True:
        print("*****Welcome*****")
        print("Please enter two numbers and the operation you want to perform : n")

        while True:
            try:
                num1 = float(input("> Enter first number : "))
                break
            except ValueError:
                print("Oops!  That was no valid number.  Try again...")

        while True:
            try:
                num2 = float(input("> Enter second number : "))
                break
            except ValueError:
                print("Oops!  That was no valid number.  Try again...")

        while True:
            try:
                operation = input("> Enter operation (+, -, *, /): ")

                if operation == '+':
                    result = num1 + num2
                elif operation == '-':
                    result = num1 - num2
                elif operation == '*':
                    result = num1 * num2
                elif operation == '/':
                    if num2 == 0:
                        raise ZeroDivisionError
                    result = num1 / num2
                else:
                    print("Oops! Operation must be +, -, * or / Try again...")
                    continue

                with open("test.txt", "a") as f:
                    f.write(f"{num1} {operation} {num2} = {result}n")
                    print(f"{num1} {operation} {num2} = {result}")
                    print("Input and result saved to file.")
                break
            except ZeroDivisionError:
                print("Invalid input: division by zero")
                continue

        print("nNow you have two options: n")
        print("Do you want to perform another operation? (press 1)n")
        print("Read equations from a file (press 2)n")

        while True:
            try:
                choice = int(input(" "))
                if choice == 1 or choice == 2:
                    break
                else:
                    print("Invalid input. Try again...")
            except ValueError:
                print("Invalid input. Try again...")

        if choice == 1:
            continue
        elif choice == 2:
            while True:
                try:
                    file_name = input("Enter file name: ").lower()
                    with open(file_name, "r") as f:
                        print(f.read())
                        break
                except FileNotFoundError:
                    print("File not found. Try again...")

        print("Thank you for using this calculator. Goodbye!")
        break

main()

output:

*****Welcome*****
Please enter two numbers and the operation you want to perform : 

> Enter first number : 2
> Enter second number : 2
> Enter operation (+, -, *, /): +
2.0 + 2.0 = 4.0
Input and result saved to file.

Now you have two options: 

Do you want to perform another operation? (press 1)

Read equations from a file (press 2)
Answered By: Abdulmajeed

Your main function only prints the welcome message, then exits. It does not prompt for input.

If you want to re-prompt, you should put the prompting code inside a function and call that at the point you call main (or put it inside main).

In general, this prompting code should be put in its own function to simplify the code and make it more expandable, though:

def get_user_input(prompt, operation):
    while True:
        try:
            return operation(input(prompt))
        except ValueError:
            print("That input was not valid, try again.")

Then, call that in place of your while loops:

num1 = get_user_input("> Enter first number: ", float)
num2 = get_user_input("> Enter second number: ", float)
...
Answered By: amycodes
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.