Comments in Python
Comments in Python start with the character # and are used to add explanations to the code. The Python interpreter ignores comments when executing the program. There are two types of comments:
One-line comments
# This is a one-line
print comment ("Hello world!") # Comment at the end of the line
Multi-line comments
"""
This is a multi-line comment
(documentation line)
Used to describe functions, classes, and modules
"""
'''
An alternative way to create
a multi-line comment
'''
Python indentation
Indentation is a fundamental feature of Python that defines the structure of the code. Unlike other programming languages that use curly braces, Python uses indentation to group code blocks.
Margins rules:
- Standard indentation: 4 spaces
- All lines in the same block must have the same indentation
- Don't mix spaces and tabs
if condition:
# A block of code with an indentation of 4 spaces
perform_action()
another_action()
else:
# Another block of code with the same indentation level
perform another action()
Variables and data types
Python is a dynamically typed language, which means that the type of a variable is determined automatically when a value is assigned.
Main data types:
| Data type | Designation | Example |
|---|---|---|
| Integers | int |
x = 42 |
| Real numbers | float |
y = 3.14 |
| Lines | str |
name = "Python" |
| Boolean values | bool |
is_valid = True |
| Lists | list |
numbers = [1, 2, 3] |
| Tuples | tuple |
coords = (10, 20) |
| Dictionaries | dict |
person = {"name": "Alice"} |
| Sets | set |
unique_nums = {1, 2, 3} |
# Examples of variable declarations
x = 5 # int
y = 3.14 # float
name = "Alice" # str
is_student = True # bool
grades = [85, 90, 78] # list
point = (10, 20) # tuple
student_info = {"name": "Bob", "age": 20} # dict
Operators in Python
Python supports various types of operators for performing mathematical and logical operations.
Arithmetic operators:
x = 10
y = 3
Sum = x + y # 13 - addition
difference = x - y # 7 - subtraction
product = x * y # 30 - multiplication
quotient = x / y # 3.333... - division
integer division = x // y # 3 - integer division
remainder = x % y # 1 - remainder of division
degree = x ** y # 1000 - exponentiation
Comparison operators:
is equal to = x == y # False - equal to not_ equal
to = x != y # True - not equal
to more = x > y # True - more
less = x < y # False - less
is greater than equal = x >= y # True - greater than or equal
to less_ equal = x <= y # False - less than or equal to
Logical operators:
a = True
b = False
and = a and b # False - logical And
or = a or b # True - logical OR
not = not a # False - logical NOT
Conditional expressions
Conditional constructions allow you to execute different blocks of code depending on the conditions.
age = 18
if age >= 18:
print("You are of legal age")
elif age >= 13:
print("You're a teenager")
else:
print("You are a child")
The ternary operator:
# The short form of the conditional expression
status = "adult" if age >= 18 else "minor"
Loops in Python
Loops allow you to perform repetitive operations.
The for loop:
# Iterating over numbers
for i in range(5):
print(f"Iteration of {i}")
# Iterating through the list items
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)
# Iterating over the index
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
The while loop:
count = 0
while count < 5:
print(f"Counter: {count}")
count += 1
Break and continue operators:
for i in range(10):
if i == 3:
continue # Skip the iteration
if i == 7:
break # Exit the
print(i) loop
Functions
The functions allow you to group the code for reuse and better program organization.
def greeting(name, age=None):
"""
Function for greeting the user
Args:
Name (str): User name
age (int, optional): The age of the user
Returns:
str: Welcome message
"""
if age:
return f"Hello, {name}! You are {age} years old."
else:
return f"Hello, {name}!"
# Function call
message = greeting("Anna", 25)
print(message)
Lambda functions:
# Anonymous function
square = lambda x: x ** 2
print(square(5)) # 25
Multi-line instructions
Python provides several ways to write multi-line instructions.
Using parentheses:
# Long
if condition (temperature > 25 and humidity < 60 and
pressure > 1000 and wind speed < 10):
print("Great weather!")
# Long list
of products = [
"bread", "milk", "eggs",
"cheese", "butter", "meat"
]
Using a backslash:
general sum = price_toward1 + price_toward2 + \
price_toward3 + price_toward4
Nested instructions
Python supports nested constructs to create complex logic.
# Nested conditions
if the weather == "sunny":
if the temperature is 20:
if there is a time:
print("Let's go on a picnic!")
else:
print("No time for a picnic")
else:
print("It's too cold")
else:
print("The weather is not suitable")
# Nested loops
for i in range(3):
for j in range(3):
print(f"i={i}, j={j}")
Importing modules
The import system allows you to use additional functions and libraries.
# Import the entire module
import math
result = math.sqrt(16)
# Importing a specific function
from math import sqrt, pi
result = sqrt(16)
# Import with the alias
import numpy as np
array = np.array([1, 2, 3])
# Import of all functions (not recommended)
from math import *
Exception handling
Error handling is an important part of writing reliable code.
try:
number = int(input("Enter a number: "))
result = 10 / number
print(f"Result: {result}")
except ValueError:
print("Error: no number entered")
except ZeroDivisionError:
print("Error: division by zero")
except Exception as e:
print(f"Unexpected error: {e}")
finally:
print("The finally block is always executed")
Working with strings
Strings are one of the most important data types in Python.
# String creation
name = "Python"
description = 'Programming language'
multiline = """
This is a multi
-line string
"""
# Formatting strings
age = 25
# f-strings (recommended method)
message = f"My name is {first name}, I am {age} years old"
# String methods
text = "python programming"
print(text.upper()) # PYTHON PROGRAMMING
print(text.capitalize()) # Python programming
print(text.split()) # ['python', 'programming']
Lists and their methods
Lists are ordered mutable collections of elements.
# Creating a list
of numbers = [1, 2, 3, 4, 5]
mixed = [1, "text", 3.14, True]
#
Number list methods.append(6) # Add
number element.insert(0, 0) # Insert element by
number index.remove(3) # Delete element by value
last = numbers.pop() # Delete and return last element
# List
slices first_three = numbers[:3]
last_three = numbers[-2:]
each_the second = numbers[::2]
Dictionaries
Dictionaries store key-value pairs and provide quick access to data.
# Creating a dictionary
student = {
"name": "Ivan",
"age": 20,
"course": 2,
"estimates": [4, 5, 4, 5]
}
# Working with
print dictionaries(student["name"]) # Ivan
student["specialty"] = "IT" # Add a new
student key.update({"city": "Moscow"}) # Update multiple keys
# Dictionary methods
keys = student.keys()
values = student.values()
items = student.items()