Python Fundamentals: Variables, Control Flow, and Data Types

Python Keywords Python has a set of reserved words that cannot be used as variable names or identifiers. These keywords define the language's syntax and structure.

import keyword
print(keyword.kwlist)

Output: ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

Variable Assignment and Memory Management

Scenario 1: Reassigning Variables When you assign a new value to a variable, Python creates a new memory location for the new value and updates the variable reference.

identifier = "first_value"
identifier = "second_value"

In this case, Python first creates memory for "first_value" and makes "identifier" point to it. Then it creates memory for "second_value" and updates "identifier" to point to the new location. The original "first_value" becomes unreferenced and is eventually garbage collected.

Scenario 2: Variable References When you assign one variable to another, Python creates a reference to the same memory location.

primary = "shared_value"
secondary = primary

Both variables now point to the same memory location containing "shared_value".

Practice Exercises

# Exercise 1
nickname = "one-eighty"
username = nickname
username = "little_brother"

print(nickname)  # Output: "one-eighty"
print(username)  # Output: "little_brother"

# Exercise 2
nickname = "one-eighty"
username = nickname
nickname = "little_brother"

print(nickname)  # Output: "little_brother"
print(username)  # Output: "one-eighty"

# Exercise 3
nickname = "one-eighty"
username = nickname
nickname = "little_brother"

text = username + nickname
print(text)      # Output: "one-eightylittle_brother"
print(username)  # Output: "one-eighty"

# Exercise 4
string_number = "20"
numeric_value = int(string_number)

data = string_number * 3
print(data)      # Output: "202020"

value = numeric_value * 3
print(value)     # Output: 60

Comments Comments are ignored by the Python interpreter and are used to explain code or make notes.

Single-line Comments Use the # symbol for single-line comments.

# This is a single-line comment
# You can also comment out code:
# print("This won't run")

Keyboard shortcuts:

Windows: Ctrl + / Mac: Command + /

Multi-line Comments Use triple quotes for multi-line comments.

"""
This is a multi-line comment
that spans multiple lines
"""

User Input The input() function reads user input as a string.

name = input("Enter your name: ")
age = int(input("Enter your age: "))
email = input("Enter your email: ")

result = name + str(age) + email
print(result)

Conditional Statements

If Statements Use if statements to execute code based on conditions.

if condition:
    # Code to execute if condition is True
else:
    # Code to execute if condition is False

Multiple Conditions Use elif for additional conditions.

if condition_a:
    # Execute if condition_a is True
elif condition_b:
    # Execute if condition_a is False but condition_b is True
elif condition_c:
    # Execute if both previous conditions are False but condition_c is True
else:
    # Execute if all conditions are False

Nested If Statements If statements can be nested inside other if statements.

if outer_condition:
    if inner_condition:
        # Code to execute
    else:
        # Alternative code
elif another_condition:
    # Code for another_condition

Customer Service Simulation

print("Welcome to 10010. Please select a service: 1. Account Balance, 2. Broadband, 3. Business Services, 4. Customer Support")
choice = input("Enter your choice: ")

if choice == "1":
    print("Account Balance Services")
    print("1. Check Balance, 2. Pay Bill, 3. Report Issue")
    sub_choice = input("Enter your choice: ")
    
    if sub_choice == "1":
        print("Balance inquiry")
        # Code to display balance
    elif sub_choice == "2":
        print("Payment successful")
        # Code to process payment
    elif sub_choice == "3":
        print("Issue reported")
        # Code to handle issue
    else:
        print("Invalid input")
elif choice == "2":
    print("Broadband Services")
elif choice == "3":
    print("Business Services")
elif choice == "4":
    print("Customer Support")
else:
    print("Invalid input")

While Loops While loops execute code as long as a condition remains True.

while condition:
    # Code to execute repeatedly

While Loop Examples

# Example 1: Infinite loop with break
print("Start")
while True:
    print("This is a loop")
    break  # Exit the loop
print("End")

# Example 2: Counting down
counter = 3
while counter > 2:
    print("123")
    counter -= 1
print("End")

# Example 3: Guessing game
secret_number = 66
attempts = 1
max_attempts = 3

while attempts <= max_attempts:
    guess = int(input("Guess a number between 0-100: "))
    
    if guess == secret_number:
        print("Correct!")
        break
    elif guess > secret_number:
        print("Too high")
    else:
        print("Too low")
    
    attempts += 1

Break and Continue The break statement exits a loop, while continue skips to the next iteration.

# Example: Skip number 7
count = 1
while count <= 10:
    if count == 7:
        count += 1
        continue  # Skip this iteration
    print(count)
    count += 1

String Formatting

.format() Method Format strings by position or keyword arguments.

text = "My name is {0}, I'm {1} years old, and my phone is {2}".format("Zhang San", 18, "12345678")
print(text)

% Formatting Similar to C-style string formatting.

text = "My name is %s, I'm %d years old, and my phone is %d" % ("Zhang San", 18, "12345678")
print(text)

f-strings (Python 3.6+) Formatted string literals provide an easy way to embed expressions inside string literals.

name = "Zhang San"
age = 18
text = f"My name is {name}, I'm {age} years old"
print(text)

Operators

Arithmetic Operators

# +, -, *, /, %, **
result = 9 % 2  # Modulo (remainder)
print(result)  # Output: 1

Comparison Operators

# >, <, >=, <=, ==, !=
a = 5
b = 10
print(a > b)   # False
print(a == b)  # False

Assignment Operators

count = 1
count += 1  # Equivalent to count = count + 1
count -= 1  # Equivalent to count = count - 1

Membership Operators

text = "Japanese people are not bad"
print("Japan" in text)      # True
print("Russia" in text)     # False

Logical Operators

# and, or
print(True and True)   # True
print(False and True)  # False
print(True or False)   # True

Number Systems

Converting Between Number Systems

decimal = 235

# Convert to binary, octal, hexadecimal
binary = bin(decimal)    # '0b11101011'
octal = oct(decimal)     # '0o353'
hexadecimal = hex(decimal)  # '0xeb'

print(binary, octal, hexadecimal)

Converting to Decimal

binary_to_decimal = int("0b11101011", 2)
octal_to_decimal = int("0o353", 8)
hex_to_decimal = int("0xeb", 16)

print(binary_to_decimal, octal_to_decimal, hex_to_decimal)

Computer Units

Bit (b): The smallest unit, represents 0 or 1 Byte (B): 8 bits Kilobyte (KB): 1024 bytes Megabyte (MB): 1024 KB Gigabyte (GB): 1024 MB Terabyte (TB): 1024 GB

Character Encoding

ASCII ASCII uses 1 byte (8 bits) to represent characters, allowing 256 possible characters.

GBK and GB-2312 Chinese character encodings that extend ASCII to support Chinese characters.

Unicode Universal character encoding that supports all languages.

UCS-2: 2 bytes per character (65,536 possible characters) UCS-4: 4 bytes per character (over 4 billion possible characters)

UTF-8 Variable-length encoding that optimizes Unicode for different character ranges.

name = "张三"  # Unicode string (each character uses 4 bytes in Python)
data = name.encode("utf-8")  # Convert to UTF-8 bytes
print(data)  # Output: b'\xe5\xbc\xa0\xe4\xb8\x89'

Tags: python programming Variables control-flow data-types

Posted on Fri, 03 Jul 2026 17:32:03 +0000 by Heavy