Day 2 of Python Learning ๐Ÿ

Published: (May 26, 2026 at 03:02 PM EDT)
3 min read
Source: Dev.to

Source: Dev.to

Control Flow Statements

Control flow statements are used to control the execution flow of a program. They come in three categories:

  1. Condition Statements
  2. Looping Statements
  3. Jump Statements

In this post weโ€™ll focus on the first two: Conditional Statements and Looping Statements.

Conditional Statements

A conditional statement checks a condition and runs code based on the result.

Key words

  • if
  • else
  • elif ๐Ÿค”

In JavaScript youโ€™d write else if; in Python the combined form is elif (elseโ€ฏ+โ€ฏif).

# Find the largest of three numbers
a = 10
b = 20
c = 21

if a >= b and a >= c:
    print(a)
elif b >= a and b >= c:
    print(b)
elif c >= a and c >= b:
    print(c)   # Output: 21
  • Three variables are created and assigned values.
  • An ifโ€‘elif chain checks which value is greatest.
  • The program prints the largest number. ๐Ÿ“ˆ

Looping Statements

Looping statements repeat a block of code until a condition becomes false. The two main types are for loops and while loops. Here weโ€™ll concentrate on the while loop.

While Loop

A while loop runs as long as its condition evaluates to True.

Below are four simple tasks that illustrate how a while loop works.

Taskโ€ฏ1 โ€“ Countdown 5โ€ฏโ†’โ€ฏ1

count = 5
while count >= 1:
    print(count, end=" ")
    count -= 1
# Output: 5 4 3 2 1

Taskโ€ฏ2 โ€“ Even numbers from 10 down to 2

loop = 10
while loop >= 2:
    print(loop, end=" ")
    loop -= 2
# Output: 10 8 6 4 2

Taskโ€ฏ3 โ€“ Multiples of 3 from 15 down to 3

count1 = 15
while count1 >= 3:
    print(count1, end=" ")
    count1 -= 3
# Output: 15 12 9 6 3

Taskโ€ฏ4 โ€“ Multiples of 5 from 25 down to 5

count2 = 25
while count2 >= 5:
    print(count2, end=" ")
    count2 -= 5
# Output: 25 20 15 10 5

Understanding end=""

The end parameter of print() controls what is appended after each printed value. By default print() ends with a newline (\n). Setting end=" " prints everything on the same line, separated by a space.

# Default behavior (new lines)
for i in range(5, 0, -1):
    print(i)
# Output:
# 5
# 4
# 3
# 2
# 1

# Using end=" " (single line)
for i in range(5, 0, -1):
    print(i, end=" ")
# Output: 5 4 3 2 1

You can use any string with end, such as a star or underscore:

for i in range(5, 0, -1):
    print(i, end="*")
# Output: 5*4*3*2*1*

for i in range(5, 0, -1):
    print(i, end="_")
# Output: 5_4_3_2_1_

Iโ€™ll continue my Python journey tomorrowโ€ฆ ๐Ÿ‘‹

0 views
Back to Blog

Related posts

Read more ยป

First Post: A Little Biography

Introduction Hello, my name is Jay. Growing up, I wanted to follow in my dad's footsteps and become an engineerโ€”and I did, just not in the way I originally exp...