I'm messing around with parameter passing in functions. The total is not being correctly passed here. What is the problem?
@tdudek, It will make it less confusing (and will make it work correctly) to remove the parameters from
InputNums and use
global num1, num2 in the line below the function definition so that you're actually storing the value you receive into
total used in this way doesn't make sense. Your global variable
total set in the bottom to 0 is not doing anything in the script. There's no reason for it to be defined beforehand since you are only using it when it's called in
There are several different ways to do this, so I just chose this way based on what you had.
#Declaring the functions def InputNums(): #remove all parameters and use global num1, num2 to store value #this way num1 and num2 can be used in the next function global num1, num2 num1=int(input("Enter the first number: ")) num2=int(input("Enter the second number: ")) #removed total from parameter as its not needed until its made def CalculateProduct(num1,num2): total=num1*num2 print("The product of the two numbers is: ",str(total)) #Setting all variables to zero #removed total from global scope as its not needed num1=0 num2=0 #Calling the functions #remove num1, num2 from parameters InputNums() #removed total from parameter as its not needed until its made in the function itself CalculateProduct(num1,num2)
@tdudek When you're passing variables between modules, what you want to do is
return values from that module back to the main script so that they can be used. In this case, you don't need the
global keyword to store the values.
main.py needs to be changed slightly and
input_module.py needs to be changed slightly.
main.py will call
input_module and then get those values back from the
Here's a repl I made from your code: https://repl.it/@heyitsmarcus/Module-Example-3-1
#Developed on 28 June 2019 #importing the modules import input_module import product_module #Main Program #Setting all variables to zero #total=0 num1=0 num2=0 #Calling the modules #Only change here is that num1, num2 get the values back from the called module num1, num2 = input_module.InputNums() product_module.CalculateProduct(num1, num2)
def InputNums(): #remove all parameters and use global num1, num2 to store value #this way num1 and num2 can be used in the next function #global num1,num2 num1=int(input("Enter the first number: ")) num2=int(input("Enter the second number: ")) #And the module now returns those values return num1, num2