Day 2 of Python Learning ๐
Source: Dev.to
Control Flow Statements
Control flow statements are used to control the execution flow of a program. They come in three categories:
- Condition Statements
- Looping Statements
- 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
ifelseelif๐ค
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โelifchain 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โฆ ๐