Python: for loops, constants, slices, tuples, sequences len, range, in, choice


We continue to learn the programming language. Let’s move on to chapter 4 of the book: Michael Dawson “Python Programming”, 2014 (Michael Dawson “Python Programming for the Absolute Beginner”, 3rd Edition), where we will study loops with the for () operator, introducing constants into code, slices and tuples, working with sequences on the example of strings with the operators len(), range(), in, jumble(), etc.

Summary of chapter 4 with examples of programs I wrote:

Cycles (loops) for

We already know loops with the while statement, and have even done a lot of tasks. Remember, there is a control variable introduced before the loop, which is then used in the condition, which in turn is tested for truth every round of the loop. So with the for loop, things are a little different.

The for loop does not use a conditional construct to test whether to do or not to do. The for loop is executed cyclically for all elements of the sequence. Once the code has been repeated for each element of the loop sequence, the loop ends. Simply put, a for construct is a loop with a precondition or a loop with a parameter. The essence of the work of this loop is to enumerate values in sequence.

What is this sequence of the for loop, what is it all about? I also did not immediately understand the difference between these cycles and those with which we worked earlier. The fact is that for in fact simply repeats the same action (loop body) for a pre-specified list of elements (sequence), which is explicitly specified in the loop itself. General view of the for loop:

for sequence elements:
    do something (operator)

The sequence can be anything – a numeric or a string of text. Variables can be introduced both before the for loop and inside it. Many programming languages have for loops, but Python has a lot of freedom for this loop and there is no need to use a counter (increment / decrement).

But if you still want to use a counter, then you can enter a counter variable among the elements of the sequence, which in Python is usually denoted by one of three characters:

  • i
  • j
  • k

The for loop allows you to organize sequential access to the elements of a sequence. 

The easiest way to see how the for loop works is with an example:

Program “Word by Spell”

word=input('Напечатай любое слово\n')
for bukva in word:
    print(bukva)

In this program, the initialization goes through the variable bukva in the sequence of the string type word (what the user enters). The user enters any text, and the program displays this text letter by letter on each line.

range() function for numeric sequence

General structure of the function range():

range(count start, end of count [not including it], interval)

The interval can be either positive or negative. If the interval is -1, then the program will count, decrementing the value by 1 each time.

🐍 Idea!
If you just need to repeat some action a given number of times, then you can not write a variable in the for loop, but simply use a loop with the range () function

for _ in range(5):
    print('кот')

The operation of the range() function in a for loop is easiest to see with an example:

Program “Counting”

Task: Write a program that 1) prints all integers from 0 to 10 in a line; 2) Lists integers from 0 to 10 that are multiples of 10; 3) Displays all integers from 0 to 10 in reverse order.

print('Считалка 0-10')
for num in range(11):
    print(num, end=' ')
print('\nСчиталка 0-100, кратные 10')
for num_1 in range(0,101,10):
    print(num_1, end=' ')
print('\nСчиталка 10-0')
for num_2 in range(10,-1,-1):
    print(num_2, end=' ')

Function len()

This function returns the length of the sequence given in parentheses.

text=input('Введите текст\n')
print('Длина=',len(text))

Operator in

The general form of using the in operator is a condition that is checked each time for true and false:

variable in sequence

Programme Text Analyzer”

Task: write a program that parses the text entered by the user. As a result of the analysis, the program displays the length of the sequence and reports whether the letter “a” is present or not in this sequence.

text=input('Введите текст\n')
print('Длина последовательности:',len(text))
if 'а' in text:
    print('Буква "а" встречается в этом тексте')
else:
    print('Буква "а" не встречается в этом тексте')

Sequence element indexing

The for loop usually just goes through all the elements of the sequence in a row in turn, if we need to get a specific element, then after the name of the variable that specifies the sequence, we put the element’s serial number in square brackets (the index starts from zero):

variable[5]

Indexes are of two types:

  • with positive numbers (the count starts from 0 and goes forward);
  • with negative numbers (count goes from -1, starts from the end of the line and goes to the left).

An example of using indexing is shown in the programme:

Program “Random Letters”

Task: Write a program that asks the user to enter any word, and then displays random letters of this word as many times as there are letters in the entered word.

import random
word=input('Напиши слово\n')
konec=(len(word)-1)
nachalo=-len(word)
for i in range(len(word)):
    index=random.randrange(nachalo,konec)
    print(word[index],'\n')

Program “Only vowels”

Task: Write a program that allows the user to enter text, and then prints only in vowels.

text=input('Введите текст, а я напечатаю его только согласными.\n')
GLASNIE='аоуэюяыиеё'
text_glasnie=''
for i in text:
    if i.lower() in glasnie:
        text_glasnie+=i
print(text_glasnie)
Введите текст, а я напечатаю его только согласными.
Штукенция
уеия
>>> 

String slices

This way of working with data is similar to indexing elements, but not one at a time, but in groups. You can create a slice-copy even of the entire original sequence. You can then refer to the slices in your program code.

Slices are created by specifying the index of the beginning and end of the sequence in square brackets in the same way as in indexing:

0              1 2 3 4 5
т е к с т
-5           -4 -3 -2 -1  

General view of the slice cut:

text[number1:number2]

It is important to remember that number1 must always be greater than number2 in order for the program to return the correct value.

You can shorten the notation of the slice by omitting the number 1, in which case the first element will be considered the beginning of the slice. The entry will be like this:

text[:number2]

You can also omit the end, in which case the end of the environment will default to the end of the sequence. The entry is similar to the previous one.

If you omit all the numbers, you get text[:] and this means a slice-copy of the entire sequence.

Program “Cut text”

Task: Write a program that will cut the text entered by the user into pieces as desired – the user sets the start and end values for the slice that he wants to see.

text=input('Write the text to be cut\n')
nachalo=int(input('Enter slice start index\n'))
konec=int(input('Enter the index of the end of the slice\n'))
print(text[nachalo:konec])
Write the text to be cut
Штукенция
Enter slice start index
1
Enter the index of the end of the slice
3
ту
>>> 

Tuples

A tuple in Python is the union of any data type into a group.

General form of a tuple: variable=()

Inside a tuple, you can write any elements separated by commas. You can enumerate the elements of a tuple both consecutively and from a new line.

tuple('кот',
      'медведь')

Tuples are more flexible constructs than arrays, because a tuple can store text, numbers, and multimedia at the same time.

Program “What’s in my bag”

Task: Write a program that displays the contents of a handbag organized as a tuple.

name=input('Hi, what is your name?\n')
print('Welcome', name,'You have in your bag several items:\n')
bag=('Food',
     'Hat',
     'Pillow')
for i in bag:
    print(i)
input('Press Entr to Exit')

The program turned out like this:

Hi, what is your name?
Kot
Welcome Kot You have in your bag several items:

Food
Hat
Pillow
Press Entr to Exit
>>> 

Function random.choice ()

To select a random element in a sequence, we first load import random and then use the random.choice(sequence variable) function.

Game “Anagram” (permutation of letters)

Task: create a program that will randomly select a word from a string, and then randomly rearrange the letters in the selected word and show the player. The user will have to guess what the word is. When the user guesses correctly, the program will congratulate him.

print('Now you will see a random anagram, you need to guess the word\n')
input('Нажмите Entr, чтобы начать')
slova=('медведь',
       'канистра',
       'грильяж',
       'табуретка',
       'программист')
import random
slovo_1=random.choice(slova)
anagramma=''
slovo_2=slovo_1
while slovo_2:
    dlina=len(slovo_2)
    bukva_index=random.randint(0,(dlina-1))
    bukva=slovo_2[bukva_index]
    anagramma+=bukva
    if bukva_index!=0:
        slovo_nachalo=slovo_2[:bukva_index]
    else:
        slovo_nachalo=''
    slovo_konec=slovo_2[(bukva_index+1):]
    slovo_2=slovo_nachalo+slovo_konec
print(anagramma)
otvet=input('Напишите слово и нажмите Entr, чтобы проверить вашу версию\n')
while otvet!=slovo_1:
    otvet=input('Напишите слово и нажмите Entr, чтобы проверить вашу версию')
print('Поздравляю, вы угадали!')
input('Нажмите Entr, чтобы выйти')

Phew! Wrote an anagram program. I wrote for two hours, there were a lot of plugs. I tried not to focus on the textbook, but to do as it seems to me. In the end, everything worked:

Сейчас вы увидите случайную анаграмму, вам нужно угадать слово

Нажмите Entr, чтобы начать
аутектраб
Напишите слово и нажмите Entr, чтобы проверить вашу версию
табуретка
Поздравляю, вы угадали!
Нажмите Entr, чтобы выйти

 


This entry was posted in Python (en). Bookmark the permalink.

Leave a Reply

🇬🇧 Attention! Comments with URLs/email are not allowed.
🇷🇺 Комментарии со ссылками/email удаляются автоматически.