Basic Python Syntax 2: If and For

Basic Python Syntax 2

If-Else

Basic Format

if condition:
  # Actions to take if the condition is met
else:
  # Actions to take if the condition is not met

Example

moon = 666
if moon == 666:
    print("Correct")
else:
    print(f"Incorrect")

Output:

Correct

No additional elements are needed after elseAnother example:

m = 1
n = 2
if m > n:
    print(m)
else:
    print(n)

Output:

2

If-Elif

If-else is a binary choiceif-elif is a multiple choiceBasic Format

if condition1:
  # Actions to take if condition1 is met
elif condition2:
  # Actions to take if condition2 is met
elif condition3:
  # Actions to take if condition3 is met
# else can also be added
else:
  # Output when none of the above conditions are met

Example:

height = 180
if height >= 180:
    print("Author's height")
elif 140 < height:
    print("Average height")
elif 10 < height <= 140:
    print("Hmm...")
else:
    print("Liar")

Output:

Author's height

Nested If

Simply put, this means adding an if inside another if, commonly referred to as nesting.

# Example:

m = 6
n = 10

if m == 6:
    print(m)
    if n == 10:
        print(n)
else:
    print("m is not equal to 6")

Output:

6
10

While Loop

# Define initial variable
while condition:
  # Loop body
  # Change variable

Example: Sum of 1+2+3+4+…+99+100:

n = 100
a = 0
b = 0
while b <= n:
    a = a + b
    b += 1
print(a)

Output:

5050

Infinite Loop

Format:

while True:
  # Loop body

Example:

while True:
    print("Moon")

Output:

Moon
Moon
Moon
Moon
Moon
Moon
Moon
.....
.....
Moon
....

Or this:

a = 0
while a < 1:
    print(a)
    a -= 1

Output:

0
-1
-2
.....
...
....
....
-475603
-475604
-475605
-475606
-475607
-475608
-475609
....

The above is an infinite loop, which will continue indefinitely without manual intervention.

Nested While Loops

A while loop inside another while loopBasic Format:

while condition1:
  # Loop body 1
  while condition2:
    # Loop body 2
    # Change variable 2
  # Change variable 1

Indentation determines the level; strictly control indentation, preferably automatic indentationExample:

a = 0
while a <= 3:
    print(f"This is the {a + 1}th outer loop")
    i = 1
    while i < 5:
        print(f"This is the {i}th inner loop")
        i += 1
    a += 1

Output:

This is the 1th outer loop
This is the 1th inner loop
This is the 2th inner loop
This is the 3th inner loop
This is the 4th inner loop
This is the 2th outer loop
This is the 1th inner loop
This is the 2th inner loop
This is the 3th inner loop
This is the 4th inner loop
This is the 3th outer loop
This is the 1th inner loop
This is the 2th inner loop
This is the 3th inner loop
This is the 4th inner loop

“Learn Python from Scratch: From ‘Hello World’ to Breakpoint Debugging, Master the Syntax Basics in One Hour!”

Leave a Comment