Python 3 Core Concepts: A Practical Guide
This guide covers essential Python programming concepts through hands-on code eaxmples. Each section includes working code snippets with expected output.
- Working with Jupyter Notebook
Jupyter Notebook is an interactive development environment widely used in Python development. Here are essential keyboard shortcuts:
- Select a cell and press DD to delete it
- Press Shift+Enter to run code and move to the next cell
- Press Ctrl+Enter to run code without moving
- Press M to convert a cell to Markdown format
- The print() Function
The print() function outputs values to the console. It handles strings, numbers, and concatenation.
print(1)
print('hello')
print("it's working")
print('it\'s working')
print('a' + 'b')
Output:
1
hello
it's working
it's working
ab
- Mathematical Operations
Python supports standard mathematical operators. The exponentiation operator (**) raises a number to a power.
result = 2 ** 3
print(result)
Output:
8
- Loops and Indentation
Python uses indentation to define code blocks. Four spaces is the standard indentation level.
While Loop
i = 0
while i < 3:
print(i)
i = i + 1
Output:
0
1
2
For Loop
for i in range(1, 5):
print(i)
Output:
1
2
3
4
The range() function generates a sequence from the start value (inclusive) to the end value (exclusive).
- Conditional Statements
Python supports if, elif (else if), and else statements for conditional logic.
a = 10
b = 5
# Simple if statement
if a > b:
print('a is greater than b')
# If-else statement
if a > b:
print('a is greater')
else:
print('b is greater or equal')
# If-elif-else chain
a = 5
b = 5
if a > b:
print('a is greater')
elif a == b:
print('a equals b')
else:
print('b is greater')
- Functions
Functions are defined using the def keyword. They can accept parameters and return values.
def add_numbers(x, y):
result = x + y
print(result)
add_numbers(3, 4)
Output:
7
Default Parameters
Parameters can have default values. When a default parameter is provided, the argument becomes optional.
def default_function(a, b=3):
result = a + b
print(result)
default_function(2)
Output:
5
Important Rule: Non-default arguments cannot follow default argumants. The following code will raise a SyntaxError:
# This will cause an error
def invalid_function(a=3, b):
print(a + b)
Error: SyntaxError: non-default argument follows default argument
- File Operations
Creating and Writing to a File
content = "1,2,3"
file = open('data.txt', 'w')
file.write(content)
file.close()
Appending to an Existing File
new_content = "\nhello world"
file = open('data.txt', 'a')
file.write(new_content)
file.close()
Reading from a File
file = open('data.txt', 'r')
content = file.read()
print(content)
file.close()
Output:
1,2,3
hello world
- Classes and Object-Oriented Programming
Classes define blueprints for creating objects. They encapsulate data and functionality.
class Calculator:
price = 18
brand = "casco"
def add(self, x, y):
result = x + y
print(result)
def show_price(self):
print(self.price)
calc = Calculator()
calc.add(3, 5)
calc.show_price()
Output:
8
18
The self parameter refers to the instance of the class and must be included in all method definitions.
The __init__ Constructor
The __init__ method initializes object attributes when an instance is created.
class Calculator:
def __init__(self, name, price, brand, size):
self.n = name
self.p = price
self.b = brand
self.s = size
def show_details(self):
print(self.n, self.p, self.b, self.s)
calc2 = Calculator('q', 3, 'y', 2)
calc2.show_details()
print(calc2.n)
Default Values in Class Constructors
class Calculator:
def __init__(self, name='e', price=8, brand='u', size=7):
self.n = name
self.p = price
self.b = brand
self.s = size
def show_details(self):
print(self.n, self.p, self.b, self.s)
calc3 = Calculator()
calc3.show_details()
Output:
e 8 u 7
- The input() Function
The input() function reads user input from the console. All input is treated as a string by default.
user_input = input()
if user_input == '1':
print('yes')
else:
print('no')
Input:
1
Output:
yes
To convert input to other types, use type casting functions like int() or float().
- Tuples and Lists
Tuples are immutable sequences, while lists are mutable. Both can store multiple items.
# Tuple - immutable
a_tuple = (1, 2, 3, 4, 5, 6)
# List - mutable
a_list = [7, 6, 5, 4, 3, 2]
# Iterating over a tuple
for item in a_tuple:
print(item, end=' ')
print()
# Accessing list elements by index
for i in range(len(a_list)):
print(a_list[i], end=' ')
print()
Output:
1 2 3 4 5 6
7 6 5 4 3 2
List Methods
a_list = [7, 6, 5, 4, 3, 2]
a_list.append('a')
print(a_list)
a_list.insert(3, 'h')
print(a_list)
a_list.remove('h')
print(a_list)
print(a_list[-1]) # Last element
print(a_list[2:4]) # Elements from index 2 to 3
print(a_list.index('a')) # Find index of element
b_list = [1, 8, 5, 8, 9, 2]
b_list.sort()
print(b_list) # Small to large
b_list.sort(reverse=True)
print(b_list) # Large to small
Output:
[7, 6, 5, 4, 3, 2, 'a']
[7, 6, 5, 'h', 4, 3, 2, 'a']
[7, 6, 5, 4, 3, 2, 'a']
a
[5, 4]
6
[1, 2, 5, 8, 8, 9]
[9, 8, 8, 5, 2, 1]
Multi-dimensional Lists
multi_list = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(multi_list[0][0]) # First row, first column
print(multi_list[1][2]) # Second row, third column
Output:
1
6
- Dictionaries
Dictionaries store key-value pairs. Keys must be unique and immutable.
student = {'name': 'Alice', 'age': 25, 'major': 'Computer Science'}
print(student['age'])
# Delete a key-value pair
del student['major']
print(student)
# Values can be tuples, lists, functions, or even other dictionaries
complex_dict = {
'data': (1, 2, 3),
'nested': {'inner': 'value'},
'function': len
}
Output:
25
{'name': 'Alice', 'age': 25}
- Importing Modules
Modules extend Python's functionality. Use the import statement to include external libraries.
import time as t
print(t.localtime())
Output:
time.struct_time(tm_year=2025, tm_mon=1, tm_mday=15, tm_hour=10, tm_min=30, tm_sec=45, tm_wday=2, tm_yday=15, tm_isdst=0)
- Break and Continue Statements
The break statement exits a loop completely. The continue statement skips to the next iteration.
# Using break to exit loop
while True:
user_input = input()
if user_input == 'quit':
print('ending program')
break
else:
print('continuing...')
# Using continue to skip iteration
while True:
user_input = input()
if user_input == 'skip':
print('skipping this iteration')
continue
elif user_input == 'quit':
break
else:
print('processing:', user_input)
- Functional Programming: map, lambda, and zip
The zip() Function
zip() combines multiple iterables element-wise into tuples.
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined = list(zip(list1, list2))
print(combined)
# zip with three lists
list3 = [7, 8, 9]
triple = list(zip(list1, list2, list3))
print(triple)
Output:
[(1, 4), (2, 5), (3, 6)]
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
Lambda Functions
Lambda functions are anonymous functions defined in a single line. They are useful for short operations.
# Regular function
def add(x, y):
return x + y
result = add(2, 6)
print(result)
# Lambda equivalent
add_lambda = lambda x, y: x + y
result = add_lambda(4, 3)
print(result)
Output:
8
7
The map() Function
map() applies a function to each element of an iterable.
def multiply(x, y):
return x * y
# map with two lists
result = map(multiply, [2, 3, 4], [5, 6, 7])
print(list(result))
Output:
[10, 18, 28]
Combining lambda with map provides a concise way to transform data:
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
print(squared)
Output:
[1, 4, 9, 16, 25]