Python Fundamentals: Code Examples and Exercises
Python Operations and Operators
This section covers fundamental operations and operators in Python, which are symbols used to perform operations on values and variables.
# Examples of different operators
a = 10 // 3 # Floor Division
a = 10 % 3 # Modulo Operator
a = 3 # Assignment
b = 1 # Declaring variables
a == b # ComparisonTypes of Operators
Operators are used for operations between values and variables. The main types are:
- Assignment Operators: Used to assign values to variables.
- Logical Operators: Used to combine conditional statements.
- Comparison Operators: Used to compare two values.
- Arithmetic Operators: Used with numeric values to perform common mathematical operations.
- Bitwise Operators: Used to compare binary numbers.
- Identity Operators: Used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location.
- Membership Operators: Used to test if a sequence is presented in an object.
Practice: Arithmetic Operations
# Variable declaration
a, b, c, d, e = 12, 3, 4.0, 6.0, 'hi'
# Addition
f, g = a + b, a + c
print(f)
print(g)
print(type(g))
# Multiplication
mult_int, mult_float, multi_comb = a * b, c * d, a * d
print(f"Multiplication of 2 Ints: {mult_int}")
print(f"Multiplication of 2 Floats: {mult_float}")
print(f"Multiplication of Int & Float: {multi_comb}")
# Division
divi_int, divi_float, divi_comb = a // b, d // c, a // d
print(f"Division of 2 Ints: {divi_int}")
print(f"Division of 2 Floats: {divi_float}")
print(f"Division of Int & Float: {divi_comb}")
# String multiplication
l = e * 3
print(l)
# A string cannot be multiplied by a float.
# m = e * c
# print(m) # This would raise a TypeError
# An integer cannot be added to a string directly.
# n = 2 + e
# print(n) # This would raise a TypeError
# String concatenation
o = e + '2'
print(o, type(o)) # Order matters in this case
# Other arithmetic operations
p = a // b # Floor division
q = a % b # Modulo
r = a ** b # Exponentiation
print(f"{p} {q} {r}")
s = a // c
t = a % c
u = a ** c
print(f"{s} {t} {u}")Exercise: Hello World
A simple script that prints "Hello World," adds comments, and uses a variable.
# This variable stores the "Hello World" string.
a = "Hello World"
print(a)Exercise: Rectangle Area and Perimeter
A Python program to print both the area and the circumference (perimeter) of a rectangle based on user input.
length = int(input("Enter the value of length:\n"))
breadth = int(input("Enter the value of breadth:\n"))
area = length * breadth
perimeter = 2 * (length + breadth)
print(f"Area of the rectangle is: {area}")
print(f"Circumference (Perimeter) of the rectangle is: {perimeter}")Boolean and Bitwise Operations in Python
Boolean (Logical) Operations
Demonstrating boolean and logical operations which result in either True or False.
a = 15
print(a == 10) # False
print(a < 10) # False
print(a != 15) # False
print(a <= 20) # True
print(a >= 10) # True
a = 50
b = 25
# AND operator
print(a > 40 and b > 40) # False
print(a > 100 and b < 50) # False
print(a == 0 and b == 0) # False
print(a > 0 and b > 0) # True
print(1 == 1 and 2 == 2) # True
print(1 == 1 and 2 == 3) # False
print(1 != 1 and 2 == 3) # False
print(1 < 1 and 3 > 6) # False
# OR operator
print(a > 40 or b > 40) # True
print(a > 100 or b < 50) # True
print(a == 0 or b == 0) # False
print(a > 0 or b > 0) # True
print(1 != 1 or 2 == 2) # True
# NOT operator
a = 10
print(a > 10) # False
print(not(a > 10)) # True
print(not(2 == 5)) # TrueBitwise Operations
Bitwise operations work on integers by first converting them to binary. The logical operation is performed on each bit, and the result is returned as a decimal value.
# Bitwise AND (&)
print(10 & 4) # 1010 & 0100 => 0000 (0)
print(10 & 10) # 1010 & 1010 => 1010 (10)
print(10 & 40) # 001010 & 101000 => 001000 (8)
print(15 & 15) # 1111 & 1111 => 1111 (15)
print(3 & 3) # 11 & 11 => 11 (3)
# Bitwise OR (|)
print(10 | 4) # 1010 | 0100 => 1110 (14)
print(10 | 10) # 1010 | 1010 => 1010 (10)
print(10 | 40) # 001010 | 101000 => 101010 (42)
print(15 | 15) # 1111 | 1111 => 1111 (15)
print(3 | 3) # 11 | 11 => 11 (3)
print(3 | 2) # 11 | 10 => 11 (3)
# Left Shift (<<)
print(3 << 1) # 0011 << 1 => 0110 (6)
print(3 << 2) # 0011 << 2 => 1100 (12)
print(13 << 3) # 1101 << 3 => 1101000 (104)
print(13 << 2) # 1101 << 2 => 110100 (52)
# Right Shift (>>)
print(3 >> 1) # 0011 >> 1 => 0001 (1)Python Type Casting Examples
Type casting is the process of converting a variable from one data type to another.
# Casting to float
print(float(10)) # 10.0
# print(float(10+5j)) # Cannot convert complex to float
print(float(True)) # 1.0
print(float(False)) # 0.0
print(float("10")) # 10.0
print(float("10.5")) # 10.5
# Casting to complex
print(complex(10)) # (10+0j)
print(complex(10.5)) # (10.5+0j)
print(complex(True)) # (1+0j)
print(complex(False)) # 0j
print(complex("10")) # (10+0j)
print(complex("10.5")) # (10.5+0j)
# print(complex("ten")) # ValueError
print(complex(10, -2)) # (10-2j)
print(complex(True, False)) # (1+0j)
# Casting to bool
print(bool(0)) # False
print(bool(1)) # True
print(bool(10)) # True
print(bool(10.5)) # True
print(bool(0.0)) # False
print(bool(0+0j)) # False
print(bool(1+1j)) # True
print(bool("True")) # True
print(bool("False")) # True
print(bool("")) # FalseMastering Loops in Python
Example: Multiplication Table
This program generates a multiplication table for a number provided by the user.
num = int(input("Enter the number for the multiplication table:\n"))
for i in range(1, 11):
j = i * num
print(f"{num} * {i} = {j}")
print(f"This is the table of {num}")Pattern Printing with Loops
Half Pyramid with Asterisks
rows = int(input("How many rows should be printed?\n"))
for i in range(1, rows + 1):
for j in range(i):
print("*", end='')
print("")Half Pyramid with Numbers
num = int(input("Enter the last number:\n"))
for i in range(1, num + 1):
for j in range(i):
print(j + 1, end='')
print("")Floyd's Triangle
num = 1
rows = int(input("Enter the number of rows:\n"))
for i in range(1, rows + 1):
for j in range(1, i + 1):
print(num, end=" ")
num += 1
print("")Creating Student Records with While Loops
This script creates a dictionary to store student names and marks using a while loop and allows for updating records.
rec = {}
n = int(input("Enter the number of students: "))
i = 1
while i <= n:
name = input("Enter Student Name: ")
marks = input("Enter the percentage marks of the student: ")
rec[name] = marks
i += 1
print("Name of Student\tPercentage of Marks")
for x in rec:
print(f"\t{x}\t\t{rec[x]}")
y = input("Enter the name of the student whose marks are to be updated: ")
z = int(input("Enter the updated marks: "))
rec.update({y: z})
print("\nUpdated Records:")
for m in rec:
print(f"\t{m}\t\t{rec[m]}")Python Function: Harshad Number Checker
A Harshad number (or Niven number) is an integer that is divisible by the sum of its digits. This code checks if a number is a Harshad number and also finds all two-digit Harshad numbers.
def harshad_number_checker(x):
y = x
digit_sum = 0
while x != 0:
digit = x % 10
digit_sum += digit
x = x // 10
if y % digit_sum == 0:
print(f"{y} is a Harshad number.")
else:
print(f"{y} is not a Harshad number.")
num = int(input("Enter a number: "))
harshad_number_checker(num)
print("\nFinding all Harshad numbers between 10 and 100:")
count = 0
for n_original in range(10, 100):
n_temp = n_original
digit_sum = 0
while n_temp != 0:
digit = n_temp % 10
digit_sum += digit
n_temp = n_temp // 10
if n_original % digit_sum == 0:
print(n_original)
count += 1
print("The total count is", count)NumPy Array Manipulation Techniques
Using the NumPy library to create and manipulate multi-dimensional arrays with specific patterns.
Array with 1s on Border, 0s Inside
import numpy as np
x = np.ones((5, 5))
print("Original array:\n", x)
print("\n1 on the border and 0 inside the array:")
x[1:-1, 1:-1] = 0
print(x)Checkerboard Pattern
import numpy as np
print("\nCheckerboard pattern:")
y = np.zeros((8, 8), dtype=int)
y[1::2, ::2] = 1
y[::2, 1::2] = 1
print(y)Array with 0s on Border, 1s Inside
import numpy as np
z = np.zeros((5, 5))
print("\nOriginal array:\n", z)
print("\n0 on the border and 1 inside the array:")
z[1:-1, 1:-1] = 1
print(z)Data Visualization with Matplotlib and NumPy
Creating charts and plots using the Matplotlib library to visualize data.
3D Bar Chart
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
# Sample Data
regions = ['North', 'South', 'East', 'West']
sales = [250, 400, 350, 300]
# 3D Bar Chart
fig = plt.figure(figsize=(10, 6))
ax = fig.add_subplot(111, projection='3d')
x_pos = np.arange(len(regions))
y_pos = np.zeros(len(regions))
z_pos = [0] * len(regions)
dx = dy = 0.5
dz = sales
ax.bar3d(x_pos, y_pos, z_pos, dx, dy, dz, color='skyblue')
ax.set_xlabel('Regions')
ax.set_ylabel('Categories')
ax.set_zlabel('Sales')
ax.set_xticks(x_pos)
ax.set_xticklabels(regions)
plt.title('3D Bar Chart: Sales by Region')
plt.show()Pie Chart
import matplotlib.pyplot as plt
# Sample Data
categories = ['Electronics', 'Clothing', 'Groceries']
sales_percent = [40, 35, 25]
# Pie Chart
plt.figure(figsize=(8, 6))
plt.pie(sales_percent, labels=categories, autopct='%1.1f%%', colors=['lightblue', 'lightgreen', 'pink'])
plt.title("Sales Percentage by Category")
plt.show()
English with a size of 10.65 KB