0% found this document useful (0 votes)
10 views6 pages

Python Functions: Basics and Examples

Uploaded by

nananana
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views6 pages

Python Functions: Basics and Examples

Uploaded by

nananana
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Functions

Functions are reusable blocks of code that perform a specific task. They help make
the code more modular, readable, and organized.

Function Basics
A function is defined using the def keyword, followed by the function name,
parentheses (which may include parameters), and a colon. The function body contains
the code to be executed.

def greet():
print("Hello, world!")
greet() # Output: Hello, world!

Function Parameters
Functions can accept inputs called parameters. These allow you to pass data to the
function when calling it.
def greet(name):
print("Hello,", name, "!", sep='') # print without spaces
greet("Alice") # Output: Hello,Alice!

Return Values
Functions can return a result to the caller using the return keyword.
def add(a, b):
return a + b

result = add(3, 5)
print(result) # Output: 8

Default Parameters
You can define default values for parameters. These values are used if no
argument is passed for that parameter.
def greet(name = "World"):
print("Hello,",name,"!", sep='')

greet() # Output: Hello, World!


greet("Python") # Output: Hello, Python!

Docstrings
Functions can have a documentation string (docstring) to describe their purpose.
This is written as a string immediately after the function definition.
def add(a, b):
"Add two numbers and return the result."
return a + b

print(add.__doc__) # Output: Add two numbers and return the result.


print(add(3,4)) # Output: 7
Scope and Lifetime of Variables
Variables defined inside a function are local to that function and cannot be
accessed outside it. This is known as the scope of the variable.
def example():
x = 10 # Local variable
print(x)

example()
# print(x) # Error: NameError: name 'x' is not defined

In the next example x is a global variable.


def example():
print(x)

x = 10 # Global variable
example()

1. Global Variables:
• Defined outside any function or block.
• Accessible anywhere in the script, unless shadowed by a local variable.
2. Local Variables:
• Defined inside a function or block.
• Only accessible within that function or block.

Local x shadows global x.

x = 10 # Global variable

def example():
x = 20 # Local variable
print(x)

example() # Output: 20
print(x) # Output: 10

Modifying global x inside a function. To modify a global variable inside a


function, the global keyword is required. If global is not used, a new local variable x
will be created instead of modifying the global one.

x = 10 # Global variable

def example():
global x
x = 20 # Modifies the global variable
print(x)

example() # Output: 20
print(x) # Output: 20
The globals() function in Python returns a dictionary representing the global
symbol table, which contains all the global variables, functions, and other objects
defined in the global scope of the current module.
The next program views the global namespace.

"program description"
x = 10
y = 20

def example():
print(globals())

example()

Accessing global variables. You can use globals() to access global variables even
when a local variable with the same name exists.

x = 10

def example():
x = 20 # Local variable
print("Local x:", x) # x = 20
print("Global x:", globals()['x']) # x = 10

example()

Anonymous (Lambda) Functions


Python supports anonymous, single-expression functions using the lambda
keyword. The syntax for a lambda function is:
lambda arguments: expression

• arguments: The input(s) to the function. You can pass multiple arguments
separated by commas.
• expression: A single expression that the lambda function evaluates and returns.
No statements (e.g., loops, assignments) are allowed.
square = lambda x: x ** 2
print(square(4)) # Output: 16

Lambda function with multiple arguments:

add = lambda x, y: x + y # Lambda function to add two numbers


print(add(3, 5)) # Output: 8

Immediate use of lambda function:


print((lambda x, y: x * y)(3, 4)) # Output: 12
First-Class Functions
In Python, functions are first-class objects, meaning they can be assigned to
variables, passed as arguments, and returned from other functions.

Assigning a function to a variable.


def greet():
print("Hello!")

say_hello = greet
say_hello() # Output: Hello!

You can pass a function as an argument.


def apply_function(func, value):
return func(value)

result = apply_function(lambda x: x ** 2, 5)
print(result) # Output: 25

E-OLYMP 8592. Simple function Implement the function f(x) = x + sin(x).

Input. One real number x.

Output. Print the value of the function f(x) with 4 decimal digits.

Sample input 1 Sample output 1


1.1234 2.0250

Sample input 2 Sample output 2


-3.1415 -3.1416

► import math

Define the function f.


def f(x):
return x + [Link](x)

The main part of the program. Read the input value x.


x = float(input())

Compute and print the value of the function f(x).


print(f(x))
Python implementation – lambda function
import math

Define the function f.


f = lambda x: x + [Link](x)

The main part of the program. Read the input value x.


x = float(input())

Compute and print the value of the function f(x).


print(f(x))

E-OLYMP 8239. Function - 1 Implement the function f(x) = x3 + 2 * x2 – 3.

Input. Each line contains one real number x.

Output. For each value of x, print the value of the function f(x) on a separate line
with four decimal places.

Sample input Sample output


2.234 18.1309
1 0.0000
56 181885.0000
23.2 13560.6480

► The problem can be solved in two ways:


• using a loop: read x and print the value of f(x) on the fly;
• implement f(x) as a function;
Read the input data until the end of the file.
import sys

Define the f function.


def f(x):
return x ** 3 + 2 * x * x – 3

Read the input data until the end of the file. Compute and print the answer.
for x in [Link]:
x = float(x)
print(f(x))
Eolymp problems
Elementary
8592. Simple function
2864. Function tabulation
Min & Max
2606. Minimum and maximum
920. Use the function
Math functions
8239. Function – 1
8241. Function – 3
4812. Function
Recursion
1658. Factorial
1603. The sum of digits
8609. Recursion – 1
11249. Recursion – 2
8377. Persistent number
GCD, LCM
1601. GCD of two numbers
1602. LCM of two numbers
6941. Sum of GCD
Fibonacci
3258. Fibonacci Sequence
5103. Koza Nostra
8295. Fibonacci string generation
Use functions in a program
141. The minimal sum of digits
5083. Sum of digits
419. The 3n + 1 problem
Primes
1616. Prime number?
830. Prime numbers
1642. Hometask

Common questions

Powered by AI

Mathematical functions can be implemented using standard function definitions for complex operations requiring multiple lines or detailed documentation using docstrings. Lambda functions are suitable for simpler expressions and immediate use, offering a concise syntax. They are optimal in scenarios requiring compact code integration, like applying small transformations or operations inline .

The globals() function returns a dictionary of the current global symbol table, which allows access to global variables even when local variables with the same name exist. By retrieving and modifying the value of a global variable through this dictionary, a function can interact with global scope while maintaining a local variable of the same name .

Anonymous functions provide brevity and can reduce code size when used infrequently or once, making them ideal for small operations, such as callbacks or quick transformations. Named functions offer clarity and reusability, benefiting larger, more complex logic requiring documentation and testing. However, overusing anonymous functions can lead to reduced readability and maintainability, particularly in extensive codebases .

Docstrings provide a means of embedding clear and concise documentation within the function itself, which can be accessed using the function's __doc__ attribute. This helps developers understand the intention and functionality of the function without needing to consult external documentation, thereby enhancing code readability and facilitating easier maintenance .

The scope determines where a variable can be accessed, while its lifetime signifies how long the variable is retained in memory. Local variables exist only within a function's scope, preventing external access and potentially leading to NameErrors if attempted. Understanding these concepts is crucial for debugging as it prevents access to unintended variables and helps manage memory effectively in larger codebases .

First-class functions treat functions as objects that can be assigned to variables, passed as arguments, and returned from other functions. This allows for higher-order functions, function composition, and more expressive programming paradigms such as closures and decorators, thereby significantly enhancing flexibility and expressiveness in Python programming .

Lambda functions in Python allow for the creation of small, anonymous functions at runtime, which can simplify code when a function definition is needed temporarily or inline. They enhance code clarity for simple operations but are limited by the inability to include statements or multiple expressions, restricting their use to single-expression definitions only .

Default parameters allow functions to be called with fewer arguments, improving flexibility and reducing the need for overloads or auxiliary functions. However, developers must be cautious with mutable default parameter values due to potential unintentional side-effects across function calls, as these default values are evaluated only once at function definition time .

When both local and global variables with the same name are used within a function, the local variable shadows the global one, meaning the function accesses the local instance unless explicitly stated otherwise using the global keyword. This shadowing can lead to unexpected behaviors if not properly managed, requiring careful consideration of variable naming and scope .

Function annotations provide a standardized way to attach metadata to function parameters and return values, which can be used for static type checking, documentation, or input validation. These annotations coexist with docstrings and default parameters, complementing docstrings as a means of documenting expected data types and providing additional context without affecting runtime behavior [Not directly covered but inferred from context].

You might also like