Python Basics - 01. Introduction & Variables¶
Welcome to the beginner’s guide to Python! In this notebook, we’ll explore the foundational concepts of Python programming, including how to output data, define variables, and work with basic data types like integers, floating-point numbers, strings, and booleans.
Download Notebook¶
1. Hello World¶
Let’s start with the classic ‘Hello, World!’ program. In Python, you can use the built-in print() function to display text or variable contents on the screen.
print("Hello, World!")
print("Welcome to Python programming.")
Hello, World!
Welcome to Python programming.
2. Variables & Data Types¶
Python is a dynamically-typed language, which means you do not need to explicitly declare a variable’s type. The type is inferred when the value is assigned. Common basic data types include:
int: Whole numbers.
float: Decimal numbers.
str: A sequence of characters (text), enclosed in single or double quotes.
bool: Represents True or False values.
x = 10 # Integer (int)
y = 3.14 # Floating-point number (float)
name = "Alice" # String (str)
is_student = True # Boolean (bool)
print(f"Value of x: {x}, Type: {type(x)}")
print(f"Value of y: {y}, Type: {type(y)}")
print(f"Value of name: {name}, Type: {type(name)}")
print(f"Is student? {is_student}, Type: {type(is_student)}")
Value of x: 10, Type: <class 'int'>
Value of y: 3.14, Type: <class 'float'>
Value of name: Alice, Type: <class 'str'>
Is student? True, Type: <class 'bool'>
3. Basic Arithmetic Operations¶
Python supports all standard mathematical operations out of the box. Notice the difference between standard division / and floor division //.
a = 15
b = 4
print(f"{a} + {b} = {a + b}") # Addition
print(f"{a} - {b} = {a - b}") # Subtraction
print(f"{a} * {b} = {a * b}") # Multiplication
print(f"{a} / {b} = {a / b}") # True Division (returns a float)
print(f"{a} // {b} = {a // b}") # Floor Division (discards the fractional part)
print(f"{a} % {b} = {a % b}") # Modulo (remainder of division)
print(f"{a} ** 2 = {a ** 2}") # Exponentiation (power of)
15 + 4 = 19
15 - 4 = 11
15 * 4 = 60
15 / 4 = 3.75
15 // 4 = 3
15 % 4 = 3
15 ** 2 = 225
4. String Manipulation¶
Strings in Python are powerful and flexible. You can extract subsections via ‘slicing’, determine their length, or change their casing.
text = "Python Programming"
print(f"Original text: '{text}'")
print(f"Length of the string: {len(text)}")
print(f"Uppercase: {text.upper()}")
print(f"Lowercase: {text.lower()}")
# String slicing: text[start:stop] -> extracts characters from 'start' up to, but not including, 'stop'
print(f"First 6 characters: {text[0:6]}")
Original text: 'Python Programming'
Length of the string: 18
Uppercase: PYTHON PROGRAMMING
Lowercase: python programming
First 6 characters: Python
5. Formatted Strings (f-strings)¶
When reading data from files, you often need clean output formatting. Python f-strings make it easy to embed variables and control number formatting directly inside strings.
Common patterns:
f"Name: {name}"for variable interpolation.f"{value:.2f}"for fixed decimal places.f"{num:>6}"for width and alignment.
# Example: formatting output from file-like records
records = [
{"name": "Alice", "score": 95.2345},
{"name": "Bob", "score": 88.5},
{"name": "Cara", "score": 100}
]
print("Simple interpolation:")
for item in records:
print(f"Name: {item['name']}, Score: {item['score']}")
print("\nDecimal formatting (2 digits):")
for item in records:
print(f"Name: {item['name']}, Score: {item['score']:.2f}")
print("\nAligned table output:")
print(f"{'Name':<10} {'Score':>8}")
print("-" * 19)
for item in records:
print(f"{item['name']:<10} {item['score']:>8.2f}")
# Bonus: zero-padding numbers
for idx in range(1, 4):
print(f"Record ID: {idx:03d}")
Simple interpolation:
Name: Alice, Score: 95.2345
Name: Bob, Score: 88.5
Name: Cara, Score: 100
Decimal formatting (2 digits):
Name: Alice, Score: 95.23
Name: Bob, Score: 88.50
Name: Cara, Score: 100.00
Aligned table output:
Name Score
-------------------
Alice 95.23
Bob 88.50
Cara 100.00
Record ID: 001
Record ID: 002
Record ID: 003
6. Type Conversion, Identity, and Mutability¶
Type Conversion¶
Python allows explicit conversion between common types with constructors like int(), float(), and str().
Identity vs Equality¶
==checks whether values are equal.ischecks whether two variables reference the same object in memory.
Mutable vs Immutable¶
Immutable:
int,float,str,tuple.Mutable:
list,dict,set.
Understanding this difference helps you avoid bugs when passing objects into functions.
# Type conversion examples
# raw_age is a string coming from user input or text files.
raw_age = "21"
# int() converts text digits into an integer value.
age = int(raw_age)
height_text = "175.5"
# float() converts decimal text into a float number.
height = float(height_text)
# Numeric operations now work because types are converted.
print(age + 1)
print(height / 10)
# str() converts number back to string for concatenation.
print(str(age) + " years old")
# Equality vs identity
# == compares values.
# is compares whether two variables point to the exact same object.
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a == b) # True: same content
print(a is b) # False: different list objects
print(a is c) # True: same object reference
# Mutability demo
# Lists are mutable, so alias and items point to one shared object.
items = ["A", "B"]
alias = items
alias.append("C")
print(items) # Also changed because alias modifies the same list
22
17.55
21 years old
True
False
True
['A', 'B', 'C']