Python Forum

Full Version: 1st Script written doesn't output anything. Need some else's eyes
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi All,
I am 24 hours into Python37 coding using IDLE and have written a calculator script. The calc script should request 2 variables and what needs done with them +-*/. Nothing shows when I run it in Python, it doesn"t ask any of the questions. Script is written off a youtube lesson. Any help would be appreciated. Sorry, when I edit the text all the indents are there and when I save it they all disappear. Any reason for this?

#returns the sum of num1 and num2
def add(num1, num2):
    return num1 + num2

#returns sum of subtracting num1 and num2
def sub(num1, num2):
    return num1 - num2

#returns sum of num1 * num2
def mul(num1, num2):
    return num1 * num2

#returns sum of num1 / num2
def div(num1, num2):
    return num1 / num2
    

def main(): #Shouldn't there be something between the brackets?(easier than writing parentisis)
    operation = input("What do you want to do (+,-,*,/):")
    if (operation != '+' and operation != '-' and operation != '*' and operation != '/'):
        #invalid operation
        print('You must enter a valid operation')
    else:
        var1 = int(input("Enter number1:"))
        var2 = int(input("Enter number2:"))
        if(operation == '+'):
            print(add(var1,var2))
        elif(operation == '-'):
            print(sub(var1 - var2))
        elif(operation =='*'):
            print(mul(var1 * var2))
        else:
            print(div(var1 / var2))
In your "main" function, you need to change you're elif's to look like the "if" statement, you can also remove all the redundant parenthesis:

        if operation == '+':
            print(add(var1, var2))
        elif operation == '-':
            print(sub(var1, var2))
        elif operation == '*':
            print(mul(var1, var2))
        else:
            print(div(var1, var2))
Then you need to call the function "main()". Add this to the end of your script:

if __name__ == "__main__":
    main()
@sparkz_alot Thank you for the help. While I was frustrated over this problem, my mind kept telling me "There is a better way to do this" Am I imagine this or is the code a little lunky? Perhaps a little cleaner method?

Is there any real reason to def main() at all?
(Feb-20-2018, 01:29 AM)Kym Wrote: [ -> ]Is there any real reason to def main() at all?
So your file can safely be imported from a different file. Which is useful for testing, or if you're building a library.