# 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
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.
A variable is like a labeled container that stores a value. Think of it as a box with a name tag on it!
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
✅ 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
Python has several built-in data types. Let’s explore the most common ones!
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 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 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 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 equal5 == 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
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'>
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
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
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!
Now it’s your turn! Try these exercises:
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 informationCreate a simple calculator that performs basic operations:
num1 = 15
num2 = 4
# Calculate and print:
# - Sum
# - Difference
# - Product
# - Division resultConvert temperature from Celsius to Fahrenheit: Formula: F = (C × 9/5) + 32
celsius = 25
# Calculate fahrenheit
# Print the resultHere are the solutions to the exercises:
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
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
celsius = 25
fahrenheit = (celsius * 9/5) + 32
print(f"{celsius}°C is equal to {fahrenheit}°F")25°C is equal to 77.0°F
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
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!