Содержание:
- Built-in Functions, Strings, and math
- 📑 Table of Contents
- 🔧 Built-in Functions: min(), max(), abs()
- 📝 The String Data Type (str)
- 📏 String Length — The len() Function
- 🔢 Converting Numbers to Strings — The str() Function
- ➕ String Operations — Concatenation
- 🔁 String Repetition — Multiplying Strings
- 🔍 The in Operator — Checking Substrings
- 🔢 The math Module
- 🔽 Rounding Functions — Comparison
Built-in Functions, Strings, and math
Essential Tools | Functions, Strings, and Mathematics
🔧 Built-in Functions: min(), max(), abs()
Python includes many pre-defined functions that are ready to use. A programmer doesn’t need to see their implementation — it’s hidden. It’s enough to know what these functions are called and what they do.
We have already encountered several built-in functions:
print()— display output on the screeninput()— read from the keyboardint()— convert to an integerfloat()— convert to a floating-point number
Now we explore three more built-in functions frequently used when working with numbers.
📌 The min() and max() Functions
The min() function returns the smallest value among its arguments, while max() returns the largest value.
min(value1, value2, value3, ...) max(value1, value2, value3, ...) |
Important: These functions can take any number of arguments, as long as all arguments support comparison operations (e.g., integers and floats can be compared, but floats and strings cannot).
a = max(3, 8, -3, 12, 9) b = min(3, 8, -3, 12, 9) c = max(3.14, 2.17, 9.8) print(a) # 12 print(b) # -3 print(c) # 9.8 |
Key points:
min()andmax()work with both integers and floats.- They can also work with strings (lexicographic comparison).
- The arguments can be numbers, variables, or expressions.
📌 The abs() Function
The absolute value (or modulus) of a number is defined as:
- The number itself, if it is positive or zero.
- The opposite of the number, if it is negative.
Mathematically: |a| = a if a ≥ 0, and |a| = -a if a < 0.
In Python, the abs() function returns the absolute value of a number.
print(abs(10)) # 10 print(abs(-7)) # 7 print(abs(0)) # 0 print(abs(-17.67)) # 17.67 |
Key points:
abs()works with both integers and floats.- The result is always non-negative.
Note: All three functions — min(), max(), and abs() — work with both integers and floating-point numbers. This makes them very versatile.
📝 The String Data Type (str)
The string data type, named str (short for "string" — a sequence of characters), is used to represent text in Python.
📌 Creating Strings
Python allows both single quotes ' and double quotes " for creating strings. This is useful when you need to include quotes inside the string.
s1 = 'Python rocks!' s2 = "Python rocks!" # Both are valid s3 = "'Multi-line string example'" # Including quotes inside strings: s4 = 'She said "Hello"' s5 = "He said 'Goodbye'" |
📌 Empty Strings
An empty string contains no characters.
empty = '' # Empty string space = ' ' # String with one space — not empty! |
Don't confuse: An empty string '' is different from a string containing a single space ' ' — they are completely different values.
📏 String Length — The len() Function
The length of a string is the number of characters it contains. The built-in function len() calculates this.
s1 = 'abcdef' length1 = len(s1) # 6 length2 = len('Python rocks!') # 13 print(length1) # 6 print(length2) # 13 |
Important: When counting string length, all characters are counted, including spaces and punctuation.
🔢 Converting Numbers to Strings — The str() Function
We have already used int() and float() to convert strings to numbers. For the reverse operation — converting a number to a string — we use the str() function.
num1 = 1777 # integer num2 = 17.77 # floating-point number s1 = str(num1) # '1777' s2 = str(num2) # '17.77' print(type(s1)) # <class 'str'> print(type(s2)) # <class 'str'> |
Why convert numbers to strings? Sometimes working with strings is much easier than working with numbers. Even if a problem says "a number is given", nothing prevents us from treating it as a string (especially when we need to access individual digits).
➕ String Operations — Concatenation
Strings can be added together. The operation of adding strings is called concatenation.
s1 = 'ab' + 'bc' s2 = 'bc' + 'ab' s3 = s1 + s2 + '!!!' print(s1) # 'abbc' print(s2) # 'bcab' print(s3) # 'abbcbcab!!!' |
Important: Unlike addition of numbers, string concatenation is not commutative — the order matters!
print('ab' + 'bc') # 'abbc' print('bc' + 'ab') # 'bcab' — different result! |
📌 Using Concatenation for Output
Both approaches produce the same output:
# Both produce the same output: print('a', 'b', 'c', sep='*', end='!') print() print('a' + '*' + 'b' + '*' + 'c' + '!') |
Output:
a*b*c! a*b*c!
🔁 String Repetition — Multiplying Strings
Python allows you to multiply a string by a non-negative integer. This operator repeats the string the specified number of times.
s = 'Hi' * 4 print(s) # 'HiHiHiHi' # Print a line of 75 dashes print('-' * 75) |
Edge cases:
print('Hello' * 0) # '' (empty string) print('Hello' * 1) # 'Hello' (unchanged) |
Interesting fact: The ability to multiply strings by a number is not available in many other programming languages. It's one of Python's convenient features.
🔍 The in Operator — Checking Substrings
The in operator checks whether one string is contained within another string.
s = 'https://python.org/' if 'a' in s: print('The string contains the character "a"') else: print('The string does not contain the character "a"') |
Output:
The string does not contain the character "a"
📌 Using in with not
We can combine in with the not operator:
s = input() if '.' not in s: print('The string does not contain a dot') else: print('The string contains a dot') |
📌 Simplifying Conditions with in
Instead of writing long conditions with multiple or operators, we can use in.
Without in (verbose):
s = input() if s == 'a' or s == 'e' or s == 'i' or s == 'o' or s == 'u': print('YES') |
With in (clean and concise):
s = input() if len(s) == 1 and s in 'aeiou': print('YES') |
📌 Exact Substring Matching
The in operator checks for exact sequence matching — characters must be in the same order and consecutive.
print('ab' in 'abc') # True — 'ab' appears exactly print('ac' in 'abc') # False — 'a' and 'c' are not consecutive |
📌 Case Sensitivity
The in operator is case-sensitive.
s = 'Alpha' print('p' in s) # True — lowercase 'p' exists print('P' in s) # False — uppercase 'P' does not exist |
Important: If s1 is contained in s2, we say that s1 is a substring of s2. The in operator determines whether one string is a substring of another.
🔢 The math Module
One of Python's advantages is the large number of ready-to-use functions. These functions are organised into modules. A module is a library of functions that can be imported into your program.
The math module is one of the most important in Python. It provides extensive functionality for performing calculations with real numbers.
📌 Importing the Module
import math num1 = math.sqrt(2) # square root of 2 num2 = math.ceil(3.8) # round up num3 = math.floor(3.8) # round down print(num1) # 1.4142135623730951 print(num2) # 4 print(num3) # 3 |
📌 Importing Specific Functions
If you want to avoid typing the module name each time, you can import specific functions.
from math import sqrt, ceil print(sqrt(25)) # 5.0 print(ceil(3.8)) # 4 # print(floor(3.8)) # Error — floor is not imported |
Alternative — Import Everything:
from math import * print(sqrt(25)) # 5.0 print(ceil(3.8)) # 4 print(floor(3.8)) # 3 |
Best practice: While from math import * is convenient, it's generally better to import only what you need, or import the whole module with import math. This makes your code more readable and avoids namespace conflicts.
📌 Commonly Used Functions in the math Module
Rounding functions:
| Function | Description |
|---|---|
floor(x) |
Rounds down (towards negative infinity) |
ceil(x) |
Rounds up (towards positive infinity) |
Roots, powers, and factorial:
| Function | Description | Example |
|---|---|---|
sqrt(x) |
Square root of x | sqrt(16) → 4.0 |
pow(x, n) |
x raised to the power n | pow(2, 3) → 8.0 |
log(x) |
Natural logarithm of x | log(2.718) ≈ 1.0 |
log10(x) |
Base-10 logarithm of x | log10(100) → 2.0 |
log(x, b) |
Logarithm of x with base b | log(8, 2) → 3.0 |
factorial(n) |
Factorial of n | factorial(5) → 120 |
Trigonometric functions:
| Function | Description |
|---|---|
degrees(x) |
Converts radians to degrees |
radians(x) |
Converts degrees to radians |
cos(x) |
Cosine of x (radians) |
sin(x) |
Sine of x (radians) |
tan(x) |
Tangent of x (radians) |
acos(x) |
Arc cosine of x (returns radians) |
asin(x) |
Arc sine of x (returns radians) |
atan(x) |
Arc tangent of x (returns radians) |
atan2(y, x) |
Polar angle of point (x, y) (returns radians) |
📌 Constants in the math Module
The math module also provides important mathematical constants:
| Constant | Description | Value |
|---|---|---|
math.pi |
The number π | 3.141592653589793 |
math.e |
Euler's number | 2.718281828459045 |
import math radius = 5 area = math.pi * radius ** 2 print(area) # 78.53981633974483 |
🔽 Rounding Functions — Comparison
Python provides several ways to round numbers. Choose based on your needs.
| Function | Description | Example |
|---|---|---|
int() |
Rounds towards zero | int(3.8) → 3, int(-3.8) → -3 |
round(x) |
Rounds to nearest integer; .5 rounds to even (banker's rounding) | round(3.5) → 4, round(4.5) → 4 |
math.floor(x) |
Rounds down (towards negative infinity) | floor(3.8) → 3, floor(-3.8) → -4 |
math.ceil(x) |
Rounds up (towards positive infinity) | ceil(3.8) → 4, ceil(-3.8) → -3 |
round(x, n) |
Rounds to n decimal places | round(3.14159, 2) → 3.14 |
📌 Comparison Table
| Number | int() | round() | floor() | ceil() |
|---|---|---|---|---|
| 3.2 | 3 | 3 | 3 | 4 |
| 3.8 | 3 | 4 | 3 | 4 |
| -3.2 | -3 | -3 | -4 | -3 |
| -3.8 | -3 | -4 | -4 | -3 |
| 3.5 | 3 | 4 | 3 | 4 |
| 4.5 | 4 | 4 (banker's) | 4 | 5 |
Interesting fact: The round() function uses "banker's rounding" (round half to even) to reduce bias in statistical calculations. This is different from the rounding taught in many schools.