THEORY AND PRACTICE
-
Input and Output Data
- Tasks
-
Conditions
- Tasks
-
For Loop
- Tasks
-
Strings
- Tasks
-
While Loop
- Tasks
-
Lists
- Tasks
-
Two-Dimensional Arrays
- Tasks
-
Dictionaries
- Tasks
-
Sets
- Tasks
-
Functions and Recursion
- Tasks
Lesson 1. Data input and output in python
Python data types
Introduction to data types in programming
Imagine that you are working with different types of boxes. It can be folded into one box. only numbers, in another — only text, in the third — only the answers "yes" or "no". In programming such "boxes" are called data types. They determine which information can be stored in the variable and what operations can be performed with it.
Python is a dynamically typed language, which means that the type of a variable is defined by automatically at the time the value is assigned. This makes Python very easy to learn. and usage.
Int data type in Python
What is int?
int (integer) is a data type for storing integers. Integers — this numbers without fractional part: ..., -3, -2, -1, 0, 1, 2, 3, ...
In Python, int numbers can be arbitrarily large (limited only by volume Memory computer)
Creating variables of type int
# Creating integers
age = 25
temperature = -10
number_of_blocks = 0
large_number = 123456789012345678901234567890
print(age) # Will output: 25
print(temperature) # Outputs: -10
print(number_of_blocks) # Outputs: 0
print(large_number) # Outputs: 123456789012345678901234567890
Operations with int
# Arithmetic operations
a = 10
b = 3
addition = a + b # 13
Subtraction = a - b # 7
multiplication = a * b # 30
division_allot = a // b # 3 (the whole part of the division)
remainder = a % b # 1 (remainder of division)
power = a ** b # 1000 (10 to the power of 3)
print(f"Addition: {addition}")
print(f"Subtraction: {Subtraction}")
print(f"Multiplication: {multiplication}")
print(f"Division by whole: {division_allot}")
print(f"Remainder of division: {remainder}")
print(f"Exponentiation: {power}")
The float data type in Python
What is a float?
float (floating point number) is a data type for storage numbers with floating point (fractional numbers). These numbers contain a fractional part.: 3.14, -0.5, 2.0, 1.23e-4.
Creating float type variables
# Creating floating point numbers
price = 19.99
temperature = -5.5
pi = 3.14159
scientific_record = 1.5e3 # 1.5 * 10^3 = 1500.0
print(price) # Will output: 19.99
print(temperature) # Outputs: -5.5
print(pi) # Outputs: 3.14159
print(scientific_record) # Outputs: 1500.0
Features of working with float
# Converting int to float
integer = 5
fractional = float(integer) # 5.0
print(f"Integer: {integer}, type: {type(integer)}")
print(f"Fractional: {fractional}, type: {type(fractional)}")
# Float operations
a = 7.5
b = 2.3
result_complication = a + b # 9.8
separation_result = a / b # 3.2608695652173911
rounded_result = round(a/ b, 2) # 3.26
print(f"Addition: {result_complication}")
print(f"Division: {separation_result}")
print(f"Rounded division: {rounded_result}")
The str data type in Python
What is str?
str (string) is a data type for storing text information. information (lines). A string is a sequence of characters enclosed in quotation marks.
Creating lines
# Different ways to create strings
first_name = "Anna"
last_name = 'Ivanova'
multiline_text = """This is a text
that takes
up several lines"""
# Empty string
empty_string = ""
print(first_name) # Will output: Anna
print(last_name) # Will output: Ivanova
print(multiline_text)
print(f"Empty_string: '{empty_string}'")
Basic operations with strings
# Concatenation (addition of strings)
first_name = "Peter"
last_name = "Petrov"
full_name = first_name + " " + last_name
print(full_name) # Will output: Peter Petrov
# Repeat line
laughter = "ha" * 3
print(laughter) # Will output: hahaha
# Line length
text = "Hello world!"
length = len(text)
print(f"Line length '{text}': {length}") # Outputs: The length of the string 'Hello, world!': 12
# Accessing the characters of a string
first_character = text[0] # 'N'
last_character = text[-1] # '!'
print(f"Firstcharacter: {first_character}")
print(f"Last character: {last_character}")
bool data type in Python
What is bool?
bool (boolean) is a data type for storing boolean values. In Python, there are only two Boolean values: True and False. (false). This data type is especially important for conditional statements and loops
Creating Boolean values
# Direct creation of boolean values
true = True
false = False
print(true) # Outputs: True
print(false) # Outputs: False
# Type verification
print(type(true))
print(type(false))
Logical operations
# Logical operators
a = True
b = False
# Boolean and (and)
result_and = a and b # False
print(f"True and False = {result_and}")
# Logical OR (or)
result_or = a or b # True
print(f"True or False = {result_or}")
# Logical NOT (not)
result_a = not a # False
result_b = not b # True
print(f"not True = {result_a}")
print(f"not False = {result_b}")
Comparison operations
# Comparison operations always return bool
number1 = 10
number2 = 20
equal = number1 == number2 # False
not_equal = number1 != number2 # True
more = number1 > number2 # False
less = number1< number2 # True
more_or_equal = number1>= number2 # False
less_or_equal = number1<= number2 # True
print(f"10 == 20: {equal}")
print(f"10 != 20: {not_equal}")
print(f"10>20: {more}")
print(f"10<20: {less}")
print(f"10>= 20: {more_or_equal}")
print(f"10 <= 20: {less_or_equal}")
Differences in data types in Python
Main characteristics of data types
Understanding the differences between data types is crucial for effective programming. Each The type has its own characteristics, capabilities, and limitations.
Comparison table of data types
| Data type | Examples of values | Changeability | Basic operations | Weight (size in bytes) |
|---|---|---|---|---|
| int | -5, 0, 42, 1000 | Immutable | +, -, *, //, %, ** | From 28 bytes, depends on the size of the number |
| float | -3.14, 0.0, 2.5 | Immutable | +, -, *, /, ** | Usually 24 bytes (fixed size) |
| str | "text", 'word' | Immutable | +, *, len(), string methods | From ~49 bytes, depends on the length of the string |
| bool | True, False | Immutable | and, or, not | Usually 28 bytes |
Note: The specified weight is approximate for 64-bit systems. The size of integers (int) and strings (str) is not fixed and grows as their value or length increases.
Automatic type detection
# Python automatically determines the data type
variable1 = 42 # int
variable2 = 3.14 # float
variable3 = "Hello" # str
variable4 = True # bool
print(f"Type {variable1}: {type(variable1)}")
print(f"Type {variable2}: {type(variable2)}")
print(f"Type {variable3}: {type(variable3)}")
print(f"Type {variable4}: {type(variable4)}")
Features of operations with different types
# Mixed operations
integer = 10
fractional = 3.5
result = integer + fractional # int + float = float
print(f"10 + 3.5 = {result}, type: {type(result)}")
# Division always returns float
result_of_division = 10 / 2 # Result will be 5.0, not 5
print(f"10 / 2 = {result_of_division}, type: {type(result_of_division)}")
# Integer division
result_integer = 10 // 3 # The result will be 3
print(f"10 // 3 = {result_integer}, type: {type(result_integer)}")
Important points when working with data types
- Immutability: All considered data types (int, float, str, bool) are immutable. This means that you cannot change an existing object, but you can create a new one
- Automatic conversion: Python automatically converts types in some operations (for example, int + float = float).
- Type checking: Use the type() function to determine the type variable or isinstance() to check whether it belongs to a specific type.
- Be careful with transformations: Not all transformations are possible (for example, int("abc") will cause an error).
2. Python variables
Introduction to variables in programming
Imagine a variable as a named box in which you can put something meaning. In real life, you can write "Toys" on the box and put the toys there, or write "Books" and put books down. In programming, a variable is a name that refers to a specific value in the computer's memory.
Variables allow us to save data, change it, and use it in different parts. programs. This is one of the most important concepts in programming.
Declaring variables
What is a variable declaration?
Declaring a variable is the process of creating a variable and assigning a value to it. In Python the variable is created at the time of the first assignment of the value. No need to specify in advance type data - Python will detect it automatically.
Syntax for declaring variables
# Basic syntax: variable name = value
name = "Ivan"
age = 25
height = 1.75
student = True
print(name) # Will output: Ivan
print(age) # Outputs: 25
print(height) # Will output: 1.75
print(student) # Outputs: True
Multiple assignment
# Assigning multiple values simultaneously
x, y, z = 1, 2, 3
print(f"x = {x}, y = {y}, z = {z}") # Outputs: x = 1, y = 2, z = 3
# Assigning one value to several variables
a = b = c = 10
print(f"a = {a}, b = {b}, c = {c}") # Outputs: a = 10, b = 10, c = 10
# Exchange of variable values
first_number = 100
second_number = 200
print(f"Before the exchange: first = {first_number}, second = {first_number}")
# Exchange of values (elegant way in Python)
first_number, second_number = second_number, first_number
print(f"After the exchange: first = {first_number}, second = {second_number}")
Redefining variables
# Variables can be redefined
counter = 0
print(f"Initial value: {counter}")
counter = 5
print(f"New value: {counter}")
counter = counter + 1 # Increment by 1
print(f"Increased value: {counter}")
# Shortened notation for arithmetic operations
counter += 10 # Equivalent: counter = counter + 10
print(f"After adding 10: {counter}")
counter *= 2 # Equivalent to: counter = counter * 2
print(f"After multiplying by 2: {counter}")
Naming rules for variables
Basic rules for naming variables in programming
In Python, there are strict rules for naming variables that must be followed absolutely, and style recommendations that make the code more readable.
Mandatory rules
# CORRECT variable names:
name = "Peter"
age = 25
user_name = "ivan_petrov"
quantity_of_goods = 10
price2 = 100.0
_private_var = "secret value"
# INCORRECT variable names (will cause an error):
# 2price = 100.0 # You cannot start with a number
# user-name = "ivan" # You can't use a hyphen
# class = "mathematics" # Reserved words cannot be used
# user name = "ivan" # Spaces must not be used
Reserved words
These are reserved Python words, they cannot be used as variable names
import keyword
reserved_keywords = keyword.kwlist
print("Python Reserved words:")
for word in reserved_keywords:
print(word)
# Examples of what NOT to do:
# if = 5 # Error!
# for = "text" # Error!
# def = 10 # Error!
# Correct alternatives:
condition = 5
loop = "text"
definition = 10
Style Conventions (PEP 8)
# Use snake_case for variables (words are separated by underscores)
user_name = "Anna"
max_speed = 120
number_excess = 3
# Use descriptive names
# BAD:
x = 3.14159
n = "Ivan"
d = 1000
# GOOD:
number_pi = 3.14159
student_name_ = "Ivan"
day_charge_ = 1000
# Write constants in UPPERCASE LETTERS
MAX_SPEED = 100
quantity_SECONDS_IN_A_MINUTE = 60
COMPANY_NAME_ = "Technosoft"
# Avoid single-letter names (except for counters in short loops)
# BAD:
a = 100
b = 200
c = a + b
# GOOD:
product_price = 100
quantity = 200
total_value = product_price + quantity
Dynamic typing
What is dynamic typing?
Dynamic typing means that in Python, the type of a variable is determined during implementations programs, not while writing code. A variable can change its type in the process. program execution.
Difference from static typing
# In Python (dynamic typing):
variable = 42 # Now it is int
print(f"Value: {variable}, type: {type(variable)}")
variable = "Hello" # Now it's str
print(f"Value: {variable}, type: {type(variable)}")
variable = 3.14 # Now it's a float
print(f" Value: {variable}, type: {type(variable)}")
variable = True # Now it's bool
print(f"Value: {variable}, type: {type(variable)}")
# In languages with static typing (for example, C++, Java)
# you need to declare the type in advance:
# int variable = 42; // Will always be int
# string other = "Hello"; // There will always be a string
Advantages of dynamic typing
# Flexibility in using
def process_data(data):
"""The function can work with different types of data"""
if isinstance(data, int):
return data * 2
elif isinstance(data, str):
return data.upper()
elif isinstance(data, list):
return len(data)
else:
return f"Unknown type: {type(data)}"
# Testing with different types
result1 = process_data(10) # int
result2 = process_data("hello") # str
result3 = process_data([1, 2, 3]) # list
print(f"Result 1: {result1}") # Outputs: 20
print(f"Result 2: {result2}") # Will output: HELLO
print(f"Result 3: {result3}") # Will output: 3
Potential problems
Problem 1: Unexpected type change
counter = 0
print(f"Initial value: {counter}, type: {type(counter)}")
# Somewhere in the code...
counter = "zero" # A string was accidentally assigned
print(f"New value: {counter}, type: {type(counter)}")
# Attempting a mathematical operation will cause an error
try:
counter += 1
except TypeError as e:
print(f"Error: {e}")
Problem 2: Implicit type conversion
number1 = 10
number2 = "20"
# This will cause an error
try:
result = number1 + number2
except TypeError as e:
print(f"Addition error: {e}")
# Correct way
result = number1 + int(number2)
print(f"Correct result: {result}")
Type detection function
Basic functions for working with types
Python provides several built-in functions for defining and verifying types data. This is especially important when working with dynamic typing.
type() function
# The type() function returns the exact type of the object
number = 42
fraction = 3.14
string = "Hello"
boolean = True
list = [1, 2, 3]
print(f"type(42): {type(number)}")
print(f"type(3.14): {type(fraction)}")
print(f"type('Hello'): {type(string)}")
print(f"type(True): {type(boolean)}")
print(f"type([1, 2, 3]): { type(list)}")
# Getting the type name as a string
print(f"Type name: {type(number).__name__}")
print(f"Type name: {type(string).__name__}")
isinstance() function
# isinstance() checks whether an object is an instance of a certain type
variable = 100
# Single type verification
print(f"isinstance(100, int): {isinstance(variable, int)}")
print(f"isinstance(100, str): {isinstance(variable, str)}")
# Checking multiple types simultaneously
print(f"isinstance(100, (int, float)): {isinstance(variable, (int, float))}")
# Practical use
def safe_dividation(a, b):
"""Safe division with type checking"""
if not isinstance(a, (int, float)) or not isinstance(b, (int, float)):
return "Error: both arguments must be numbers"
if b == 0:
return "Error: division by zero"
return a / b
# Testing
print(safe_dividation(10, 2)) # 5.0
print(safe_dividation(10, 0)) # Error: division by zero
print(safe_dividation(10, "2"))# Error: both arguments must be numbers
Understanding how to work with data types and variables in Python is fundamental to writing high-quality code. Dynamic typing makes Python flexible and convenient, but It requires care when working with different types of data.
Type conversions in python
Introduction to type conversions in programming
Imagine that you have different forms for the same information: the number 42 can be write it as an integer 42, as a fraction 42.0, as a string "42", or even as a boolean value True (since any non-zero number is considered true). Type Conversion - This is the process of changing the data type of a variable from one to another.
There are two types of transformations in Python:
- Explicit conversion - when the programmer himself specifies what data needs to be converted
- Implicit conversion - when Python automatically converts types when performing operations
Explicit conversion
What is explicit conversion?
Explicit conversion is when we ourselves tell Python which type to use. convert data using special functions: int(), float(), str(), bool().
For explicit conversion, we use the following functions: int(), float(), str(), bool()
Converting an integer to a fraction, string, or Boolean type data
Converting int to float
# Converting an integer to a fractional
number = 5
fraction = float
print(f"Integer: {number}") #5
print(f"Fractional number: {fraction}") # 5.0
print(f"Type: {type(fraction)}") # <class 'float'>
Converting int to str
# Converting an integer to a string
age = 25
age_string = str(age)
print(f"Number: {age}") # 25
print(f"String: '{age_string}'") # '25'
print(f"Type: {type(age_string)}") # <class 'str'>
# Text usage
message = "Me" + str(age) + "years"
print(message) # I am 25 years old
Converting int to bool
# Converting an integer to a Boolean value
print(f"bool(0) = {bool(0)}") # False
print(f"bool(1) = {bool(1)}") # True
print(f"bool(-5) = {bool(-5)}") # True
print(f"bool(100) = {bool(100)}") # True
# Rule: 0 = False, any other number = True
Converting float variables to int, str, bool
Converting float to int
# Converting a fractional number to an integer
price = 99.99
price_integer = int(price)
print(f"Fraction: {price}") # 99.99
print(f"Integer: {price_integer}") # 99
# Attention! The fractional part is simply discarded
print(f"int(3.7) = {int(3.7)}") # 3
print(f"int(-2.9) = {int(-2.9)}") # -2
Converting float to str
# Converting a fractional number to a string
temperature = 36.6
temperature_string = str(temperature)
print(f"Number: {temperature}")
print(f"String: '{temperature_string}'")
print(f"Type: {type(temperature_string)}")
# Usage in the text
Message = "Temperature " + str(temperature) + "degrees"
print(Message)
Converting float to bool
# Converting a fractional number to a boolean value
print(f"bool(0.0) = {bool(0.0)}") # False
print(f"bool(1.5) = {bool(1.5)}") # True
print(f"bool(-0.1) = {bool(-0.1)}") # True
# Rule: 0.0 = False, any other number = True
Converting a string to integers, fractions, and Booleans a variable
Converting str to int
# Converting a string to an integer
age_string = "25"
age = int(age_string)
print(f"String: '{age_string}'")
print(f"Number: {age}")
print(f"Type: {type(age)}")
# Conversion errors
try:
number = int("abc") # Error!
except ValueError:
print("Error: cannot convert 'abc' to a number")
Converting str to float
# Converting a string to a fractional number
price_string = "99.99"
price = float(price_string)
print(f"String: '{price_string}'")
print(f"Fraction: {price}")
print(f"Type: {type(price)}")
# You can also convert integers
integer_as_a_string = "42"
fraction = float(integer_as_a_string)
print(f"'{integer_as_a_string}' -> {fraction}") # 42.0
Converting str to bool
# Converting a string to a Boolean value
print(f"bool('') = {bool('')}") # False (empty string)
print(f"bool('hello') = {bool('hello')}") # True
print(f"bool('0') = {bool('0')}") # True (the string is not empty!)
print(f"bool('False') = {bool('False')}") # True
Rule: only empty string = False, any other string = True
Converting Boolean variables to strings, fractions, and integers
Converting bool to str
# Converting a boolean value to a string
active = True
inactive = False
print(f"str(True) ='{str(active)}'") # 'True'
print(f"str(False) = '{str(inactive)}'") # 'False'
# Usage in text
status = "User " + str(active)
print(status) # User True
Converting bool to int
# Converting a boolean value to an integer
print(f"int(True) = {int(True)}") # 1
print(f"int(False) = {int(False)}") # 0
# Practical application - counting
results = [True, False, True, True, False]
correct = sum(results) # True counts as 1
print(f"Correct answers: {correct}") # 3
Converting bool to float
# Converting a boolean value to a fractional number
print(f"float(True) = {float(True)}") # 1.0
print(f"float(False) = {float(False)}") # 0.0
Implicit type conversion in python
Implicit conversion occurs automatically when Python executes operations with different types of data.
Arithmetic operations
# int + float = float
integer = 10
fractional = 3.5
result = integer + fractional
print(f"{integer} + {fractional} = {result}") # 10 + 3.5 = 13.5
print(f"Result type: {type(result)}") # <class 'float'>
# Division always gives float
division = 10 / 2
print(f"10 / 2 = {division}") #5.0 (not 5!)
print(f"Type: {type(division)}") # <class 'float'>
Operations with bool
#bool participates in arithmetic operations as a number
print(f"True + 5 = {True + 5}") # 6 (True = 1)
print(f"False * 10 = {False * 10}") # 0 (False = 0)
print(f"True + False = {True + False}") # 1 (1 + 0)
Strings and numbers
# Strings are NOT converted automatically!
try:
result = "5" + 3 # Error!
except TypeError:
print("Error: you cannot add a string and a number")
# The correct way
number_string = "5"
number = 3
result = int(number_string) + number # First convert
print(f"Correct: {result}") # 8
Comparisons
# Comparison of different numeric types
print(f"5 == 5.0: {5 == 5.0}") # True
print(f"1 == True: {1 == True}") # True
print(f"0 == False: {0 == False}") # True
# But the types are different!
print(f"type(5): {type(5)}") # <class 'int'>
print(f"type(5.0): {type(5.0)}") # <class 'float'>
Important rules
- int + float = float — for operations with integers and fractions the result is always fractional
- Division always gives a float — even if the numbers are completely divisible
- bool = number — True = 1, False = 0 in arithmetic operations
- Strings are NOT converted automatically — you need to do it explicitly
- Comparisons work between numeric types — but the types remain different
Mathematical operations in python
Existing mathematical operations
Mathematical operations are actions that can be performed with numbers. Python It supports all the basic mathematical operations that we use in everyday life. life, plus a few special ones.
Basic arithmetic operations in Python
Basic operators
Python supports five basic arithmetic operations:
Addition ( + )
# Adding numbers
a = 10
b = 5
result = a + b
print(f"{a} + {b} = {result}") # 10 + 5 = 15
# Addition with different types
integer = 7
fractional = 2.5
amount = integer + fractional
print(f"{integer} + {fractional} = {amount}") # 7 + 2.5 = 9.5
Subtraction ( - )
# Subtraction of numbers
a = 20
b = 8
difference = a - b
print(f"{a} - {b} = {difference}") # 20 - 8 = 12
# Negative numbers
result = 5 - 10
print(f"5 - 10 = {result}") # 5 - 10 = -5
Multiplication ( * )
# Multiplication of numbers
a = 6
b = 7
product = a * b
print(f"{a} * {b} = {product}") # 6 * 7 = 42
# Multiplication with fractional numbers
price = 15.5
quantity = 3
overall_cost = price * quantity
print(f"Price {price} * {quantity} = {overall_cost}") # 46.5
Division ( / )
# The usual division
a = 15
b = 3
private = a / b
print(f"{a} / {b} = {private}") # 15 / 3 = 5.0
# Division always gives float
result = 10 / 2
print(f"10 / 2 = {result}") # 10 / 2 = 5.0 (not 5!)
print(f"Type: {type(result)}") # <class 'float'>
# Division with remainder
print(f"7 / 2 = {7 / 2}") # 7 / 2 = 3.5
Special operators in python
Introduction to special operators
In addition to the basic operations, Python has three special operators for working with numbers.
// integer division
What is integer division?
Integer division (//) is a division that returns only the integer part. the result, discarding the fractional part.
# Integer division
print(f"7 // 2 = {7 // 2}") # 7 // 2 = 3
print(f"15 // 4 = {15 // 4}") # 15 // 4 = 3
print(f"20 // 6 = {20 // 6}") # 20 // 6 = 3
# Comparison with the usual division
print(f"7 / 2 = {7 / 2}") # 7 / 2 = 3.5
print(f"7 // 2 = {7 // 2}") # 7 // 2 = 3
Working with negative numbers
# Integer division with negative numbers
print(f"-7 // 2 = {-7 // 2}") # -7 // 2 = -4
print(f"7 // -2 = {7 // -2}") # 7 // -2 = -4
print(f"-7 // -2 = {-7 // -2}") # -7 // -2 = 3
# Rounding goes to a smaller integer
print(f"-7 / 2 = {-7 / 2}") # -7 / 2 = -3.5
print(f"-7 // 2 = {-7 // 2}") # -7 // 2 = -4
% remainder of division
What is the remainder of division?
The remainder of the division (%) is what remains after the integer division.
# The remainder of the division
print(f"7 % 2 = {7 % 2}") # 7 % 2 = 1
print(f"15 % 4 = {15 % 4}") # 15 % 4 = 3
print(f"20 % 6 = {20 % 6}") # 20 % 6 = 2
# If the number is completely divisible, the remainder is 0
print(f"10 % 5 = {10 % 5}") # 10 % 5 = 0
print(f"8 % 2 = {8 % 2}") # 8 % 2 = 0
Connection with integer division
# Let's check the relationship // and %
number = 17
divisor = 5
quotient = number // divisor
remainder = number % divisor
print(f"{number} = {divisor} * {quotient} + {remainder}")
print(f"17 = 5 * 3 + 2") # Verification: 5 * 3 + 2 = 17
** exponentiation in Python
What is exponentiation?
Exponentiation (**) is the multiplication of a number by itself a certain number of times.
# Exponentiation
print(f"2 ** 3 = {2 ** 3}") # 2 ** 3 = 8 (2 * 2 * 2)
print(f"5 ** 2 = {5 ** 2}") # 5 ** 2 = 25 (5 * 5)
print(f"10 ** 4 = {10 ** 4}") # 10 ** 4 = 10000
# The degree can be fractional
print(f"9 ** 0.5 = {9 ** 0.5}") # 9 ** 0.5 = 3.0 ( square root)
print(f"8 ** (1/3) = {8 ** (1/3)}") # 8 ** (1/3) = 2.0 ( the cubic root)
Special cases
# Exponentiation of 0
print(f"5 ** 0 = {5 ** 0}") # 5 ** 0 = 1
print(f"100 ** 0 = {100 ** 0}") # 100 ** 0 = 1
# Exponentiation of 1
print(f"7 ** 1 = {7 ** 1}") # 7 ** 1 = 7
# Negative degrees
print(f"2 ** -3 = {2 ** -3}") # 2 ** -3 = 0.125 (1/8)
print(f"10 ** -2 = {10 ** -2}") # 10 ** -2 = 0.01 (1/100)
Priority of arithmetic operations in python
The order of operations in programming
Python performs mathematical operations in a certain order, as in the usual math:
- Brackets
()— highest priority **Exponentiation*Multiplication, division/, integer division//, remaining%+Addition,-Subtraction is the lowest priority
Examples of priority
# Without parentheses
result1 = 2 + 3 * 4
print(f"2 + 3 * 4 = {result1}") # 2 + 3 * 4 = 14 (not 20!)
# With parentheses
result2 = (2 + 3) * 4
print(f"(2 + 3) * 4 = { result2}") # (2 + 3) * 4 = 20
# Degree is performed by the first
result3 = 2 + 3 ** 2
print(f"2 + 3 ** 2 = {result3}") # 2 + 3 ** 2 = 11 ( not 25!)
# With parentheses
result4 = (2 + 3) ** 2
print(f"(2 + 3) ** 2 = { result4}") # (2 + 3) ** 2 = 25
Operations of the same priority
# Multiplication and division are performed from left to right
result1 = 12 / 3 * 2
print(f"12 / 3 * 2 = {result1}") # 12 / 3 * 2 = 8.0
# Is equal to: (12 / 3) * 2 = 4 * 2 = 8
# AND NOT: 12 / (3 * 2) = 12 / 6 = 2
# Addition and subtraction are also left to right
result2 = 10 - 3 + 2
print(f"10 - 3 + 2 = {result2}") # 10 - 3 + 2 = 9
Complex examples
# Complex expression
expression = 2 + 3 * 4 ** 2 - 5 / 2
print(f"2 + 3 * 4 ** 2 - 5 / 2 = {expression}")
# Let's take it step by step:
# 1. 4 ** 2 = 16
# 2. 3 * 16 = 48
# 3. 5 / 2 = 2.5
# 4. 2 + 48 = 50
# 5. 50 - 2.5 = 47.5
# Let's check the steps
step1 = 4 ** 2 # 16
step2 = 3 * step1 # 48
step3 = 5/2 # 2.5
step4 = 2 + step2 # 50
step5 = step4 - step3 # 47.5
print(f"Result in steps: {step5}")
Tips for memorizing
- Always use parentheses for clarity, even if they are not needed
- Remember the abbreviation: brackets → degree → multiplication/division
- If in doubt, add parentheses
- Break complex expressions into simple parts
# It's a good practice to use parentheses for clarity.
complex_expression = ((2 + 3) * 4) - (5 / 2)
print(f"Clear expression: {complex_expression}")
# Split into parts
part1 = (2 + 3) * 4
part2 = 5 / 2
result = part1 - part2
print(f"In parts: {result}")
Output function and data formatting in Python print
print output function
The print() function is the main way to display information on the screen in Python. It allows you to show the results of the program to the user.
print output function
Basic usage
# Simple output
print("Hello, world!")
# Variable output
name = "Anna"
age = 25
print(name)
print(age)
Output of multiple values
Output of several elements at once
# Output of multiple values separated by commas
name = "Peter"
age = 30
city = "Moscow"
print(name, age, city)
# Will display: Peter 30 Moscow
# Output of different data types
number = 42
fraction = 3.14
logical = True
print(number, fraction, logical)
# Outputs: 42 3.14 True
Mixing text and variables
# Combining text and variables
name = "Maria"
age = 22
print("Name:", name, "Age:", age)
# Will output: Name: Maria Age: 22
# Output of calculation results
a = 10
b = 5
print("Sum:", a, "+", b, "=", a + b)
# Will output: Amount: 10 + 5 = 15
Sep and end parameters
Sep parameter (separator)
sep is a parameter that determines what is printed between the elements.
# By default, the space separator
print("a", "b", "c")
# Outputs: a b c
# Changing the separator to a comma
print("a", "b", "c", sep=",")
# Outputs: a,b,c
# The hyphen separator
print("a", "b", "c", sep="-")
# Outputs: a-b-c
# The separator is an empty string.
print("a", "b", "c", sep="")
# Will output: abc
Practical examples sep
# Creating a CSV string
first_name = "Ivan"
last_name = "Petrov"
age = 28
print(first_name, last_name, age, sep=",")
# Outputs: Ivan,Petrov,28
# Create a file path
folder = "documents"
subfolder = "projects"
file = "report.txt"
print(folder, subfolder, file, sep="/")
# Outputs: документы/проекты/отчет.txt
The end parameter
end is a parameter that determines what is printed at the end of the line.
# By default, there is a newline at the end.
print("First line")
print("Second line")
# Outputs:
# The first line
# The second line
# Changing the ending to a space
print("First line", end="")
print("Second line")
# Outputs: First line Second line
# The end is a point
print("Sentence", end=".")
print("Next sentence")
# Will output: An offer. The following sentence
Practical examples end
# Creating a line without hyphenation
print("Loading", end="")
print(".", end="")
print(".", end="")
print(".", end="")
print("Done!")
# Outputs: Loading... It's done!
# Output of numbers in one line
numbers = [1, 2, 3, 4, 5]
for number in numbers:
print(number, end=" ")
print() # Line break at the end
# Will output: 1 2 3 4 5
Combining sep and end
# We use both parameters
print("a", "b", "c", sep="-", end="!\n")
# Outputs: a-b-c!
# Creating a table
print("Name", "Age", "City", sep="|", end="\n")
print("Anna", "25", "Moscow", sep="|", end="\n")
print("Peter", "30", "SPb", sep="|", end="\n")
# Outputs:
# Name | Age | City
# Anna | 25 | Moscow
# Peter | 30 | St. Petersburg
Formatted data output in Python
Introduction to formatting
Formatting is a way to present data beautifully and accurately in text. Python has three the main formatting methods.
f-strings in Python
What are f-strings?
f-strings are a modern and convenient way to format strings in Python. They they start with the letter f before the quotation marks.
# The main use of f-strings
name = "Alexey"
age = 27
# Inserting variables into curly brackets
message = f"My name is {name}, I am {age} years old"
print(message)
# Will show: My name is Alexey, I am 27 years old
Calculations in f-lines
# You can perform calculations directly in line
a = 10.
b = 5
print(f"{a} + {b} = {a + b}")
# Outputs: 10 + 5 = 15
print(f"{a} *{b} = {a * b}")
# Will output: 10 * 5 = 50
# Working with more complex expressions
price = 100
quantity = 3
discount = 0.1
print(f"Total cost: {price * quantity * (1 - discount)}")
# Outputs: Total cost: 270.0
Formatting numbers
# Rounding fractional numbers
number = 3.14159
print(f"Number: {number:.2f}") # 2 decimal places
# Will output: A number: 3.14
print(f" Number: {number:.0f}") # Without fractional part
# Will output: Number: 3
# Formatting large numbers
big_number = 1234567
print(f"Number: {big_number:,}") # With separators
# Will output: Number: 1,234,567
Simple examples of f-strings
# Student information
name = "Elena"
group = "IT-21"
average_score = 4.75
print(f"Student: {name}")
print(f"Group: {group}")
print(f"Average score: {average_score:.1f}")
# Outputs:
# Student: Elena
# Group: IT-21
# Average_score: 4.8
format() function
Basics of format()
format() is a string method that allows you to insert values into certain places.
# Main use of format()
name = "Dmitry"
age = 33
# Curly braces {} are places to insert
message = "My name is {}, I am {} years old.".format(name, age)
print(message)
# Will show: My name is Dmitry, I am 33 years old
Numbering of items
# You can specify the position numbers
print("First: {0}, second: {1}".format("A", "B"))
# Outputs: First: A, second: B
# You can change the order
print("Second: {1}, first: {0}".format("A", "B"))
# Outputs: Second: B, first: A
# You can repeat
print("{0} + {0} = {1}".format(5, 10))
# Outputs: 5 + 5 = 10
Named parameters
# Using names instead of positions
print("Name: {name}, age: {age}".format(name="Olga", age=29))
# Outputs: Name: Olga, age: 29
# You can change the order
print("Age: {age}, name: {name}".format(name="Olga", age=29))
# Outputs: Age: 29, name: Olga
Formatting with format()
# Rounding up numbers
number = 3.14159
print("Number: {:.2f}".format(number))
# Outputs: Number: 3.14
print("Number: {:.0f}".format(number))
# Will output: Number: 3
# With named parameters
print("Price: {price:.2f} rubles".format(price=199.99))
# Outputs: Price: 199.99 rub.
Simple examples of format()
# Purchase information
product = "Milk"
price = 55.50
quantity = 2
message = "Product: {}, price: {:.2f}, quantity: {}, total: {:.2f}".format(
product, price, quantity, price * quantity)
print(message)
# Outputs: Product: Milk, price: 55.50, quantity: 2, total: 111.00
% data formatting
Basics of % formatting
%formatting is an old way of formatting strings in Python, similar to the C language.
# Main use of % formatting
name = "Sergey"
age = 31
# %s — for strings, %d — for integers
message = "My name is %s, I am %d years old" % (name, age)
print(message)
# Will show: My name is Sergey, I am 31 years old
The main specifiers
# %s — string
print("Name: %s" % "Anna")
# %d is an integer
print("Age: %d" %25)
# %f is a fractional number
print("Price: %f" %99.99)
#%% is the % symbol
print("Discount: %d%%" %15)
# Outputs: Discount: 15%
Formatting fractional numbers
# Specifying the number of decimal places
number = 3.14159
print("Number: %.2f" %number) # 2 signs
# Will output: A number: 3.14
print("Number: %.0f" %number) # Without fractional part
# Will output: Number: 3
# Specifying the total width
print("Number: %10.2f" %number) # 10 characters total, 2 after the decimal point
# Will output: A number: 3.14
Simple examples of % formatting
# Sales report
seller = "Ivanov"
sales = 15
revenue = 45000.50
report = "Seller: %s, sales: %d, revenue: %.2f rub." % (seller, sales, revenue)
print(report)
# Will output: Seller: Ivanov, sales: 15, revenue: 45000.50 rub.
Comparison of all formatting methods
# The same information in three ways
name = "Maria"
age = 28
salary = 50000.75
# f-strings (modern way)
print(f"Employee: {name}, age: {age}, salary: {salary:.2f}")
# format() (universal method)
print("Employee: {}, age: {}, salary: {:.2f}".format(name, age, salary))
#% formatting (the old way)
print("Employee: %s, age: %d, salary: %.2f" % (name, age, salary))
# All three will output the same way:
# Employee: Maria, age: 28, salary: 50000.75
Which formatting method should I choose?
1. f-strings are the best choice for modern Python (fast and readable)
2. format() — good for complex formatting and older versions of Python
3. % formatting — rarely used, mostly in old code
# It is recommended to use f-strings
name = "Alexey"
age = 25
# Good
print(f"Hello, {name}! You're {age} years old.")
# It's fine too
print("Hi, {}! You are {} years old.".format(name, age))
# Old style (not recommended)
print("Hello, %s! You are %d years old." % (name, age))
Data entry with input() in python
Data entry in programming languages
The input() function is the main way to receive data from a user in Python. It allows the program to interact
with a person by requesting information from them.
input() function
Basics of working with input()
The input() function stops program execution and waits for the user to enters the data and presses Enter.
# Simple use of input()
name = input()
print("Hello,", name)
What does input() return
Important: input() always returns a string (str), regardless of , what the user entered.
# We receive data from the user
data = input()
print("You have entered:", data)
print("Data type:", type(data))
Converting input data using int, float, bool functions
The problem with data types
# Problem: you can't immediately count as a number
age = input() # User enters "25"
through_year = age + 1 # Error! You can't add a string and a number together
# TypeError: can only concatenate str (not "int") to str
Conversion to int
# Correct conversion string to integer
age = input()
age = int(age)
through_year = age + 1
print("In a year you will be:", through_year)
# Can be done in one line
age = int(input())
print("Your age:", age)
Conversion to float
# Converting to a fractional number
rost_string = input()
height = float(rost_string)
print("Your height:", height, "cm")
# In one line
weight = float(input())
index_mass = weight / (height / 100) ** 2
print("Your BMI:", index_mass)
Conversion to bool
# Conversion to a logical value
response = input() # The user enters something
logical = bool(response)
print("Your answer:", response)
print("Like bool:", logical)
# Remember: only an empty string will give False
# Any non-empty string (even "false") will give True
Smart conversion to bool
# Smarter conversion
response = input()
responder_unit = response.lower()
if responder_unit in ["yes", "yes", "true", "1"]:
result = True
elif responder_unit in ["no", "no", "false", "0"]:
result = False
else:
result = bool(response) # Standard conversion
print("Result:", result)
Numeric input processing
Problems with conversion
# What happens if the user enters a non-number?
try:
number = int(input())
print("You entered a number:",number)
except ValueError:
print("It's not a number!")
Secure number entry
# Function for safely entering an integer
def get_incumber():
while True:
try:
number = int(input())
return number
except ValueError:
print("Error! Enter an integer:")
# Use
age = get_incumber()
print("Your age:", age)
Secure fractional number input
# Function for safely entering a fractional number
def get_a_detailed_number():
while True:
try:
number = float(input())
return number
except ValueError:
print("Error! Enter a number:")
# Use
height = get_a_detailed_number()
print("Your height:", height)
Range-checking input
# Entering a number in a certain range
def number_in_the_range(minimum, maximum):
while True:
try:
number = int(input())
if minimum <= number <= maximum:
return number
else:
print(f"The number must be from {minimum} to {maximum}")
except ValueError:
print("Error! Enter an integer:")
# Usage
print("Enter age from 0 to 120:")
age = number_in_the_range(0, 120)
print("Your age:", age)
The argument of the input function
The prompt parameter
The input() function can accept a single argument, prompt.
# Without invitation
name = input()
# With invitation
name = input("Enter your name: ")
Using prompt
# Examples with invitations
name = input("What is your name? ")
age = input("How old are you? ")
city = input("Where do you live? ")
print("Hello,", name)
print("You", age, "years")
print("You're from the city", city)
Beautiful invitations
# Beautiful invitation design
print("=== REGISTRATION ===")
first_name = input("Enter your first name:")
last_name = input("Enter your last name:")
email = input("Enter your email:")
print(f"\Welcome, {first_name} {last_name}!")
print(f"Your email: {email}")
Multi-line invitations
# Long invitations
invitation = """Welcome to the program!
Enter your name: """
name = input(invitation)
print(f"Hello, {name}!")
Invitations with formatting
# Invitations with additional information
product = "Bread"
price = 25.50
quantity = int(input(f"How much should I buy '{product}' at {price} RUB?"))
total_cost = price * quantity
print(f"Total cost: {total_cost} rub.")
Tips for using input()
- 1. Always use invitations - they make the program clearer.
- 2. Check your input - users may enter unexpected data.
- 3. Convert the types - remember that input() always returns a string
- 4. Handle errors - use try-except for security
The math library in Python
Modules in programming
The math module is a built—in Python library that contains many mathematical functions and constants.
It allows you to perform complex mathematical tasks. calculations such as root extraction, trigonometric functions,
logarithms, and more other.
Module import
Import methods
# Method 1: Import the entire module
import math
# Usage: math.function()
result = math.sqrt(16)
print(result) #4.0
# Method 2: Import specific functions
from math import sqrt, pi
# Usage: function() without math.
result = sqrt(16)
print(pi) # 3.141592653589793
# Method 3: Import all functions (not recommended)
from math import *
# All functions can be used without math.
result = sqrt(16)
constant = pi
Recommended method
# It is best to use full
import math
# It's more readable and secure
root = math.sqrt(25)
sine = math.sin(math.pi/2)
The main functions of the math module in Python
math.sqrt()
Square root extraction
math.sqrt() is a function for extracting the square root of a number.
import math
# Extracting the square root
print(math.sqrt(16)) # 4.0
print(math.sqrt(25)) # 5.0
print(math.sqrt(2)) # 1.4142135623730951
print(math.sqrt(100)) # 10.0
# Fractional root
print(math.sqrt(2.25)) # 1.5
print(math.sqrt(0.25)) #0.5
math.pow()
Exponentiation
math.pow() is a function for exponentiating numbers.
import math
# Exponentiation
print(math.pow(2, 3)) #8.0
print(math.pow(5, 2)) #25.0
print(math.pow(10, 0)) # 1.0
# Fractional powers
print(math.pow(8, 1/3)) #2.0 (cubic root)
print(math.pow(9, 0.5)) # 3.0 (square root)
# Negative degrees
print(math.pow(2, -3)) # 0.125 (1/8)
Comparison with the ** operator
import math
# math.pow() always returns float
print(math.pow(2, 3)) # 8.0
print(type(math.pow(2, 3))) # <class 'float'>
# The ** operator saves the type
print(2 ** 3) # 8
print(type(2 ** 3)) # <class 'int'>
Trigonometric functions
math.sin(), math.cos(), math.tan()
Trigonometric functions work with angles in radians.
import math
# Sine
print(math.sin(0)) # 0.0
print(math.sin(math.pi/2)) # 1.0 (90 degrees)
print(math.sin(math.pi)) # 0.0 (180 degrees)
# Cosine
print(math.cos(0)) # 1.0
print(math.cos(math.pi/2)) # 0.0 (practically 0)
print(math.cos(math.pi)) # -1.0
# Tangent
print(math.tan(0)) # 0.0
print(math.tan(math.pi/4)) # 1.0 (45 degrees)
Converting degrees to radians
import math
# Function for converting degrees to radians
def degree_to_radians(degrees):
return degrees * math.pi / 180
# Or use the built-in function
angle_degrees = 90
angleradians = math.radians(angle_degrees)
print(f"90° sine: {math.sin(angleradians)}") # 1.0
print(f"90°cosine: {math.cos(angleradians)}") # 0.0
math.log()
Logarithms
math.log() is a function for calculating logarithms.
import math
# Natural logarithm (base e)
print(math.log(1)) # 0.0
print(math.log(math.e)) # 1.0
print(math.log(10)) # 2.302585092994046
# Logarithm with a different base
print(math.log(8, 2)) # 3.0 (logarithm of 8 based on 2)
print(math.log(100, 10)) # 2.0 (logarithm of 100 based on 10)
# Special logarithms
print(math.log10(100)) # 2.0 (decimal logarithm)
print(math.log2(8)) # 3.0 (binary logarithm)
Other useful functions
math.ceil() and math.floor()
import math
# Rounding up
print(math.ceil(3.1))# 4
print(math.ceil(3.9))# 4
print(math.ceil(-2.1))# -2
# Rounding down
print(math.floor(3.1)) #3
print(math.floor(3.9)) #3
print(math.floor(-2.1))# -3
# Practical example
price = 99.99
quantity = 7
total_cost = price * quantity
print(f"Exact cost: {total_cost}")
print(f"Rounded up: {math.ceil(total_cost)}")
print(f" Rounded down: {math.floor(total_cost)}")
math.factorial()
import math
# Factorial
print(math.factorial(5)) # 120 (5! = 5*4*3*2*1)
print(math.factorial(0)) # 1
print(math.factorial(1)) # 1
# Practical example: placement
def placements(n, k):
return math.factorial(n) // math.factorial(n - k)
print(f"Placements from 5 to 3: {placements(5, 3)}") # 60
math.gcd() and math.lcm()
import math
# Largest common divisor
print(math.gcd(12, 18)) # 6
print(math.gcd(15, 25)) # 5
# Smallest common multiple (with Python 3.9+)
# print(math.lcm(12, 18)) # 36
# Practical example
numerator = 12
denominator = 18
nodes = math.gcd(numerator, denominator)
simplified_numerator = numerator // nodes
simplified_signifier = denominator // nodes
print(f"Fraction {numerator}/{denominator} = {simplified_numerator}/{simplified_signifier}")
math.fabs()
import math
# Absolute value (always returns float)
print(math.fabs(-5)) # 5.0
print(math.fabs(3.14)) # 3.14
print(math.fabs(-3.14)) # 3.14
# Comparison with abs()
print(abs(-5)) # 5 (int)
print(math.fabs(-5)) # 5.0 (float)
Constants in the math module in python
math.pi is the number of pi
The constant π (pi)
math.pi is the mathematical constant π ≈ 3.14159...
import math
# The value of π
print(math.pi) # 3.141592653589793
# Use in formulas
radius = 5
circumference = 2 * math.pi * radius
area_circle = math.pi * radius**2
print(f"Radius: {radius}")
print(f"Circumference: {circumference:.2f}")
print(f"Area of the circle: {area_circle:.2f}")
math.e
The constant e (Euler's number)
math.e is a mathematical constant e ≈ 2.71828...
import math
# Value of e
print(math.e) # 2.718281828459045
# Relation to the natural logarithm
print(math.log(math.e)) # 1.0
print(math.exp(1)) # 2.718281828459045 (e^1)
Useful tips
1. Always import math at the beginning of the program
2. Remember about radians in trigonometric functions
3. Check the input data for functions with constraints
4. Use the constants math.pi and math.e instead of approximations values
Examples of Python programs
Let's look at some examples of Python programs for solving various tasks.
Python program example: Circle Area Calculator
Here is a simple code to calculate the area of a circle based on a given radius:
import math
radius = float(input("Enter the radius of the circle:"))
area = math.pi * radius ** 2
print(f"The area of a circle with radius {radius} is {area:.2f}")
Python program example: Calculator
An example of a simple calculator that performs basic arithmetic operations:
operation = input("Enter the operation (+, -, *, /): ")
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
if operation == '+':
result = num1 + num2
print(f"Result: {result}")
elif operation == '-':
result = num1 - num2
print(f"Result: {result}")
elif operation == '*':
result = num1 * num2
print(f"Result: {result}")
elif operation == '/':
result = num1 / num2
print(f"Result: {result}")
else:
print("Invalid operation")
An example of a simple Python program: Currency converter
A simple example of a currency converter that uses a fixed exchange rate:
amount = float(input("Enter the amount in a currency (for example, USD): "))
rate = float(input("Enter the exchange rate (for example, 0.85 for USD in EUR): "))
converted_amount = amount * rate
print(f"Amount in the converted currency: {converted_amount:.2f}")
These examples show the main Python features for solving practical problems, such as how calculating areas, performing mathematical operations, and converting currencies.