Week 3-1: Variables, Data Types, and Operations

CMPSC 100 Computational Expression

Janyl Jumadinova

Variables and Data Types Review

Building upon Python fundamentals

Variables Recap

  • Variables store data values
  • Python is dynamically typed (no need to declare types)
  • Variable names are case-sensitive
  • Use descriptive names (covered in Week 2)

Examples:

student_name = "Alice"
test_score = 95
is_passing = True

Data Types Review

Python’s built-in data types:

  • int: Whole numbers (e.g., 42, -17)
  • float: Decimal numbers (e.g., 3.14, -2.5)
  • str: Text/strings (e.g., “Hello”, ‘Python’)
  • bool: True or False
  • list: Ordered collection (e.g., [1, 2, 3])
  • dict: Key-value pairs (e.g., {“name”: “Alice”})

Checking Variable Types

Use the type() function to check a variable’s type:

age = 25
height = 5.8
name = "Bob"

print(type(age))     # <class 'int'>
print(type(height))  # <class 'float'>
print(type(name))    # <class 'str'>

Arithmetic Operations

Working with numbers in Python

Basic Arithmetic Operators

Python supports standard mathematical operations:

  • + Addition
  • - Subtraction
  • * Multiplication
  • / Division (returns float)
  • // Floor division (returns int)
  • % Modulus (remainder)
  • ** Exponentiation (power)

Arithmetic Examples

a = 10
b = 3

print(a + b)    # 13
print(a - b)    # 7
print(a * b)    # 30
print(a / b)    # 3.333...
print(a // b)   # 3 (floor division)
print(a % b)    # 1 (remainder)
print(a ** b)   # 1000 (10 to the power of 3)

Order of Operations

Python follows standard mathematical precedence (PEMDAS):

  1. Parentheses ()
  2. Exponents **
  3. Multiplication * and Division /, //
  4. Addition + and Subtraction -
result = 2 + 3 * 4      # 14 (not 20)
result = (2 + 3) * 4    # 20
result = 2 ** 3 * 4     # 32 (8 * 4)

Rounding Numbers

Use the round() function to round decimal numbers:

# Basic rounding
temperature = 22.666666
print(round(temperature))      # 23 (no decimal places)
print(round(temperature, 1))   # 22.7 (1 decimal place)
print(round(temperature, 2))   # 22.67 (2 decimal places)

# Useful for displaying sensor data
percentage = 66.66666
print("Battery: " + str(round(percentage, 1)) + "%")  # Battery: 66.7%

Variable Assignment Operations

Efficient ways to update variables

Assignment Operators

Shorthand for common operations:

  • += Add and assign
  • -= Subtract and assign
  • *= Multiply and assign
  • /= Divide and assign
  • //= Floor divide and assign
  • %= Modulus and assign
  • **= Exponent and assign

Assignment Examples

score = 100

score += 10    # Same as: score = score + 10
print(score)   # 110

score -= 5     # Same as: score = score - 5
print(score)   # 105

score *= 2     # Same as: score = score * 2
print(score)   # 210

score //= 3    # Same as: score = score // 3
print(score)   # 70

String Assignment Operations

message = "Hello"
message += " World"    # Same as: message = message + " World"
print(message)         # "Hello World"

repeat = "Python "
repeat *= 3           # Same as: repeat = repeat * 3
print(repeat)         # "Python Python Python "

String Operations

Working with text data

String Concatenation

Use + to join strings together:

first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name)  # "John Doe"

greeting = "Hello, " + full_name + "!"
print(greeting)   # "Hello, John Doe!"

String Repetition

Use * to repeat strings:

laugh = "ha"
loud_laugh = laugh * 3
print(loud_laugh)  # "hahaha"

border = "-" * 20
print(border)      # "--------------------"

String Slicing

Extract parts of strings using square brackets:

text = "Python"
print(text[0])     # "P" (first character)
print(text[0:3])   # "Pyt" (characters 0, 1, 2)
print(text[2:])    # "thon" (from index 2 to end)
print(text[:4])    # "Pyth" (from start to index 3)
print(text[-1])    # "n" (last character)

String Methods

Common string methods for text processing:

text = "Hello World"
name = "alice"

# Convert to uppercase
print(text.upper())    # "HELLO WORLD"
print(name.upper())    # "ALICE"

# Convert to lowercase
print(text.lower())    # "hello world"

# Other useful methods
print(text.replace("World", "Python"))  # "Hello Python"
print(len(text))       # 11 (length of string)

Input and Output Operations

Interacting with users

Getting User Input

Use input() to get text from the user:

name = input("What's your name? ")
print("Hello, " + name + "!")

# input() always returns a string
age_str = input("How old are you? ")
age = int(age_str)  # Convert to integer
print("Next year you'll be", age + 1)

Formatting Output

Different ways to format output:

name = "Alice"
age = 25
score = 95.67

# String concatenation
print("Name: " + name + ", Age: " + str(age))

# f-strings (formatted string literals)
print(f"Name: {name}, Age: {age}")
print(f"Score: {score:.1f}")  # One decimal place

Type Conversion (Casting)

Converting between data types

What is Type Conversion?

Type conversion (casting) changes a value from one data type to another:

  • Implicit conversion: Python does it automatically
  • Explicit conversion: You do it manually using functions

Explicit Type Conversion

Common conversion functions:

  • int() - Convert to integer
  • float() - Convert to floating-point number
  • str() - Convert to string
  • bool() - Convert to boolean

Converting to Integer

# From string
age_str = "25"
age_int = int(age_str)
print(age_int)  # 25
print(type(age_int))  # <class 'int'>

# From float (truncates decimal)
height_float = 5.8
height_int = int(height_float)
print(height_int)  # 5

# From boolean
bool_val = True
int_val = int(bool_val)
print(int_val)  # 1

Converting to Float

# From string
price_str = "29.99"
price_float = float(price_str)
print(price_float)  # 29.99

# From integer
count = 42
count_float = float(count)
print(count_float)  # 42.0

# From boolean
is_true = True
float_val = float(is_true)
print(float_val)  # 1.0

Converting to String

# From integer
age = 25
age_str = str(age)
print(age_str)  # "25"
print(type(age_str))  # <class 'str'>

# From float
pi = 3.14159
pi_str = str(pi)
print(pi_str)  # "3.14159"

# From boolean
is_ready = False
ready_str = str(is_ready)
print(ready_str)  # "False"

Converting to Boolean

# From numbers (0 is False, everything else is True)
print(bool(0))     # False
print(bool(1))     # True
print(bool(-5))    # True
print(bool(0.0))   # False
print(bool(3.14))  # True

# From strings (empty string is False)
print(bool(""))      # False
print(bool("Hello")) # True
print(bool("0"))     # True (string "0", not number 0)

Implicit Type Conversion

Python automatically converts types in some situations:

# Integer + Float = Float
result = 5 + 3.2
print(result)       # 8.2
print(type(result)) # <class 'float'>

# Boolean in arithmetic (True=1, False=0)
total = 10 + True + False
print(total)  # 11

Common Conversion Errors

Be careful with invalid conversions:

# These will cause errors:
# int("hello")     # ValueError
# float("abc")     # ValueError
# int("3.14")      # ValueError (use float() first)

# Safe conversion:
number_str = "3.14"
number_float = float(number_str)
number_int = int(number_float)  # 3

Cross-type Operations

Understanding how operators work with different data types

The Same Operator, Different Behaviors

The same operator can behave differently with different data types:

# * with two integers
result = 3 * 4        # 12 (multiplication)

# * with integer and float  
result = 3 * 4.0      # 12.0 (multiplication, result is float)

# * with integer and string
result = "Hey" * 3    # "HeyHeyHey" (string repetition)

# + with numbers vs strings
result = 3 + 4        # 7 (arithmetic addition)
result = "3" + "4"    # "34" (string concatenation)

Why Understanding Types Matters

Type awareness helps you predict behavior:

# These work as expected
print(5 + 3)         # 8 (arithmetic)
print("Hello" + " World")  # "Hello World" (concatenation)

# These cause errors - mixed types!
# print("5" + 3)     # TypeError!
# print(5 + "3")     # TypeError!

# Solution: Convert types explicitly
print("5" + str(3))  # "53" (both strings)
print(int("5") + 3)  # 8 (both numbers)

Common Mistakes and Tips

Avoiding pitfalls

Type Conversion Mistakes

❌ Common errors:

# Error: Can't convert string with decimal to int directly
age = int("25.5")  # ValueError!

# Error: Can't convert non-numeric string
number = int("hello")  # ValueError!

✅ Correct approaches:

# Convert to float first, then to int
age = int(float("25.5"))  # 25

# Check if string contains only digits
text = "123"
print(text.isdigit())  # True
# We'll learn how to use this check with conditional statements

Division Safety

# Integer division vs. regular division
print(7 / 2)    # 3.5 (regular division)
print(7 // 2)   # 3 (floor division)

# Division by zero causes errors
# print(5 / 0)  # ZeroDivisionError!

# Always be careful with division
numerator = 10
denominator = 0
print(f"Attempting to divide {numerator} by {denominator}")
# We'll learn how to handle this safely with conditional statements

String vs. Number Confusion

# String concatenation vs. arithmetic
print("5" + "3")    # "53" (string concatenation)
print(5 + 3)        # 8 (arithmetic addition)

# Mixed types cause errors
# print("5" + 3)    # TypeError!

# Convert for proper operation
print("5" + str(3))   # "53"
print(int("5") + 3)   # 8