I'm trying to learn how to call functions in a main function, going at it with the same approach as C++ (where the main function calls all other functions defined outside of it). Here's my code:
#!/usr/bin/env python3
#MainFunctionBasics.py
def definedOutsideOfMain():
favoriteColor = input("What is your favorite color? ")
print("Your favorite color is " + favoriteColor + ".")
print("This function was defined outside of the main function.")
def main():
definedOutsideOfMain()
print()
definedOutsideOfMainAgain()
print()
futureValue = calculateFutureValue(monthlyInv, yearlyInt, numYears)
print("The future value is: " + futureValue)
print()
#main function definition ends here
def definedOutsideOfMainAgain():
favoriteBeer = input("What is your favorite beer? ")
print("Lets go drink some " + favoriteBeer + ".")
print("This function was also defined outside of the main function.")
def calculateFutureValue(monthlyInvestment, yearlyInterest, years):
monthlyInvestment = float(input("Enter the monthly investment: "))
yearlyInterest = float(input("Enter the yearly interest rate: "))
years = int(input("Enter the number of years: "))
#convert yearly values to monthly values:
monthlyInterest = yearlyInterest / 12 #/ monthlyInvestment - wtf is this?
months = years * 12
#calculate future value:
futureValue = 0.0
for i in range(0, months):#display starting at 0
futureValue += monthlyInvestment
monthlyInterest = futureValue * monthlyInterest
futureValue += monthlyInterest
return futureValue
main()
The errors are:
Traceback (most recent call last):
File "I:/Python/Python36-32/SamsPrograms/MainFunctionBasics.py", line 41, in <module>
main()
File "I:/Python/Python36-32/SamsPrograms/MainFunctionBasics.py", line 15, in main
futureValue = calculateFutureValue(monthlyInv, yearlyInt, numYears)
NameError: name 'monthlyInv' is not defined
First of all, why can't I call the main function where it is right now (if that's even the problem)?
Second, I thought name miss-matches for arguments in a calling statement and in a function definition didn't matter, as long as those arguments were in the same sequence. So What is wrong with my function call in line 15?
Calling the functions within main is fine. The problem here is you never defined these three variables monthlyInvestment, yearlyInterest, years
when you pass them to calculateFutureValue
on line 15. As it seems you want to take those from user input, you don't need to pass them at all. Change the function to accept no arguments and then don't pass anything to it.
Why are you posting different code? Start a new thread when you have a different question and code.
As to your original code and question, you may be asking the using the customers input, but it is staying inside the function. If you want the answer available outside the function, you need to "return" it.
(Nov-10-2017, 08:49 PM)sparkz_alot Wrote: [ -> ]Why are you posting different code? Start a new thread when you have a different question and code.
Look closer. The code may have changed slightly, but my questions have been relevant to the title of this thread. Just because I'm talking about passing arguments doesn't mean that I'm not also still trying to call the functions in the main function.
Here's my new code:
#!/usr/bin/env python3
#ArgumentPassingProblems.py
def main():
yearlySalary = hardCodedNamedArguments(wage, workWeek)
print()
milesPerMinute = overrideValues(speed=200, seconds=60, something=50)
print()
#main function definition ends here
def hardCodedNamedArguments(hourlyWage=62.5, weeklyWorkHours=40):
weeklyPaycheck = weeklyWorkHours * weeklyWorkHours
monthlyPaycheck = 4 * weeklyPaycheck
yearlySalary = monthlyPaycheck * 12
return yearlySalary
def overrideValues(speed, seconds):
milesPerMinute = speed / seconds
print("At " + str(speed) + "mph, you travel " + str(milesPerMinute)
+ " miles per minute.")
return milesPerMinute
main()
My errors are:
line 6, NameError: name 'wage' is not defined
line 8, TypeError: overrideValues() got an unexpected keyword argument 'something'
Traceback (most recent call last):
File "I:/Python/Python36-32/SamsPrograms/ArgumentPassingProblems.py", line 26, in <module>
main()
I'm so confused. Assigning named arguments values doesn't work in the function definition for hardCodedNamedArguments, nor does it work in the function call for overrideValues. My overrideValues function call also doesn't seem to understand that 'something' is supposed to be an extra argument (supplied as a way to override the function).
What am I doing wrong?
(Nov-10-2017, 10:37 PM)RedSkeleton007 Wrote: [ -> ]Look closer.
I did look closer, which is why I split the post. Your second post was referring to global variable, using code with entirely different variable(s), and now you're doing it again, posting code with entirely different variable names.
You could have stuck with the original code for your latest post, because the problem is the same. You cannot call a variable without first defining it (for the most part). You are trying to call the function
hardCodedNamedArguments(wage, workWeek)
without specifying what 'wage' and 'workWeek' are. You then call
overrideValues(speed=200, seconds=60, something=50)
with 3 arguments, yet the function is only expecting 2.
In the future, when you post a thread, stick with the original code. If the question is different and the code is different, start a new thread. We don't charge extra for that.
(Nov-10-2017, 11:43 PM)sparkz_alot Wrote: [ -> ]You are trying to call the function hardCodedNamedArguments(wage, workWeek)
without specifying what 'wage' and 'workWeek' are.
Without specifying what 'wage' and 'workWeek' are? I don't understand. I specified them by assigning them values in the arguments of the hardCodedNamedArgument function definition. I also tried reversing that (see the code below) by assigning them values in the function call instead, and that STILL doesn't work. What is it going to take to get my program to understand what 'wage' is?
(Nov-10-2017, 11:43 PM)sparkz_alot Wrote: [ -> ]You then call overrideValues(speed=200, seconds=60, something=50)
with 3 arguments, yet the function is only expecting 2.
If a function call is only capable of accepting the same amount of arguments that were passed into it from the function definition, then what good is overriding? Does Python even support overriding? If so, then again I ask, what am I doing wrong?
#!/usr/bin/env python3
#ArgumentPassingProblems.py
def main():
yearlySalary = hardCodedNamedArguments(wage=62.5, workWeek=40)
print()
milesPerMinute = overrideValues(speed=200, seconds=60, something=50)
print()
#main function definition ends here
def hardCodedNamedArguments(hourlyWage, weeklyWorkHours):
weeklyPaycheck = weeklyWorkHours * weeklyWorkHours
monthlyPaycheck = 4 * weeklyPaycheck
yearlySalary = monthlyPaycheck * 12
return yearlySalary
def overrideValues(speed, seconds):
milesPerMinute = speed / seconds
print("At " + str(speed) + "mph, you travel " + str(milesPerMinute)
+ " miles per minute.")
return milesPerMinute
main()
My goal here is to learn 3 things:
*How to call a function and use its default values
*How to call a function and override its default value(s)
*How to call a function with named arguments
But my book isn't explaining it very well

First, never rely on just one book, web site, video, etc. Be prepared to have several resources you can turn to.
Here are a couple examples:
# Basic function, takes no arguments. Everything it needs is within the function
def basic_func():
print("Hello World")
return
basic_func()
# A function requiring a predefined variable
def pdv_func(num):
print("The variables value is: {}".format(num))
return
number = 2.5
pdv_func(number)
# A function using a default value
def dv_func1(num = 5):
print("The default value is: {}".format(num))
return
dv_func1()
# The same function, supplying a different value
def dv_func2(num = 5):
print("The value is now: {}".format(num))
return
numb = 10
dv_func2(numb)
# A function using an optional argument
def opt_func1(*value):
print("No value was given")
return
opt_func1()
# The same thin, but now supplying a value
def opt_func2(*value):
print("The value is now: {}".format(value[0]))
print("\tNote that 'value' is of {}".format(type(value)))
return
a_value = "Hello World"
opt_func2(a_value)
the results being:
Output:
Hello World
The variables value is: 2.5
The default value is: 5
The value is now: 10
No value was given
The value is now: Hello World
Note that 'value' is of <class 'tuple'>
Process finished with exit code 0
For more options and rules look at Python's own tutorial on functions here:
Functions Tutorial.