cancel
Showing results for 
Search instead for 
Did you mean: 
  • 238 Views

Question on Python Functions

"I’m having trouble understanding how to use functions in Python. Can anyone explain with examples?"
Labels (1)
Tags (1)
3 Replies
Commoner
Cadet
Cadet
  • 155 Views

#!/usr/bin/env python3

# add_things function defined
# note that the scope of a and b are limited to this function definition
def add_things(a, b):
return a + b

# subtract_things function defined
# note that the scope of a and b are limited to this function definition
def subtract_things (a, b):
return a - b

# Start of main program

first_num = 40 (but we could have called this 'a' as the scope is different than the function definitions above)
second_num = 50 (but we could have called this 'b' as the scope is different than the function definitions above)

# Add my two numbers and print it
print(add_things(first_num, second_num))

#subtract the second number from the first and print
print(subtract_things(first_num, second_num))

#subtract the first number from the second
print(subtract_things(second_num, first_num))

Commoner
Cadet
Cadet
  • 155 Views

The output when you run the executable.

For example if the file is called test.py (and I have set the execution bit on the file test.py) I can type this command from the directory that has the test.py file:

./test.py

If I do not have the execution bit set, I can execute the file (assuming that I am in that directory with:

python3 test.py

 

And the result should be (I didn't actually execute this in an environment, so typos may be present):

90

-10

10

Chetan_Tiwary_
Community Manager
Community Manager
  • 117 Views

@AvalaVinay Functions in Python can be understood as mini programs residing within your larger program. They are designed to execute specific tasks. Once defined, a function can be invoked repeatedly throughout your code, eliminating the need to rewrite the same code segments multiple times.

To define a function, you use the def keyword followed by the name of the function and parentheses (). If the function takes any arguments, they are included within the parentheses. The code block for the function is then indented after the colon.

Chetan_Tiwary__1-1737574092560.png

1. def my_function(first_name, last_name):

This line defines a function named my_function.
first_name and last_name are parameters. These are like placeholders for values that will be passed to the function when it's called.


2. print(first_name + " " + last_name)

This line is the body of the function.
It takes the first_name and last_name parameters and concatenates (joins) them with a space in between.
Finally, it prints the resulting full name to the console.


3. my_function("Chetan", "Tiwary")

This line calls the my_function.
"Chetan" is passed as the first_name argument.
"Tiwary" is passed as the last_name argument.

Hence the output : Chetan Tiwary

Tags (3)
Join the discussion
You must log in to join this conversation.