DEV Community

yuna song
yuna song

Posted on

Python Basics: Variables, Conditionals, and Loops

1. Variables

A variable stores a value that can be referenced and reused throughout a program.

Syntax

name = "Python"
age = 20
pi = 3.14
is_active = True
Enter fullscreen mode Exit fullscreen mode

Naming Rules

  • Use letters, numbers, and underscores (_).
  • Variable names cannot start with a number.
  • Do not use spaces (use snake_case instead).
  • Do not use Python keywords (e.g. if, for, while, class).

Common Data Types

age = 20              # int
pi = 3.14             # float
name = "Python"       # str
is_active = True      # bool
Enter fullscreen mode Exit fullscreen mode

Notes

  • Variables can be reassigned at any time.
  • Python automatically determines the data type.

2. Conditional Statements

Conditional statements execute different code depending on whether a condition is True or False.

Syntax

score = 85

if score >= 90:
    print("Grade A")
elif score >= 80:
    print("Grade B")
else:
    print("Grade C")
Enter fullscreen mode Exit fullscreen mode

Keywords

  • if : Checks the first condition.
  • elif : Checks additional conditions if previous ones are False.
  • else : Executes when none of the above conditions are met.

Comparison Operators

>    <    >=    <=    ==    !=
Enter fullscreen mode Exit fullscreen mode

Logical Operators

and    or    not
Enter fullscreen mode Exit fullscreen mode

Notes

  • A colon (:) is required after each condition.
  • Proper indentation defines the code block.

3. Loops

Loops execute a block of code repeatedly.

for Loop

Used when iterating over a sequence or a fixed range.

for i in range(5):
    print(i)
Enter fullscreen mode Exit fullscreen mode

Output:

0
1
2
3
4
Enter fullscreen mode Exit fullscreen mode

while Loop

Repeats as long as a condition remains True.

count = 0

while count < 3:
    print(count)
    count += 1
Enter fullscreen mode Exit fullscreen mode

Output:

0
1
2
Enter fullscreen mode Exit fullscreen mode

Loop Control

break      # Exit the loop immediately
continue   # Skip the current iteration
pass       # Placeholder; does nothing
Enter fullscreen mode Exit fullscreen mode

Notes

  • Use for when the number of iterations is known.
  • Use while when repetition depends on a condition.
  • Ensure a while loop eventually becomes False to avoid an infinite loop.

Top comments (0)