Skip to content
Python Programming

Python Basics

Beginner Lesson 2 of 10

In this lesson, we’ll explore the fundamental building blocks of Python: variables, data types, and operators.

Variables are containers for storing data values. In Python, you don’t need to declare a variable type - Python figures it out automatically.

# Creating variables
name = "Alice"
age = 25
height = 5.7
is_student = True
# Printing variables
print(name) # Output: Alice
print(age) # Output: 25
print(height) # Output: 5.7
print(is_student) # Output: True
  • Must start with a letter or underscore
  • Can contain letters, numbers, and underscores
  • Case-sensitive (name and Name are different)
  • Cannot use reserved keywords (if, for, class, etc.)
# Good variable names
user_name = "Bob"
userAge = 30
_private = "secret"
MAX_SIZE = 100
# Bad variable names (will cause errors)
# 2name = "Error" # Cannot start with number
# my-name = "Error" # Cannot use hyphens
# class = "Error" # Cannot use reserved words
# snake_case for variables and functions (recommended)
first_name = "John"
total_count = 42
# UPPER_CASE for constants
MAX_CONNECTIONS = 100
PI = 3.14159
# PascalCase for classes
class UserProfile:
pass

Python has several built-in data types:

# Integer (int) - whole numbers
count = 42
negative = -10
big_number = 1_000_000 # Underscores for readability
# Float - decimal numbers
price = 19.99
temperature = -5.5
scientific = 1.5e-4 # Scientific notation (0.00015)
# Complex numbers
complex_num = 3 + 4j
# Strings - text data
single_quotes = 'Hello'
double_quotes = "World"
multiline = """This is a
multiline string"""
# String operations
greeting = "Hello"
name = "World"
message = greeting + " " + name # Concatenation: "Hello World"
repeated = "Ha" * 3 # Repetition: "HaHaHa"
# String indexing (0-based)
text = "Python"
print(text[0]) # 'P' (first character)
print(text[-1]) # 'n' (last character)
print(text[0:3]) # 'Pyt' (slicing)
# Useful string methods
text = " hello world "
print(text.upper()) # " HELLO WORLD "
print(text.lower()) # " hello world "
print(text.strip()) # "hello world"
print(text.replace("world", "Python")) # " hello Python "
print(len(text)) # 15
# f-strings (formatted strings) - Python 3.6+
name = "Alice"
age = 25
print(f"My name is {name} and I'm {age} years old")
# Boolean - True or False
is_active = True
is_logged_in = False
# Boolean operations
print(True and False) # False
print(True or False) # True
print(not True) # False
# Truthy and Falsy values
# Falsy: False, 0, 0.0, "", [], {}, None
# Truthy: Everything else
# None represents absence of value
result = None
if result is None:
print("No result yet")
# Check type
x = 42
print(type(x)) # <class 'int'>
y = "hello"
print(type(y)) # <class 'str'>
# Type conversion (casting)
num_str = "42"
num_int = int(num_str) # String to integer: 42
num_float = float(num_str) # String to float: 42.0
num = 42
num_as_str = str(num) # Integer to string: "42"
# Be careful with invalid conversions
# int("hello") # ValueError!
a = 10
b = 3
print(a + b) # Addition: 13
print(a - b) # Subtraction: 7
print(a * b) # Multiplication: 30
print(a / b) # Division: 3.333...
print(a // b) # Floor division: 3
print(a % b) # Modulus (remainder): 1
print(a ** b) # Exponentiation: 1000
a = 10
b = 5
print(a == b) # Equal: False
print(a != b) # Not equal: True
print(a > b) # Greater than: True
print(a < b) # Less than: False
print(a >= b) # Greater or equal: True
print(a <= b) # Less or equal: False
x = True
y = False
print(x and y) # False (both must be True)
print(x or y) # True (at least one True)
print(not x) # False (negation)
# Practical example
age = 25
has_license = True
can_drive = age >= 18 and has_license
print(can_drive) # True
x = 10 # Assign
x += 5 # Add and assign (x = x + 5) → 15
x -= 3 # Subtract and assign → 12
x *= 2 # Multiply and assign → 24
x /= 4 # Divide and assign → 6.0
x //= 2 # Floor divide and assign → 3.0
x **= 2 # Power and assign → 9.0
x %= 4 # Modulus and assign → 1.0
# Getting input from user
name = input("What is your name? ")
print(f"Hello, {name}!")
# Input is always a string - convert if needed
age_str = input("Enter your age: ")
age = int(age_str) # Convert to integer
birth_year = 2024 - age
print(f"You were born around {birth_year}")

Swap the values of two variables without using a third variable.

# Your task: Swap a and b
a = 5
b = 10
# After swap: a should be 10, b should be 5
Solution
a = 5
b = 10
a, b = b, a # Python's tuple unpacking!
print(a, b) # 10, 5

Convert temperature from Celsius to Fahrenheit.

# Formula: F = (C Ă— 9/5) + 32
celsius = 25
# Calculate fahrenheit
Solution
celsius = 25
fahrenheit = (celsius * 9/5) + 32
print(f"{celsius}°C = {fahrenheit}°F") # 25°C = 77.0°F

Given a user’s full name, extract and print the initials.

full_name = "John Michael Smith"
# Output should be: J.M.S.
Solution
full_name = "John Michael Smith"
parts = full_name.split()
initials = ".".join([name[0] for name in parts]) + "."
print(initials) # J.M.S.

In this lesson, you learned:

  • âś… How to create and name variables
  • âś… Python’s main data types (int, float, str, bool, None)
  • âś… Type checking and conversion
  • âś… Arithmetic, comparison, logical, and assignment operators
  • âś… Getting user input

In the next lesson, we’ll explore data structures in Python:

  • Lists, Tuples, and Sets
  • Dictionaries
  • Common operations on collections

Continue to Data Types →