Loops
Loops allow you to perform repetitive actions in your code. There are two main types of loops in Python: for and while.
1. for loop: used to iterate over a sequence (eg list, tuple, string).
Example:
for i in range(5): print(i)
In this example, i will take values from 0 to 4, and on each iteration of the loop, the value i.
2 will be output. while loop: executes a block of code while the condition is true.
Example:
x = 0 while x < 5: print(x) x += 1
In this example, the loop will run as long as the value of x is less than 5. On each iteration of the loop, the value of x will be printed, and x will be incremented by 1.
Basic string operations
1. Concatenation (string addition): Use the + operator to concatenate strings.
name = "John" surname = "Doe" full_name = name + " " + surname print(full_name) # "John Doe"
2. String multiplication: use the * operator to repeat a string a specified number of times.
hello = "Hello! " greeting = hello * 3 print(greeting) # "Hello! Hello! Hello! "
3. String character access: Use square brackets [] and character index.
text = "Python" first_letter = text[0] print(first_letter) # "P"
4. Line slicing: Use square brackets [] and colon : to indicate the start, end, and stride of the slicing.
text = "Python" slice_text = text[1:4] # Slice from index 1 to 3 (not including 4) print(slice_text) # "yth"
You are now familiar with loops and basic string operations in Python. In the next lesson, we'll look at lists, tuples, and sets.
- Если Вам понравилась статья, рекомендуем почитать
- Microsoft Corporation brought a new vulnerability to UEFI loading
- Linux 6.13-RC7 has already been released-the release of Linux 6.13 Stable in a few days