- Running python functions from terminal
- 4 Answers 4
- Running a python method/function directly from a file
- 2 Answers 2
- Python Functions – How to Define and Call a Function
- Basic Syntax for Defining a Function in Python
- Basic Examples of a Function in Python
- Arguments in Python Functions
- How to Use the Return Keyword in Python
- Conclusion
Running python functions from terminal
I’m trying to figure out how to run my functions from my homework file. I opened up terminal, changed the directory to desktop (where my hw1.py file is), started up python, then typed «import hw1». Then I type in fizzbuzz(15) and it returns this statement:
Traceback (most recent call last): File "", line 1, in
def fizzbuzz(n): if (n % 3) == 0 and (n % 5) == 0: return "FizzBuzz" elif (n % 3) == 0: return "Fizz" elif (n % 5) == 0: return "Buzz"
4 Answers 4
import hw1 Then use hw1.fizzbuzz(15)
so you will have imported fizzbuzz into your current namespace and can then call it using fizzbuzz(15) .
import hw1 just imports the module name not all the functions defined in it so either use my_module.my_function or the from my_module import my_function syntax.
No worries, have a peek at the doc examples I linked to, there are nice easily understandable examples.
Although this question is about executing a function from a python file (as a Module) inside the Python Interpreter in Interactive Mode, it’s also possible to run a function or module with a one-liner (i.e. not use the interactive interpreter), as documented in Command line and environment. Amongst others:
When called with -c command, it executes the Python statement(s) given as command. Here command may contain multiple statements separated by newlines. Leading whitespace is significant in Python statements!
While quotation marks for strings etc. need escaping (depending on your environment), I could get the desired output on Windows 10 with Python 3.8 using:
python -c "import hw1; print(hw1.fizzbuzz(15))" FizzBuzz
I could not simply insert a newline on Windows CMD, so this may be limited to Simple statements:
A simple statement is comprised within a single logical line. Several simple statements may occur on a single line separated by semicolons.
Running a python method/function directly from a file
I would like to know if there is a way to directly run a python function directly from a file by just mentioning the filename followed by the function in a single line. For example, lets say I have a file ‘test.py‘ with a function ‘newfunction()‘. ———-test.py————
def newfunction(): print 'welcome'
python test.py newfunction
I know how to import and to call functions etc.Having seen similar commands in django etc ( python manage.py runserver ), I felt there is a way to directly call a function like this. Let me know if something similar is possible. I want to be able to use it with django. But an answer that is applicable everywhere would be great.
That is not actually what I want to know. I want to know if it can be done in a similar way to the ‘python manage.py migrate’ etc.
2 Answers 2
Try with globals() and arguments (sys.argv) :
#coding:utf-8 import sys def moo(): print 'yewww! printing from "moo" function' def foo(): print 'yeeey! printing from "foo" function' try: function = sys.argv[1] globals()[function]() except IndexError: raise Exception("Please provide function name") except KeyError: raise Exception("Function <> hasn't been found".format(function))
➜ python calling.py foo yeeey! printing from "foo" function ➜ python calling.py moo yewww! printing from "moo" function ➜ python calling.py something_else Traceback (most recent call last): File "calling.py", line 18, in raise Exception("Function <> hasn't been found".format(function)) Exception: Function something_else hasn't been found ➜ python calling.py Traceback (most recent call last): File "calling.py", line 16, in raise Exception("Please provide function name") Exception: Please provide function name
Python Functions – How to Define and Call a Function
Kolade Chris
In programming, a function is a reusable block of code that executes a certain functionality when it is called.
Functions are integral parts of every programming language because they help make your code more modular and reusable.
In this article, I will show you how to define a function in Python and call it, so you can break down the code of your Python applications into smaller chunks.
I will also show you how arguments and the return keyword works in Python functions.
Basic Syntax for Defining a Function in Python
In Python, you define a function with the def keyword, then write the function identifier (name) followed by parentheses and a colon.
The next thing you have to do is make sure you indent with a tab or 4 spaces, and then specify what you want the function to do for you.
def functionName(): # What to make the function do
Basic Examples of a Function in Python
Following the basic syntax above, an example of a basic Python function printing “Hello World” to the terminal looks like this:
def myfunction(): print("Hello World")
To call this function, write the name of the function followed by parentheses:
Next, run your code in the terminal by typing python filename.py to show what you want the function to do:
Another basic example of subtractig 2 numbers looks like this:
def subtractNum(): print(34 - 4) subtractNum() # Output: 30
Arguments in Python Functions
While defining a function in Python, you can pass argument(s) into the function by putting them inside the parenthesis.
The basic syntax for doing this looks as shown below:
def functionName(arg1, arg2): # What to do with function
When the function is called, then you need to specify a value for the arguments:
functionName(valueForArg1, valueForArg2)
Here’s an example of arguments in a Python function:
def addNum(num1, num2): print(num1 + num2) addNum(2, 4) # Output: 6
- I passed 2 arguments into the function named addNum
- I told it to print the sum of the 2 arguments to the terminal
- I then called it with the values for the 2 arguments specified
N.B.: You can specify as many arguments as you want.
How to Use the Return Keyword in Python
In Python, you can use the return keyword to exit a function so it goes back to where it was called. That is, send something out of the function.
The return statement can contain an expression to execute once the function is called.
The example below demonstrates how the return keyword works in Python:
def multiplyNum(num1): return num1 * 8 result = multiplyNum(8) print(result) # Output: 64
What’s the code above doing?
- I defined a function named multiplyNum and passed it num1 as an argument
- Inside the function, I used the return keyword to specify that I want num1 to be multiplied by 8
- After that, I called the function, passed 8 into it as the value for the num1 argument, and assigned the function call to a variable I named result
- With the result variable, I was able to print what I intended to do with the function to the terminal
Conclusion
In this article, you learned how to define and call functions in Python. You also learned how to pass arguments into a function and use the return keyword, so you can be more creative with the functions you write.
If you find this article helpful, don’t hesitate to share it with your friends and family.
Kolade Chris
Web developer and technical writer focusing on frontend technologies. I also dabble in a lot of other technologies.
If you read this far, tweet to the author to show them you care. Tweet a thanks
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
freeCodeCamp is a donor-supported tax-exempt 501(c)(3) charity organization (United States Federal Tax Identification Number: 82-0779546)
Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons — all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.
Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.