Programming with Python | Chapter 2: Variables, Data Types, and Basic Operators
Chapter Objectives
- Understand the concept of variables for storing data.
- Learn Python’s rules for naming variables.
- Identify and use fundamental data types: integers (
int
), floating-point numbers (float
), strings (str
), and booleans (bool
). - Understand how to check the type of a variable using
type()
. - Perform basic arithmetic operations using operators (
+
,-
,*
,/
,//
,%
,**
). - Use assignment operators (
=
,+=
,-=
, etc.) to modify variable values. - Understand the concept of data type conversion (casting).
Introduction
In Chapter 1, we learned how to print messages and simple calculations. To write more complex and useful programs, we need a way to store and manage data. This chapter introduces variables, which act as named containers for data within your program. We will explore Python‘s fundamental data types – the different kinds of information variables can hold, such as numbers and text. Finally, we’ll learn how to manipulate this data using operators, starting with basic arithmetic and assignment.
Theory & Explanation
Variables: Naming Storage Locations
Think of a variable as a labeled box where you can store a piece of information (data). Instead of referring to the data directly, you refer to the label on the box (the variable name). When you need the data, you use the variable’s name, and Python retrieves the value stored inside.
Assigning a value to a variable is done using the assignment operator (=
).
# Assigning the integer value 42 to a variable named 'age'
age = 42
# Assigning the string value "Alice" to a variable named 'name'
name = "Alice"
Now, whenever you use age
in your code, Python substitutes it with 42
. If you use name
, Python substitutes it with "Alice"
.
Variable Naming Rules & Conventions:
Must start with a letter (a-z, A-Z) or an underscore (_).
Cannot start with a number.- Can only contain letters, numbers (0-9), and underscores. No spaces or special characters like
!
,@
,#
,$
,%
. - Case-sensitive:
myVariable
is different frommyvariable
orMyVariable
. - Cannot be a Python keyword: Keywords are reserved words with special meaning in Python (e.g.,
if
,else
,for
,while
,def
,class
,True
,False
,None
). You cannot use them as variable names. - Convention (PEP 8): Use
snake_case
for variable names (all lowercase words separated by underscores). Example:first_name
,item_count
,total_price
. While other styles work,snake_case
is the standard Python convention and improves readability.
Python Variable Naming Examples
Rule Type | VALID ✓ | INVALID ✗ |
---|---|---|
Starting Character | ✓ user_name = “John” ✓ _private = 100 |
✗ 3total = 42 ✗ 123 = “numbers” |
Allowed Characters | ✓ total3 = 42 ✓ hello_world_2 = “Hi” |
✗ user-name = “John” ✗ my@email = “a@b.com” |
Spacing | ✓ camelCase = True ✓ name = “Bob” |
✗ user name = “Bob” |
Case Style Options | ✓ snake_case = “preferred” ✓ camelCase = True ✓ PascalCase = “Class names” |
✗ kebab-case = “not allowed” |
Reserved Keywords | ✓ class_name = “Python” ✓ for_loop = 5 |
✗ class = “Python” ✗ for = 5 ✗ True = False |
Best Practice | ✓ CONSTANT = 3.14 ✓ user_age = 25 |
✗ a = 42 (unclear name) ✗ verylongvariablenamewithnounderscore = True |
Note: Python is case-sensitive, so score
, Score
, and SCORE
are all different variables.
Fundamental Data Types
Every value in Python has a data type, which determines what kind of data it is and what operations can be performed on it. Python is dynamically typed, meaning you don’t have to explicitly declare the type of a variable; Python infers it from the value assigned.
flowchart TD A[Python Data Types] --> B[Numeric] A --> C[Text Sequence] A --> D[Boolean] A --> E[None] B --> F[int] B --> G[float] C --> H[str] D --> I[bool] F --> J["Examples: -10, 0, 42, 1000"] G --> K["Examples: 3.14, -0.1, 2.0, 6.022e23"] H --> L["Examples: hello, Python, multiline string"] I --> M["Values: True, False"] E --> N["Value: None"] style A fill:#f9f,stroke:#333,stroke-width:2px style B fill:#bbf,stroke:#333 style C fill:#bbf,stroke:#333 style D fill:#bbf,stroke:#333 style E fill:#bbf,stroke:#333 style F fill:#ddf,stroke:#333 style G fill:#ddf,stroke:#333 style H fill:#ddf,stroke:#333 style I fill:#ddf,stroke:#333 style J fill:#f5f5f5,stroke:#333 style K fill:#f5f5f5,stroke:#333 style L fill:#f5f5f5,stroke:#333 style M fill:#f5f5f5,stroke:#333 style N fill:#f5f5f5,stroke:#333
Here are the most common fundamental types:
Integer (int):
Whole numbers (positive, negative, or zero) without decimals.- Examples:
-10
,0
,1
,999
- Examples:
Floating-Point Number (float):
Numbers with a decimal point or represented in exponential (E) notation.- Examples:
-3.14
,0.0
,99.99
,1.2e3
(which is 1.2 * 10^3 = 1200.0)
- Examples:
String (str):
Sequences of characters, used to represent text. Enclosed in single quotes ('...'
), double quotes ("..."
), or triple quotes ('''...'''
or"""..."""
for multi-line strings).- Examples:
'Hello'
,"Python"
,"123"
,'''This is a multi-line string.'''
- Examples:
Boolean (bool):
Represents truth values. Can only be one of two values:True
orFalse
(note the capitalization). Often the result of comparisons.- Examples:
True
,False
- Examples:
Checking Data Types:
You can use the built-in type()
function to determine the data type of a variable or value.
count = 10
price = 19.95
message = "Order confirmed"
is_valid = True
print(type(count)) # Output: <class 'int'>
print(type(price)) # Output: <class 'float'>
print(type(message)) # Output: <class 'str'>
print(type(is_valid)) # Output: <class 'bool'>
print(type(5)) # Output: <class 'int'>
print(type("abc")) # Output: <class 'str'>
Basic Operators
Operators are special symbols used to perform operations on values (operands).
1. Arithmetic Operators: Used for mathematical calculations.
Arithmetic Operators in Python
Operator | Description | Example | Result |
---|
Try changing the values above to see how the results change!
2. Assignment Operators: Used to assign values to variables.
Data Type Conversion (Casting)
Sometimes you need to convert a value from one data type to another. This is called casting. Python provides built-in functions for this:
int(value)
: Convertsvalue
to an integer. Fails if the value cannot be interpreted as a whole number (e.g.,int("hello")
). Truncates floats (e.g.,int(5.9)
becomes5
).float(value)
: Convertsvalue
to a float. Works for integers and strings representing numbers (e.g.,float("123.45")
).str(value)
: Convertsvalue
to a string. Works for almost any data type.bool(value)
: Convertsvalue
to a boolean. Most values convert toTrue
, except for0
,0.0
,""
(empty string),None
, and empty collections (which we’ll see later), which convert toFalse
.
num_str = "100"
num_int = int(num_str) # num_int is now the integer 100
print(type(num_int)) # <class 'int'>
price_float = 99.0
price_int = int(price_float) # price_int is now the integer 99 (truncated)
print(price_int) # 99
count = 50
count_str = str(count) # count_str is now the string "50"
print(type(count_str)) # <class 'str'>
value = 0
is_true = bool(value) # is_true is False
print(is_true) # False
value = "Hello"
is_true = bool(value) # is_true is True
print(is_true) # True
Interactive Example for Type Casting:
Data Type Conversion (Casting)
int(value)
Converts to whole number. Fails if not a valid number.
float(value)
Converts to decimal number. Fails if not a valid number.
str(value)
Converts to string. Works for almost any data type.
bool(value)
False for: 0, “”, null, undefined, NaN.
Code Examples
Example 1: Using Variables and Arithmetic Operators
# variables_math.py
# Assigning initial values
apples = 15
oranges = 8
cost_per_apple = 0.50 # dollars
cost_per_orange = 0.75 # dollars
# Calculating total number of fruits
total_fruits = apples + oranges
# Calculating total cost
total_cost = (apples * cost_per_apple) + (oranges * cost_per_orange)
# Displaying the results
print("Number of apples:", apples)
print("Number of oranges:", oranges)
print("Total number of fruits:", total_fruits)
print("Total cost: $", total_cost)
# Example of floor division and modulus
num_students = 25
group_size = 4
full_groups = num_students // group_size
leftover_students = num_students % group_size
print("Number of full groups:", full_groups)
print("Students left over:", leftover_students)
Explanation:
- We define variables (
apples
,oranges
,cost_per_apple
, etc.) to store known quantities. - We use arithmetic operators (
+
,*
) to calculate derived values (total_fruits
,total_cost
). Parentheses()
are used to control the order of operations (multiplication before addition). - The
print()
function displays both descriptive text (strings) and the values stored in the variables. - Floor division (
//
) gives the whole number of groups, while modulus (%
) gives the remainder.
Example 2: Using Assignment Operators and Type Casting
# assignment_casting.py
score = 100
print("Initial score:", score) # Output: 100
# Add 10 points
score += 10 # Equivalent to score = score + 10
print("Score after adding 10:", score) # Output: 110
# Double the score
score *= 2 # Equivalent to score = score * 2
print("Score after doubling:", score) # Output: 220
# Get input from the user (input() always returns a string)
bonus_str = input("Enter bonus points: ")
# Convert the input string to an integer before adding
# This will cause an error if the user doesn't enter a valid number!
bonus_points = int(bonus_str)
score += bonus_points
print("Final score after bonus:", score)
# Convert final score to string for display message
final_message = "Your final score is: " + str(score)
print(final_message)
Explanation:
- We initialize
score
to 100. - Assignment operators (
+=
,*=
) provide a concise way to modify the variable’s value based on its current value. - The
input()
function reads user input, but crucially, it returns it as a string. - We use
int()
to cast the input stringbonus_str
to an integerbonus_points
so we can perform arithmetic addition. Without this cast, tryingscore + bonus_str
would cause aTypeError
. - Finally, we use
str()
to cast the integerscore
back to a string so it can be concatenated (+) with thefinal_message
string for printing.
Common Mistakes or Pitfalls
- TypeError: Trying to perform operations between incompatible types (e.g., adding a string to an integer:
5 + " apples"
). Remember to cast types when necessary. - NameError: Using a variable name before assigning a value to it, or misspelling a variable name.
- Integer Division vs. Float Division: Forgetting that
/
always results in a float, even if the result is a whole number (10 / 2
is5.0
). Use//
if you specifically need an integer result from division. - Input is Always String: Forgetting that
input()
returns a string and failing to cast it toint
orfloat
before performing numerical operations. - Variable Naming: Using invalid characters or starting variable names with numbers. Using keywords as variable names.
Chapter Summary
- Variables are named containers for storing data, assigned using
=
. - Variable names must follow specific rules (start with letter/underscore, contain letters/numbers/underscores, case-sensitive, not keywords). Use
snake_case
convention. - Python has fundamental data types:
int
(whole numbers),float
(decimal numbers),str
(text), andbool
(True
/False
). - Python is dynamically typed; variable types are inferred. Use
type()
to check a variable’s type. - Arithmetic operators (
+
,-
,*
,/
,//
,%
,**
) perform calculations. - Assignment operators (
=
,+=
,-=
, etc.) assign and modify variable values. - Type casting (
int()
,float()
,str()
,bool()
) converts values between data types, which is often necessary, especially when handling user input.
Exercises & Mini Projects
Exercises
- Variable Swap: Create two variables,
a = 5
andb = 10
. Write code to swap their values (soa
becomes 10 andb
becomes 5). Print the values before and after the swap. (Hint: You might need a third temporary variable). - Temperature Converter (Celsius to Fahrenheit): Write a script that:
- Assigns a temperature value in Celsius to a variable (e.g.,
celsius = 25
). - Calculates the equivalent Fahrenheit temperature using the formula:
F = (C * 9/5) + 32
. - Prints the result in a user-friendly format, e.g., “25 degrees Celsius is equal to 77.0 degrees Fahrenheit.”
- Assigns a temperature value in Celsius to a variable (e.g.,
- String Repetition: Create a string variable
symbol = "*"
. Use the multiplication operator (*
) with the string and an integer to print a line of 50 asterisks. - Data Type Exploration: Create variables of different types (
int
,float
,str
,bool
). Use thetype()
function to print the type of each variable. Try converting theint
to afloat
and thefloat
to anint
. Print the results and their types. - Modulo Operator: Write a script that determines if a number (assigned to a variable
num
) is even or odd. Print “Even” if it is, and “Odd” otherwise. (Hint: Use the modulo operator%
. An even number has a remainder of 0 when divided by 2).
Variable Swap Animation
Memory Visualization
Python Code
Mini Project: Simple Area Calculator
Goal: Create a Python script area_calculator.py
that calculates the area of a rectangle.
Steps:
- Use the
input()
function twice to ask the user for thewidth
andheight
of a rectangle. - Remember that
input()
returns strings. Convert both thewidth
andheight
inputs to floating-point numbers usingfloat()
. Store them in variables (e.g.,rect_width
,rect_height
). - Calculate the area of the rectangle (
area = width * height
). Store the result in a variablerect_area
. - Use the
print()
function to display the calculated area in a clear message, e.g., “The area of the rectangle is: 150.75”.
Additional Resources:
https://www.w3schools.com/python/python_variables.asp