Python Forum
Trouble calling functions in main function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Trouble calling functions in main function
#1
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?
Reply
#2
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.
Reply
#3
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.
If it ain't broke, I just haven't gotten to it yet.
OS: Windows 10, openSuse 42.3, freeBSD 11, Raspian "Stretch"
Python 3.6.5, IDE: PyCharm 2018 Community Edition
Reply
#4
(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?
Reply
#5
(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.
If it ain't broke, I just haven't gotten to it yet.
OS: Windows 10, openSuse 42.3, freeBSD 11, Raspian "Stretch"
Python 3.6.5, IDE: PyCharm 2018 Community Edition
Reply
#6
(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 Dodgy
Reply
#7
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.
If it ain't broke, I just haven't gotten to it yet.
OS: Windows 10, openSuse 42.3, freeBSD 11, Raspian "Stretch"
Python 3.6.5, IDE: PyCharm 2018 Community Edition
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Calling functions by making part of their name with variable crouzilles 4 841 Nov-02-2023, 12:25 PM
Last Post: noisefloor
  calling external function with arguments Wimpy_Wellington 7 1,446 Jul-05-2023, 06:33 PM
Last Post: deanhystad
  Calling a function (which accesses a library) from another file mouse9095 4 823 Jun-07-2023, 08:55 PM
Last Post: deanhystad
  Run a Function?: Trouble with Online Python Course webmanoffesto 3 1,010 Aug-18-2022, 10:14 PM
Last Post: deanhystad
Sad Iterate randint() multiple times when calling a function Jake123 2 2,056 Feb-15-2022, 10:56 PM
Last Post: deanhystad
  Function global not readable by 'main' fmr300 1 1,346 Jan-16-2022, 01:18 AM
Last Post: deanhystad
  Calling a class from a function jc4d 5 1,823 Dec-17-2021, 09:04 PM
Last Post: ndc85430
  Calling functions from within a class: PYQT6 Anon_Brown 4 3,784 Dec-09-2021, 12:40 PM
Last Post: deanhystad
  [Solved] TypeError when calling function Laplace12 2 2,891 Jun-16-2021, 02:46 PM
Last Post: Laplace12
  Combine Two Recursive Functions To Create One Recursive Selection Sort Function Jeremy7 12 7,385 Jan-17-2021, 03:02 AM
Last Post: Jeremy7

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020