Python Tutorial: Loops, Operators, Data Structures, and More

Python Programming Basics

Control Flow: Pass, Continue, and Break

Let’s understand the pass, continue, and break statements in Python:

(i) Pass:

The pass statement is a placeholder. It does nothing but is useful when a statement is syntactically required, but you don’t want any action to be taken.

Example:

if condition:
    pass  # Do nothing for now

(ii) Continue:

The continue statement is used inside loops. It skips the rest of the current iteration and moves to the next one.

Example:

for i in range(5):
    if i == 3:
        continue  # Skip iteration when i is 3
    print(i)

(iii) Break:

The break statement is used to exit a loop prematurely. It’s often used when a certain condition is met, and there’s no need to continue looping.

Example:

for i in range(5):
    if i == 3:
        break  # Exit the loop when i is 3
    print(i)

Loops: While and For

While Loop:

A while loop repeatedly executes a block of code as long as a condition is True.

Example:

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

For Loop:

A for loop iterates over a sequence (like a list, string, or range) and executes a block of code for each element.

Example:

for i in range(5):
    print(i)

Key Differences:

FeatureWhile LoopFor Loop
ConditionRuns as long as a condition is true.Iterates over a sequence.
Use CaseWhen the number of iterations is unknown.When the number of iterations is known or for iterating over collections.

Operators in Python

Python has 7 categories of operators:

  1. Arithmetic Operators: +, -, *, /, %, **, // (Perform mathematical operations)
  2. Comparison Operators: ==, !=, >, <, >=, <= (Compare values)
  3. Assignment Operators: =, +=, -=, *=, etc. (Assign values to variables)
  4. Logical Operators: and, or, not (Combine or negate conditions)
  5. Bitwise Operators: &, |, ^, ~, <<, >> (Operate on bits)
  6. Membership Operators: in, not in (Check for membership in a sequence)
  7. Identity Operators: is, is not (Check if objects are the same)

(Examples for each operator category are provided in the original HTML, which can be included here if needed)

Python Execution Modes

Interactive Mode:

  • Code is executed line by line.
  • Great for quick testing and experimentation.

Script Mode:

  • Code is written in a file and executed as a whole.
  • Used for writing complete programs.

More Python Concepts

1. Membership Operators:

Check if a value is present in a sequence (e.g., list, string).

Example:

my_list = [1, 2, 3]
print(2 in my_list)  # True

2. Identity Operators:

Check if two variables refer to the same object in memory.

Example:

a = [1, 2]
b = a
print(a is b)  # True

3. Escape Sequences:

Represent special characters in strings (e.g., newline, tab).

Example:

print("Hello\nWorld")  # Prints on two lines

4. Slicing:

Extract a portion of a sequence (e.g., list, string).

Example:

my_string = "Python"
print(my_string[1:4])  # yth

String Functions: lstrip(), swapcase(), isspace()

1. lstrip():

Removes leading whitespace from a string.

Example:

text = "   Hello"
print(text.lstrip())  # "Hello"

2. swapcase():

Swaps the case of letters in a string.

Example:

text = "Hello"
print(text.swapcase())  # "hELLO"

3. isspace():

Checks if a string contains only whitespace.

Example:

text = "  "
print(text.isspace())  # True

Dictionaries in Python

A dictionary stores data in key-value pairs.

Creating Dictionaries:

  1. Using curly braces: my_dict = {"name": "Alice", "age": 30}
  2. Using dict(): my_dict = dict(name="Alice", age=30)

List Methods: reverse(), insert(), remove(), pop()

1. reverse():

Reverses the list in place.

Example:

my_list = [1, 2, 3]
my_list.reverse()
print(my_list)  # [3, 2, 1]

2. insert():

Inserts an element at a specific index.

Example:

my_list = [1, 2, 3]
my_list.insert(1, 4)
print(my_list)  # [1, 4, 2, 3]

3. remove():

Removes the first occurrence of an element.

Example:

my_list = [1, 2, 3, 2]
my_list.remove(2)
print(my_list)  # [1, 3, 2]

4. pop():

Removes and returns the element at a specific index (or the last element if no index is specified).

Example:

my_list = [1, 2, 3]
removed_element = my_list.pop(1)
print(my_list)  # [1, 3]
print(removed_element)  # 2

Mutable vs. Immutable Objects

Mutable:

  • Can be changed after creation (e.g., lists, dictionaries).

Immutable:

  • Cannot be changed after creation (e.g., strings, tuples).

Tuples in Python

Tuples are ordered, immutable collections.

Defining and Accessing Tuples:

Example:

my_tuple = (1, 2, "apple")
print(my_tuple[0])  # 1

Dictionary Methods: keys(), values(), items(), clear(), copy(), update(), get()

1. keys():

Returns a view of the dictionary’s keys.

2. values():

Returns a view of the dictionary’s values.

3. items():

Returns a view of the dictionary’s key-value pairs.

4. clear():

Removes all items from the dictionary.

5. copy():

Creates a shallow copy of the dictionary.

6. update():

Updates the dictionary with key-value pairs from another dictionary or iterable.

7. get():

Returns the value for a key (or a default value if the key is not found).

(Examples for each dictionary method can be included from the original HTML if needed)

List Slicing

Example:

alphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']

# First 3 letters
print(alphabet[:3])  # ['A', 'B', 'C']

# Middle 3 letters
print(alphabet[3:6]) # ['D', 'E', 'F']

# From index 5 to the end
print(alphabet[5:])  # ['F', 'G', 'H', 'I', 'J']

Removing Duplicates from a List

Example:

numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = list(set(numbers))
print(unique_numbers)  # [1, 2, 3, 4, 5]

Printing Odd/Even Numbers from a List

Example:

numbers = [1, 2, 3, 4, 5, 6]

even_numbers = []
odd_numbers = []

for num in numbers:
    if num % 2 == 0:
        even_numbers.append(num)
    else:
        odd_numbers.append(num)

print("Even numbers:", even_numbers)  # [2, 4, 6]
print("Odd numbers:", odd_numbers)  # [1, 3, 5]