Search code examples
python-3.xfunctionunreachable-code

Code is unreachable but I have no return function


This is my first post so I am sorry if I make any mistakes writing this. So I'm making a calculator program as my first personal program after learning enough on how to code with python. But I ran into a problem when adding the functions.

When I started the making them, the code was unreachable. I am not sure how to explain more than to show you the code. I have tried removing some code, and using global functions (which I still don't really fully understand).

import math

i = 101
j = 102
num_1 = 0
num_2 = 0
operator = 'x'

while True:
    begin = input("Welcome to calculator. Type start to begin, and q to quit ")
    if begin == 'start':
        num_1 = float(input("Enter the first number: "))
        num_2 = float(input("Enter the second number: "))
        operator = input("Enter the function ('*' for multiplication,\n '/' for division,\n '+' for addition,\n '-' for subtraction. (Case Sensitive))")
        if operator == "*":
            print("Filler")
        if operator == "/":
            print("Filler")
        if operator == "+":
            Add()
        if operator == "-":
            print("Filler")
    elif begin == 'q':
        print("quitting program...")
        exit()
    else:
        print("You must type 'start', or 'q'(Case sensitive)")

def Add():
    answer = num_1 + num_2
    print(answer + "is your answer.")

I am sorry if the code is messy, as I said this is my first program and I haven't really looked on how to style it correctly.


Solution

  • I think you can define the Add() function before it is called.

    Please try the following:

    import math
    
    def Add():
        answer = num_1 + num_2
        print(answer + "is your answer.")
    
    i = 101
    j = 102
    num_1 = 0
    num_2 = 0
    operator = 'x'
    
    while True:
        begin = input("Welcome to calculator. Type start to begin, and q to quit ")
        if begin == 'start':
            num_1 = float(input("Enter the first number: "))
            num_2 = float(input("Enter the second number: "))
            operator = input("Enter the function ('*' for multiplication,\n '/' for division,\n '+' for addition,\n '-' for subtraction. (Case Sensitive))")
            if operator == "*":
                print("Filler")
            if operator == "/":
                print("Filler")
            if operator == "+":
                Add()
            if operator == "-":
                print("Filler")
        elif begin == 'q':
            print("quitting program...")
            exit()
        else:
            print("You must type 'start', or 'q'(Case sensitive)")