1  Variables and Data Types

1.1 Welcome to Python!

This tutorial will teach you the fundamentals of Python variables and data types. By the end, you’ll understand how to store and work with different kinds of data in Python.

1.2 What are Variables?

A variable is like a labeled container that stores a value. Think of it as a box with a name tag on it!

Creating Variables

In Python, creating a variable is simple - just give it a name and assign a value using the = sign:

# Create a variable called 'name' and store a text value
name = "Alice"
print(name)

# Create a variable called 'age' and store a number
age = 25
print(age)
Alice
25

Variable Naming Rules

✅ Good variable names: - Use lowercase letters and underscores: my_variable - Start with a letter or underscore: _count or total - Use descriptive names: user_age instead of x

❌ Invalid variable names: - Cannot start with a number: 2names ❌ - Cannot contain spaces: my variable ❌ - Cannot use special characters: my-variable ❌

# Good variable names
first_name = "Bob"
total_score = 100
is_student = True

print(f"Name: {first_name}")
print(f"Score: {total_score}")
print(f"Student: {is_student}")
Name: Bob
Score: 100
Student: True

1.3 Data Types

Python has several built-in data types. Let’s explore the most common ones!

Strings (str) - Text Data

Strings are used to store text. You can use single quotes '...' or double quotes "...".

# Creating strings
greeting = "Hello, World!"
message = 'Python is awesome!'
multiline = """This is a
multi-line
string"""

print(greeting)
print(message)
print(multiline)
Hello, World!
Python is awesome!
This is a
multi-line
string

String Operations:

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

# String length
print(f"Length of full name: {len(full_name)}")

# Uppercase and lowercase
print(full_name.upper())
print(full_name.lower())

# Accessing characters (indexing starts at 0)
print(f"First character: {full_name[0]}")
print(f"Last character: {full_name[-1]}")
John Doe
Length of full name: 8
JOHN DOE
john doe
First character: J
Last character: e

Integers (int) - Whole Numbers

Integers are whole numbers without decimals (positive, negative, or zero).

# Creating integers
positive_num = 42
negative_num = -10
zero = 0

print(positive_num)
print(negative_num)
print(zero)
42
-10
0

Math with Integers:

a = 10
b = 3

print(f"Addition: {a} + {b} = {a + b}")
print(f"Subtraction: {a} - {b} = {a - b}")
print(f"Multiplication: {a} * {b} = {a * b}")
print(f"Division: {a} / {b} = {a / b}")
print(f"Integer Division: {a} // {b} = {a // b}")
print(f"Remainder (Modulo): {a} % {b} = {a % b}")
print(f"Power: {a} ** {b} = {a ** b}")
Addition: 10 + 3 = 13
Subtraction: 10 - 3 = 7
Multiplication: 10 * 3 = 30
Division: 10 / 3 = 3.3333333333333335
Integer Division: 10 // 3 = 3
Remainder (Modulo): 10 % 3 = 1
Power: 10 ** 3 = 1000

Floats (float) - Decimal Numbers

Floats are numbers with decimal points.

# Creating floats
pi = 3.14159
temperature = -5.5
price = 19.99

print(f"Pi: {pi}")
print(f"Temperature: {temperature}°C")
print(f"Price: ${price}")
Pi: 3.14159
Temperature: -5.5°C
Price: $19.99

Float Operations:

# Math with floats
height = 5.9
width = 3.2
area = height * width

print(f"Area: {area}")
print(f"Rounded area: {round(area, 2)}")
Area: 18.880000000000003
Rounded area: 18.88

Booleans (bool) - True or False

Booleans represent truth values and can only be True or False.

# Creating booleans
is_sunny = True
is_raining = False

print(f"Is it sunny? {is_sunny}")
print(f"Is it raining? {is_raining}")
Is it sunny? True
Is it raining? False

Boolean Operations:

# Comparison operators create boolean values
x = 5
y = 10

print(f"{x} == {y}: {x == y}")  # Equal to
print(f"{x} != {y}: {x != y}")  # Not equal to
print(f"{x} < {y}: {x < y}")    # Less than
print(f"{x} > {y}: {x > y}")    # Greater than
print(f"{x} <= {y}: {x <= y}")  # Less than or equal
print(f"{x} >= {y}: {x >= y}")  # Greater than or equal
5 == 10: False
5 != 10: True
5 < 10: True
5 > 10: False
5 <= 10: True
5 >= 10: False

Logical Operators:

has_ticket = True
has_id = True
is_banned = False

# AND - both must be True
can_enter = has_ticket and has_id and not is_banned
print(f"Can enter: {can_enter}")

# OR - at least one must be True
is_vip = False
is_member = True
gets_discount = is_vip or is_member
print(f"Gets discount: {gets_discount}")
Can enter: True
Gets discount: True

1.4 Checking Data Types

You can check the type of any variable using the type() function:

name = "Alice"
age = 30
height = 5.7
is_student = False

print(f"type of name: {type(name)}")
print(f"type of age: {type(age)}")
print(f"type of height: {type(height)}")
print(f"type of is_student: {type(is_student)}")
type of name: <class 'str'>
type of age: <class 'int'>
type of height: <class 'float'>
type of is_student: <class 'bool'>

1.5 Type Conversion

Sometimes you need to convert between different data types:

# String to integer
age_str = "25"
age_int = int(age_str)
print(f"String '{age_str}' converted to integer: {age_int}")
print(f"Type: {type(age_int)}")

# String to float
price_str = "19.99"
price_float = float(price_str)
print(f"\nString '{price_str}' converted to float: {price_float}")
print(f"Type: {type(price_float)}")

# Integer to string
count = 100
count_str = str(count)
print(f"\nInteger {count} converted to string: '{count_str}'")
print(f"Type: {type(count_str)}")

# Float to integer (loses decimal part)
pi = 3.14159
pi_int = int(pi)
print(f"\nFloat {pi} converted to integer: {pi_int}")
String '25' converted to integer: 25
Type: <class 'int'>

String '19.99' converted to float: 19.99
Type: <class 'float'>

Integer 100 converted to string: '100'
Type: <class 'str'>

Float 3.14159 converted to integer: 3

1.6 Multiple Assignment

Python allows you to assign multiple variables at once:

# Assign same value to multiple variables
x = y = z = 0
print(f"x={x}, y={y}, z={z}")

# Assign different values to multiple variables
name, age, city = "Bob", 28, "New York"
print(f"Name: {name}, Age: {age}, City: {city}")

# Swap variables
a = 5
b = 10
print(f"Before swap: a={a}, b={b}")

a, b = b, a  # Swap!
print(f"After swap: a={a}, b={b}")
x=0, y=0, z=0
Name: Bob, Age: 28, City: New York
Before swap: a=5, b=10
After swap: a=10, b=5

1.7 User Input

You can get input from users using the input() function:

# Get user's name
user_name = input("What is your name? ")
print(f"Hello, {user_name}!")

# Get a number (input always returns a string!)
age_input = input("What is your age? ")
age_number = int(age_input)  # Convert to integer
print(f"You are {age_number} years old.")

Note: The code above won’t run in this document because it requires interactive input. Try it in your own Python environment!

1.8 Practice Exercises

Now it’s your turn! Try these exercises:

Exercise 1: Personal Information

Create variables to store your personal information and print them:

# Your code here:
my_name =
my_age =
my_height =
am_i_learning_python =

# Print all information

Exercise 2: Calculator

Create a simple calculator that performs basic operations:

num1 = 15
num2 = 4

# Calculate and print:
# - Sum
# - Difference
# - Product
# - Division result

Exercise 3: Temperature Converter

Convert temperature from Celsius to Fahrenheit: Formula: F = (C × 9/5) + 32

celsius = 25
# Calculate fahrenheit
# Print the result

1.9 Solutions

Here are the solutions to the exercises:

Solution 1:

Click to show solution
my_name = "Alex"
my_age = 20
my_height = 5.8
am_i_learning_python = True

print(f"Name: {my_name}")
print(f"Age: {my_age}")
print(f"Height: {my_height} feet")
print(f"Learning Python: {am_i_learning_python}")
Name: Alex
Age: 20
Height: 5.8 feet
Learning Python: True

Solution 2:

Click to show solution
num1 = 15
num2 = 4

sum_result = num1 + num2
difference = num1 - num2
product = num1 * num2
division = num1 / num2

print(f"Sum: {sum_result}")
print(f"Difference: {difference}")
print(f"Product: {product}")
print(f"Division: {division}")
Sum: 19
Difference: 11
Product: 60
Division: 3.75

Solution 3:

Click to show solution
celsius = 25
fahrenheit = (celsius * 9/5) + 32

print(f"{celsius}°C is equal to {fahrenheit}°F")
25°C is equal to 77.0°F

1.10 Key Takeaways

Remember: 1. Variables store data and can be changed 2. Use descriptive variable names with underscores 3. Main data types: str (text), int (whole numbers), float (decimals), bool (True/False) 4. Use type() to check data types 5. Use int(), float(), str() to convert between types 6. Python is dynamically typed - variables can change types

1.11 Next Steps

Now that you understand variables and data types, you’re ready to learn: - Lists and dictionaries (data structures) - Conditional statements (if/else) - Loops (for/while) - Functions

Keep practicing and happy coding!