Week 2, Day 2: Python Basics

CMPSC 100 Computational Expression

Janyl Jumadinova

Python Basics

Introduction to Python programming fundamentals

Program Structure

  • Python programs are made up of statements
  • Python uses indentation to define blocks
  • No need for semicolons or braces
  • Functions are defined with def

Variables

  • Variables store data values
  • You can change their values at any time
  • Variable names should be descriptive
  • Python is dynamically typed (no need to declare type)

Examples:

num = 5
name = "Alice"
score = num * 2

Variable Naming Rules

You can name variables almost anything, but:

Cannot start with numbers:

2cats = "Fluffy"  # Error!

Can contain letters, numbers, underscores:

cats_2 = "Fluffy"  # Good!
my_age = 20        # Good!
firstName = "Bob"  # Good (but prefer snake_case)

Cannot use Python keywords:

int = 5      # Error! 'int' is a built-in function
if = "test"  # Error! 'if' is a keyword

Variable Naming Best Practices

Balance descriptive and easy to type:

# Too short - unclear
c = "blue"
n = 42

# Too long - hard to type
the_color_of_the_sky_on_a_clear_day = "blue"
the_number_of_students_in_the_class = 42

# Just right - clear and concise
sky_color = "blue"
student_count = 42

Variable Types in Python

Python variables can hold different types of data:

  • int: Integer numbers
  • float: Decimal numbers
  • str: Text (string)
  • bool: True or False
  • list: Collection of items

Examples:

age = 20          # int
height = 1.75     # float
name = "Alice"    # str
is_student = True # bool
scores = [90, 85, 88] # list

Comments

  • Use comments to explain your code
  • Comments are ignored by Python
  • Single-line comment: starts with #
  • Multi-line comment: use triple quotes """ ... """

Examples:

# This is a single-line comment
num = 5  # Assign 5 to num
"""
This is a
multi-line comment
"""

What are Comments?

  • Comments are text in your code that Python ignores
  • They explain what your code does
  • Excellent for learning and debugging
  • Can temporarily disable code without deleting it

Single-line Comments

Use # to create single-line comments:

# This is a single-line comment
age = 25  # You can also add comments at the end of lines
# print("This line won't run")

Multi-line Comments

Use triple quotes for multi-line comments:

"""
This is a multi-line comment.
It can span multiple lines.
Very useful for longer explanations.
"""

'''
You can also use single quotes
for multi-line comments.
'''

What are Variables?

Think of variables as containers or labeled boxes that hold values:

  • Like a tea bag that can hold different types of tea
  • The container (variable) stays the same, but contents (value) can change
  • You use the same steeping process regardless of tea type
my_container = "green tea"    # Container holds green tea
my_container = "black tea"    # Same container, different tea
my_container = 42             # Same container, now holds a number!

Code Execution Order

How Python reads your code

Python Reads Top to Bottom

Python executes code line by line, from top to bottom:

n = 5          # Step 1: assigns variable n the value 5
print(n)       # Step 2: output: 5
n = 7          # Step 3: reassigns n a new value
print(n)       # Step 4: output: 7
n = n + 2      # Step 5: assigns n a value based on prior value
print(n)       # Step 6: output: 9

Complete output:

5
7
9

Variable Reassignment

  • Variables can be reassigned new values
  • The old value is replaced
  • You can use the current value to calculate the new value
score = 100
print(f"Starting score: {score}")  # Starting score: 100

score = score + 50  # Use current value to calculate new value
print(f"After bonus: {score}")     # After bonus: 150

score = 0  # Completely replace with new value
print(f"Reset score: {score}")     # Reset score: 0

The main Function Pattern

  • Use a main() function for your program’s main logic
  • Run main if the file is executed directly
  • This is a common Python convention

Example:

def main():
    print("This is the main function.")

if __name__ == "__main__":
    main()