Python Fundamentals: Variables, Data Structures, and Control Flow

Variables and Data Types

Variables

  • A variable name must start with a letter or undercsore, and can only contain letters, digits, and underscores. For instance, message_1 is valid, but 1_message is not.
  • Variable names cannot contain spaces; use underscores to seperate words. greeting_message works, while greeting message causes an error.
  • Avoid using Python keywords and built-in function names as variable names (e.g., print).
  • Choose descriptive yet concise names: name is better than n, student_name better than s_n, name_length better than length_of_persons_name.
  • Be careful with lowercase l and uppercase O as they can be mistaken for 1 and 0.

Practice

Simple message: assign a message to a variable and print it.

msg = "Hello Python"
print(msg)

Output:

Hello Python

Multiple messages: store a message, print it, change its value, and print again.

msg = "Hello"
print(msg)
msg = "World"
print(msg)

Output:

Hello
World

Strings

A string is a sequecne of characters enclosed in single or double quotes.

Changing Case

name = "ada lovelace"
print(name.title())

Concatenation

Use the + operator to join strings.

Whitespace

Use \t (tab) and \n (newline) to add whitespace.

Stripping Whitespace

  • rstrip() removes trailing whitespace.
  • lstrip() removes leading whitespace.
  • strip() removes both.

Practice

Personalized message:

name = "ada lovelace"
print("Hello " + name.title() + ", would you like to learn some Python today?")

Output:

Hello Ada Lovelace, would you like to learn some Python today?

Name cases:

name = "ada lovelace"
print(name.upper())
print(name.lower())
print(name.title())

Output:

ADA LOVELACE
ada lovelace
Ada Lovelace

Stripping names:

name = " alsa  \tLili    Blue     \n"
print(name)
print(name.lstrip())
print(name.rstrip())
print(name.strip())

Output:

 alsa  	Lili    Blue     

alsa  	Lili    Blue     

 alsa  	Lili    Blue
alsa  	Lili    Blue

Numbers

Integers support +, -, *, / operations. Numbers with a decimal point are called floats.

Practice

Favorite number:

num = 7
print("My favorite number is " + str(num))

Output:

My favorite number is 7

Lists

A list is an ordered collection of elements, denoted by square brackets [] with comma-separated values.

Modifying Elements

Access by index and assign a new value.

Adding Elements

  • append() adds to the end.
  • insert(index, value) inserts at a specific position.

Removing Elements

  • del list[index] removes by index.
  • pop() removes and returns the last item (or by index).
  • remove(value) removes the first occurrence of a value.

Practice

Names:

names = ['bababab', 'lili', 'oppop', 'whilesh', 'hahaha']
for item in names:
    print(item)

Output:

bababab
lili
oppop
whilesh
hahaha

Greetings:

names = ['bababab', 'lili', 'opop', 'jkjk']
for item in names:
    print(item + ", how are you?")

Output:

bababab, how are you?
lili, how are you?
opop, how are you?
jkjk, how are you?

Own list (transport):

vehicles = ["bike", "car", "motorcycle", "bus", "on foot"]
for item in vehicles:
    print("I would like to go to school by " + item)

Output:

I would like to go to school by bike
I would like to go to school by car
I would like to go to school by motorcycle
I would like to go to school by bus
I would like to go to school by on foot

Guest list:

people = ["mom", "teacher", "frind", "lili", "zip", "mmoy"]
for item in people:
    print(item + ", would you like to dine with me?")

Output:

mom, would you like to dine with me?
teacher, would you like to dine with me?
frind, would you like to dine with me?
lili, would you like to dine with me?
zip, would you like to dine with me?
mmoy, would you like to dine with me?

Changing guest list:

people = ["mom", "teacher", "frind", "lili", "zip", "mmoy"]
for item in people:
    print(item + ", would you like to dine with me?")
print("lili could not dine with me")
people.remove("lili")
people.append("lucy")
for item in people:
    print(item + ", would you like to dine with me?")

Output:

mom, would you like to dine with me?
teacher, would you like to dine with me?
frind, would you like to dine with me?
lili, would you like to dine with me?
zip, would you like to dine with me?
mmoy, would you like to dine with me?
lili could not dine with me
mom, would you like to dine with me?
teacher, would you like to dine with me?
frind, would you like to dine with me?
zip, would you like to dine with me?
mmoy, would you like to dine with me?
lucy, would you like to dine with me?

More guests:

people = ["lili", "popo", "wow", "gree", "moon", "ana"]
print("We have a bigger table!")
people.insert(0, "lucy")
people.append("xixi")
for item in people:
    print(item + ", would you like to dine with me?")

Output:

We have a bigger table!
lucy, would you like to dine with me?
lili, would you like to dine with me?
popo, would you like to dine with me?
wow, would you like to dine with me?
gree, would you like to dine with me?
moon, would you like to dine with me?
ana, would you like to dine with me?
xixi, would you like to dine with me?

Shrinking guest list:

print("I can only invite two people")
people = ["lili", "poop", "greeen"]
person_not = people.pop()
print("sorry, " + person_not + ", I cannot dine with you")
for i in people:
    print(i + ", you are still invited.")
del people[1]
del people[0]
print(people)

Output:

I can only invite two people
sorry, greeen, I cannot dine with you
lili, you are still invited.
poop, you are still invited.
[]

Sorting Lists

  • list.sort() permanently sorts the list alphabetically.
  • list.sort(reverse=True) sorts in reverse alphabetical order.
  • sorted(list) returns a new sorted list without modifying the original.
  • len(list) gets the number of elements.
  • list.reverse() reverses the order of elements.

Practice

Places to visit:

places = ["dalian", "datong", "beijin", "chengdu", "nanjin", "wulumuqi"]
print(places)
print(sorted(places))
print(places)
places.sort()
print(places)
places.sort(reverse=True)
print(places)

Output:

['dalian', 'datong', 'beijin', 'chengdu', 'nanjin', 'wulumuqi']
['beijin', 'chengdu', 'dalian', 'datong', 'nanjin', 'wulumuqi']
['dalian', 'datong', 'beijin', 'chengdu', 'nanjin', 'wulumuqi']
['beijin', 'chengdu', 'dalian', 'datong', 'nanjin', 'wulumuqi']
['wulumuqi', 'nanjin', 'datong', 'dalian', 'chengdu', 'beijin']

Dinner guests count:

people = ["lili", "opop", "ghgh", "anna"]
print("I invited " + str(len(people)) + " people")

Output:

I invited 4 people

Working with Numeric Lists

Use range() to generate sequences.

for num in range(1, 21):
    print(num)

Output: numbers 1 through 20.

nums = list(range(1, 1000001))
print(min(nums))
print(max(nums))
print(sum(nums))

Output:

1
1000000
500000500000

Odds:

nums = list(range(1, 21, 2))
for num in nums:
    print(num)

Output: 1, 3, 5, 7, 9, 11, 13, 15, 17, 19.

Multiples of 3:

nums = list(range(3, 31, 3))
for num in nums:
    print(num)

Output: 3, 6, 9, 12, 15, 18, 21, 24, 27, 30.

Cubes:

cubes = [num**3 for num in range(1, 11)]
print(cubes)

Output: [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

Slicing and Copying Lists

  • Slice: list[start:stop] returns a new list.
  • Copy: list[:] creates a full copy.

Practice

items = ["lili", "coco", "song", "vivi", "fgfg", "emm"]
print("The first three items in list are:")
print(items[:3])
print("Three items from the middle:")
print(items[1:4])
print("The last three items:")
print(items[-3:])

Output:

The first three items in list are:
['lili', 'coco', 'song']
Three items from the middle:
['coco', 'song', 'vivi']
The last three items:
['vivi', 'fgfg', 'emm']

Copying lists:

friend_pizzas = ["apple", "food", "fish", "joke", "orange"]
my_pizzas = friend_pizzas[:]
friend_pizzas.append("beef")
print("My favorite pizzas:")
for food in my_pizzas:
    print(food)
print("My friend's favorite pizzas:")
for food in friend_pizzas:
    print(food)

Output:

My favorite pizzas:
apple
food
fish
joke
orange
My friend's favorite pizzas:
apple
food
fish
joke
orange
beef

Tuples

Tuples are immutable lists, defined with parentheses ().

Practice

menu = ("pizza", "fish", "ice-cream", "hamburger", "apple")
# menu[0] = "orange"  # This would cause an error
menu = ("pizza", "fish", "ice-cream", "beef", "corn")
print("Updated menu:")
for food in menu:
    print(food)

Output:

Updated menu:
pizza
fish
ice-cream
beef
corn

If Statements

Conditional tests evaluate to True or False.

if-elif-else Chain

Only one block executes.

Avoiding else

Use explicit elif when the condition is known, to avoid unexpected behavior.

Practice

Conditional tests:

car = "subaru"
print("Is car == 'subaru'? I predict True.")
print(car == 'subaru')
print("\nIs car == 'audi'? I predict False.")
print(car == 'audi')

Output:

Is car == 'subaru'? I predict True.
True

Is car == 'audi'? I predict False.
False

Alien colors #1:

alien_color = "green"
if alien_color == "green":
    print("You earned 5 points")

Output: You earned 5 points

Second version (fails silently):

alien_color = "red"
if alien_color == "green":
    print("You earned 5 points")

No output.

Alien colors #2:

alien_color = "green"
if alien_color == "green":
    print("You killed the alien. 5 points")
else:
    print("You earned 10 points")

Output: You killed the alien. 5 points

alien_color = "red"
if alien_color == "green":
    print("message")
else:
    print("You earned 10 points")

Output: You earned 10 points

Alien colors #3:

if alien_color == "green":
    print("You earned 5 points")
elif alien_color == "yellow":
    print("You earned 10 points")
elif alien_color == "red":
    print("You earned 15 points")

Checking Lists with if

requested_toppings = []
if requested_toppings:
    for topping in requested_toppings:
        print("Adding " + topping + ".")
    print("\nPizza is ready!")
else:
    print("Are you sure you want a plain pizza?")

Output: Are you sure you want a plain pizza?

Practice

Greeting admin:

users = ["admin", "admax", "ada", "aba", "bbc", "mmm"]
for user in users:
    if user == "admin":
        print("Hello admin, would you like a status report?")
    else:
        print("Hello " + user + ", thank you for logging in again")

Output:

Hello admin, would you like a status report?
Hello admax, thank you for logging in again
Hello ada, thank you for logging in again
Hello aba, thank you for logging in again
Hello bbc, thank you for logging in again
Hello mmm, thank you for logging in again

Empty list:

users = []
if users:
    for user in users:
        if user == "admin":
            print("Hello admin, status report?")
        else:
            print("Hello " + user + ", thanks")
else:
    print("We need to find some users!")

Output: We need to find some users!

Dictionaries

A dictionary stores key-value pairs, enclosed in {}.

Adding/Modifying/Removing

man = {'first_name': 'Green', 'last_name': 'lili', 'age': 18, 'city': 'chongqing'}
print(man['first_name'])
print(man['last_name'])
print(man['age'])
print(man['city'])

Output:

Green
lili
18
chongqing

Glossary:

lang = {"python": "len", "java": "str", "C": "printf", "go": "for"}
print("python: " + lang["python"])
print("java: " + lang["java"])
print("C: " + lang["C"])
print("go: " + lang["go"])

Output:

python: len
java: str
C: printf
go: for

Iterating through Dictionaries

  • keys() returns all keys.
  • values() returns all values.
  • set() can be used to eliminate duplicates.

Practice

Glossary 2:

lang = {"python": "len", "java": "str", "C": "printf", "go": "for"}
lang.update({"temo": "help"})
for key, value in lang.items():
    print(key)
    print(value)

Output:

python
len
java
str
C
printf
go
for
temo
help

User Input and While Loops

input()

Pauses the program and waits for user input.

Practice

Car rental: ask the user what car they want.

Flag

A boolean variable that controls the loop.

break and continue

  • break exits the loop entirely.
  • continue skips the rest of the iteration and returns to the top.

Removing All Instances from a List

pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
    pets.remove('cat')
print(pets)

Output:

['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
['dog', 'dog', 'goldfish', 'rabbit']

Filling a Dictionary with User Input

Functions

Define with def keyword.

Parameters and Arguments

Positional Arguments

Order matters.

Keyword Arguments

def describe_pet(animal_type, pet_name):
    print("\nI have a " + animal_type + ".")
    print("My " + animal_type + "'s name is " + pet_name.title() + ".")

Call with keyword arguments: describe_pet(animal_type='hamster', pet_name='harry')

Return Values

Use return statement.

Modifying a List in a Function

Changes are permanent.

Modules

Store functions in a .py file and import them.

import module_name
from module_name import function_name
from module_name import function_0, function_1
import module_name as mn
from module_name import *

Classes

Defining a Class

class MyClass:
    # class body

Creating an Instance

obj = MyClass()

Constructor __init__

class MyClass:
    def __init__(self, attribute):
        self.attribute = attribute

Methods

Methods are functions defined inside a class.

Inheritance

class ChildClass(ParentClass):
    pass

Polymorphism

Different classes can define methods with the same name.

Special Methods

__init__, __str__, __repr__, etc.

Access Control

By convention, a single underscore _ means protected, double underscore __ means private.

Files

Reading a File

with open('pi_digits.txt') as file_object:
    contents = file_object.read()
    print(contents)

Reading Line by Line

with open('filename.txt') as file_object:
    for line in file_object:
        print(line.rstrip())

Storing Lines in a List

with open('filename.txt') as file_object:
    lines = file_object.readlines()

for line in lines:
    print(line.rstrip())

Writing to a File

with open('filename.txt', 'w') as file_object:
    file_object.write("Hello world!")

Modes: 'r' (read), 'w' (write, overwrites), 'a' (append), 'r+' (read/write).

Writing Multiple Lines

Include \n to start a new line.

Appending to a File

with open('filename.txt', 'a') as file_object:
    file_object.write("New content\n")

Tags: python Variables Data Types Lists Tuples

Posted on Thu, 07 May 2026 04:12:03 +0000 by voltrader