Python: if, elif, else branching, while loops, random number generation

We continue to learn programming. Let’s move on to the study of the third chapter of the book: Michael Dawson “Programming in Python”, 2014 (Michael Dawson “Python Programming for the Absolute Beginner”, 3rd Edition), where we will study if, elif, else conditional statements and while loops and learn how to generate random numbers using a module with the functions random.randint() and random.randrage().

Summary of chapter 3 with examples of programs I wrote:

Random Number Generation in Python

We load the import random module – it generates random numbers based on the built-in formula. To assign a random value to a variable, after calling the module, call one of its functions, for example,

import random
# Случайные значения в диапазоне от 1 до 10 включительно:
peremennaya = random.randint(1,10) 
# Случайные значения в диапазоне от 0 до 9 включительно:
peremennaya = random.randrange(10)

Conditional constructs if, elif, else

First, let’s study the comparison operators, because conditional constructions are possible if one variable is compared with some value. Operators:

== equals
!= not equal
> more
>= greater than or equal
< less
<= less than or equal to

A general view of a conditional construct in Python:

There is always one if at the beginning and one else at the end, and elif can be repeated any number of times between them.

Option 1:

if "значение 1" оператор сравнения "значение 2":
    сделай то-то
elif "значение 3" оператор сравнения "значение 4":
    сделай что-то еще
   сделай что-то другое

Option 2 (values as conditions: true/false):

This construct assumes that the value in the if “value”: condition is true, that is, the condition will be executed only if the value is True. To reverse the construction, the negation of not after the if before “value” (значение) is used.

What is true and false in Python? You can check for true / false any number or line of text. All numbers except “0” are true, and zero is false. All strings except the empty string are true, and the empty string is false.

if "значение 1":
    сделай то-то
    сделай что-то еще
    сделай что-то другое

Examples of using conditionals:

Password Login Program: Write a program that asks the user to enter a password. If the password matches the given value, then the program welcomes the participant. If the password does not match the specified value, the program displays a message stating that the password is not correct.

passw=input('Привет, введите пароль.\n')
if passw=='kot':
    print('Wow, hi Kot!')
    print('So sorry, it\'s not right')

VIP Club Program: Write a program that asks the user to enter a password. The system has two VIP guests who have passwords. If the user enters one of the two given passwords, then the program welcomes the guest who entered. If the password does not match either of the two given values, the program will write a message stating that the password is not correct.

passw=input('Привет, введите пароль.\n')
if passw=='kot':
    print('Wow, hi Kot!')
elif passw=='medved':
    print('Hi, Bear! Love you!')
    print('So sorry, it\'s not right')

while loop, control variable, break, continue

To create cycles, we need logical operators:


The loop will be executed if the condition is true. Conditions can be either single or compound.

General view of the cycle:

control variable = ” “
while control variable comparison operator “value (значение)”:
  do something
do something else after the loop ends if its condition is false

Loop example while:

Baby Simulator Program: Create a program that asks the question “Why?” and gives the user the opportunity to respond. After each answer, the program repeats the question “Why?” and again gives the opportunity to enter the answer. And so on until repeated until the user enters the answer “shake”; in this case the program writes “Okidoki”.

print('Child simulator')
while answer!='покачану':

Endless loop in Pythonwhile True:, continue, break

If the loop turned out to be infinite by chance, then this is a logical error. But you can also make an intentionally infinite loop, for example, while True:

To end such a cycle, you need to write break – interrupt the cycle.

To go from some place in the code to the beginning of the loop, we write continue.

The task of using conditional structures and a loop:

Write a game “Epic battle with the undead”. The program asks for a username. The hero is then told that “Only you can defeat the uneds and save the village.” The question is asked: “Full readiness for battle?”. The user can answer. If the user answers “yes”, then the game starts, if the answer is different, then the program ends by asking the user to press Enter to exit. The game is as follows: a hero with 13 lives is attacked one by one by undereds, who hit for 2 points per turn. At the same time, the hero takes 2 life points. The battle continues until the hero has lost almost all his lives, but remains alive. At the end of the battle, you need to display the number of defeated undead and the number of remaining lives.

print('Игра "Эпичная битва с андедами":')
name=input('Как тебя зовут?\n')
print('Воин ',name,'!\nТолько ты сможешь победить андедов и спасти деревню.\n', sep='')
ready=input('Полная готовность к бою? (да/нет)\n')
if ready=='да':
    while health > 2:
        print('Воин',name,'доблестно сразился с андедом и победил!\n \
Из-за повреждений очки жизни уменьшились с 13 до',health)
    print('Поздравляю! Всех нападавшие андеды побеждены, их было:', undead,'\n \
У тебя осталось', health,'очков жизни.')
input('Нажми Entr, чтобы выйти из игры')

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

Leave a Reply

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