Tasks studies - laboratory
Some functions were already used in the previous lesson, such as the print()
function. These were built-in functions provided with Python libraries.
print("Hello world!")
a = []
a.extend(range(2, 20))
print(a)
print(str(12))
print(list(range(10, 20, 3)))
Below is an example of a simple function that can be written manually. Each newly created function has a header consisting of the `def` keyword, the function name, and the parameters it accepts, enclosed in parentheses. Then comes the function body, which performs specific tasks. A function can be called by providing its name along with the appropriate parameters. A simple example function and its call are presented below.
> It is important to remember that the code block inside any function starts with a colon and must be indented. :exclamation:
```Python
def my_func():
print("spam")
print("spam")
print("spam")
my_func()
To call a function correctly, it must be defined before its call. Running the following code will result in an error: NameError: name 'hello' is not defined
.
hello()
def hello():
print("hello")
To improve code readability, comments are used. In Python, a single-line comment is written with #
at the beginning of the commented line. A multi-line comment is created using triple quotes.
def shout(word):
"""
Multi-line comment
"""
# Single-line comment
print(word + "!")
shout("spam")
Function arguments are used like variables inside the function and cannot be used outside of it. The same applies to variables created within the function.
def print_with_exclamation(word):
print(word + "!")
print_with_exclamation("spam")
print_with_exclamation("eggs")
print_with_exclamation("python")
def print_sum_twice(x, y):
print(x + y)
print(x + y)
print_sum_twice(2, 5)
The function below uses the var
parameter inside its body, which is not accessible outside the function. This means that these variables are local.
def function(var):
var += 1
print(var)
function(7)
print(var)
Certain functions, such as int
or str
, return a value that can be used later. To make a function return a value, it must include the return
keyword.
def max(x, y):
if x >= y:
return x
else:
return y
print(max(4, 6))
z = max(9, 3)
print(z)
If the return
keyword appears at a certain level in the function, none of the instructions written after it will be executed.
def add_numbers(x, y):
sum = x + y
return sum
print("This line will not be displayed")
print(add_numbers(4, 5))
Although they are created differently than normal variables, functions are like any other value. They can be assigned to variables and overwritten, and then called using their name.
def multiply(x, y):
return x * y
a = 4
b = 6
operation = multiply
print(operation(a, b))
Below is an example of passing one function as a parameter to another function.
def add(x, y):
return x + y
def do_twice(func, x, y):
return func(func(x, y), func(x, y))
a = 5
b = 10
print(do_twice(add, a, b))
import random
for i in range(5):
val = random.randint(1, 6)
print(val)
To import all objects from a module, use
*
, e.g.,from math import *
. :exclamation:
from math import pi
print(pi)
If an attempt is made to import a module that is not available, e.g., import any_module
, an ImportError
exception is raised.
Imported modules or selected objects within them can be used under a different name by defining keywords for them using the as
operator.
from math import sqrt as square_root
print(square_root(100))
Python has three main types of modules: user-written modules, modules installed from external sources, and built-in Python modules. The modules used earlier are part of Python’s standard libraries. Python provides many useful modules, some of which allow operations on strings, date objects, mathematical operations, JSON handling, multithreading, and many more.
Many additional Python modules can be found in PyPI (Python Package Index). To install an additional module, use the pip
tool. To install a module, enter the following command in the terminal:
pip install module_name
Once installed, the module can be used freely in the code.
Errors inform the user that something went wrong. When an error is detected, the program immediately stops. One of the most common errors is division by zero, which raises a ZeroDivisionError
.
Other frequently occurring errors include:
:small_blue_diamond: ImportError
:small_blue_diamond: IndexError
:small_blue_diamond: NameError
:small_blue_diamond: SyntaxError
:small_blue_diamond: TypeError
:small_blue_diamond: ValueError
To handle an exception that may occur, the try/except
statement is used. The try
block can have multiple except
blocks to catch different types of errors. Multiple error types can also be grouped in a single except
block.
try:
var = 100
print(var + "hello")
print(var / 2)
except ZeroDivisionError:
print("Division by 0")
except (ValueError, TypeError):
print("Some error occurred")
An except
block without specifying an error type will catch all exceptions.
try:
word = "spam"
print(word / 0)
except:
print("Error detected")
finally
BlockThis is placed after try
and except
blocks. It ensures that a certain code fragment executes regardless of whether an error occurs.
try:
print("hello")
# print(1/0)
except ZeroDivisionError:
print("Division by 0")
finally:
print("This line will always execute")
raise
StatementUsed to manually raise an exception.
print(1)
raise ValueError
print(2)
name = "123"
raise NameError("Invalid name")
print(name)
Assertions test whether a condition holds true after executing a code fragment. If it does not, an exception is raised.
print(1)
assert 2 + 2 == 4
print(2)
assert 1 + 1 == 3
Assertions can also take a second argument, which is displayed if the assertion fails.
temp = -10
assert temp >= 0, "Less than 0"
To edit a file in Python, it must first be opened using:
myfile = open("spam.txt")
The
open
function’s argument is the file path. If the file is in the project directory, just enter its name. :exclamation:
file = open("newFile.txt", "w")
file.write("This text will be saved to the file")
file.close()
Using the with
statement ensures that files are always properly closed.
with open("filename.txt") as f:
print(f.read())
2-7 must be added to GitHub.