Conditional Statements (if, elif, else)

Conditional statements allow your code to execute different actions based on certain conditions.

  • if: Checks a condition and executes a block of code if it evaluates to True.
  if condition:
    # code to execute
  
  • elif: Short for “else if,” checks another condition if the previous if condition was False.
  elif another_condition:
    # code to execute
  
  • else: Executes a block of code if none of the preceding conditions were True.
  else:
    # code to execute
  

Example:

  age = 20
if age < 13:
    print("Child")
elif 13 <= age < 20:
    print("Teenager")
else:
    print("Adult")
  

Loops (for, while)

Loops allow you to execute a block of code repeatedly.

  • for Loop: Iterates over a sequence (e.g., a list, tuple, string).
  for item in sequence:
    # code to execute
  

Example:

  for i in range(5):
    print(i)
  
  • while Loop: Repeats as long as a condition is True.
  while condition:
    # code to execute
  

Example:

  count = 0
while count < 5:
    print(count)
    count += 1
  

Comprehensions (list, dictionary, and set comprehensions)

Comprehensions provide a concise way to create lists, dictionaries, and sets.

  • List Comprehensions: Create a new list by applying an expression to each item in an existing iterable.
  [expression for item in iterable]
  

Example:

  squares = [x**2 for x in range(10)]
  
  • Dictionary Comprehensions: Create a new dictionary by applying an expression to each item in an existing iterable.
  {key_expression: value_expression for item in iterable}
  

Example:

  square_dict = {x: x**2 for x in range(10)}
  
  • Set Comprehensions: Create a new set by applying an expression to each item in an existing iterable.
  {expression for item in iterable}
  

Example:

  square_set = {x**2 for x in range(10)}
  

Let me know if you need further explanations or examples on any of these topics!