Practice programs
Differences Between Python 2.x and 3.x
# Python 2.x:
print "Hello, World!" # This would work in Python 2.x
# Python 3.x:
print("Hello, World!") # Works in Python 3.x
# Integer division difference:
print(5 / 2) # Python 2.x would output 2, Python 3.x outputs 2.5
Elements of Python Language
x = 5 # Variable
y = 10
z = x + y # Expression
if z > 10: # Control structure (if-else)
print("z is greater than 10")
Identifiers
_myVar = 100 # Valid identifier
age = 25 # Valid identifier
3data = 50 # Invalid (starts with a digit)
Keywords
# Some Python keywords
if x > 0:
print("Positive")
else:
print("Non-positive")
Literals
x = 10 # Integer literal
pi = 3.14 # Floating-point literal
name = "Alice" # String literal
is_active = True # Boolean literal
Python Block Structure and Illustration of Blocks in Python
# The block is defined by indentation
if x > 0:
print("This is inside the block") # Indented code forms the block
print("This is outside the block")
Comments in Python
# This is a single-line comment
x = 10 # Assign 10 to x
# Printing the value of x
print(x) # Output: 10
'''
This is a multi-line comment
It spans multiple lines
Useful for larger explanations
'''
x = 20
y = 30
print(x + y) # Output: 50
x = 5 # Assigning value 5 to variable x
y = x * 2 # Multiplying x by 2 and storing it in y
print(y) # Output: 10
# Check if the number is positive, negative, or zero
num = -3
if num > 0:
print("Positive") # The number is greater than 0
elif num == 0:
print("Zero") # The number is exactly 0
else:
print("Negative") # The number is less than 0
# Original code
print("This line works")
# print("This line is disabled") # This line won't execute because it's
commented out
# Bad comment (explains what the code is doing, which is obvious from
the code itself)
x = x + 1 # Add 1 to x
# Good comment (explains why we are adding 1 to x)
x = x + 1 # Increment x to account for the loop iteration
'''
This function implements the Fibonacci sequence.
The Fibonacci sequence is defined as:
F(n) = F(n-1) + F(n-2), with base cases F(0) = 0, F(1) = 1.
This implementation uses recursion to calculate the nth Fibonacci
number.
'''
def fibonacci(n):
# Base case
if n <= 1:
return n
# Recursive case
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(5)) # Output: 5
Variables and Assignment Statement
x = 5 # Assignment statement
y = "Hello"
z = x + 10
# Assigning the same value to multiple variables
a = b = c = 100
print(a) # 100
print(b) # 100
print(c) # 100
# Assigning different values to multiple variables
x, y, z = 10, 20, 30
print(x) # 10
print(y) # 20
print(z) # 30
# Swapping two variables
x, y = 5, 10
print("Before swapping:", x, y) # Before swapping: 5 10
# Swap
x, y = y, x
print("After swapping:", x, y) # After swapping: 10 5
# Defining a constant (by convention)
PI = 3.14159
RADIUS = 5
# Using constant in a formula
area = PI * RADIUS ** 2
print("Area of the circle:", area) # 78.53975
# Chained assignment
x = y = z = 50
print(x, y, z) # 50 50 50
# Modifying one variable doesn't affect the others
x = 10
print(x, y, z) # 10 50 50
a = 10
print(a) # 10
# Deleting variable a
del a
# print(a) # This would raise an error because a is deleted
Name Spaces
# Example of different namespaces
x = 10 # Global namespace
def my_function():
x = 20 # Local namespace
print("Inside function:", x)
my_function()
print("Outside function:", x)
Python Objects
x = 10
y = "Python"
print(type(x)) # Output: <class 'int'>
print(type(y)) # Output: <class 'str'>
Data types
Integer Programs:
#Addition
a = 12
b=8
result = a + b
print("Addition:", result) # 20
#Division
a = 17
b=4
div = a // b
mod = a % b
print("Division:", div) # 4
print("Modulus:", mod) # 1
#EXponentiation
a=3
b=4
result = a ** b
print("Exponentiation:", result) # 81
#Subtraction
x = 100
y = 35
result = x - y
print("Subtraction:", result) # 65
#MUltiplication
p=7
q=6
product = p * q
print("Multiplication:", product) # 42
Float Programs:
#addition
x = 10.5
y = 2.3
result = x + y
print("Sum:", result) # 12.8
#Division
a = 20.0
b = 3.0
result = a / b
print("Division:", result) # 6.666666666666667
#Square root using exponent
num = 16.0
sqrt = num ** 0.5
print("Square Root:", sqrt) # 4.0
#Multiplying two floats
a = 4.5
b = 3.2
product = a * b
print("Product:", product) # 14.4
#Subtracting floats
x = 10.7
y = 5.3
result = x - y
print("Subtraction:", result) # 5.4
String Programs:
#Concatenation
first = "Hello"
second = "World"
result = first + " " + second
print(result) # Hello World
#String repetition
text = "Python"
result = text * 3
print(result) # PythonPythonPython
#Length of a string
text = "Machine Learning"
length = len(text)
print("Length of string:", length) # 16
#Slicing a string
text = "Data Science"
slice = text[0:4]
print("Sliced string:", slice) # Data
#Converting to uppercase
text = "hello"
result = text.upper()
print("Uppercase:", result) # HELLO
List Programs:
#Creating a list and accessing elements
my_list = [1, 2, 3, 4, 5]
first = my_list[0]
print("First element:", first) # 1
#Appending an element to a list
my_list = [10, 20, 30]
my_list.append(40)
print("Updated List:", my_list) # [10, 20, 30, 40]
#Multiplying list elements
my_list = [1, 2, 3]
result = my_list * 2
print("Repeated List:", result) # [1, 2, 3, 1, 2, 3]
#Length of a list
my_list = [10, 20, 30, 40]
length = len(my_list)
print("Length of list:", length) # 4
Tuple Programs:
#Creating a tuple and accessing elements
my_tuple = (1, 2, 3, 4)
first = my_tuple[0]
print("First element:", first) # 1
#Concatenating two tuples
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
result = tuple1 + tuple2
print("Concatenated Tuple:", result) # (1, 2, 3, 4, 5, 6)
#Tuple slicing
my_tuple = (10, 20, 30, 40)
slice = my_tuple[1:3]
print("Sliced Tuple:", slice) # (20, 30)
#Length of a tuple
my_tuple = (5, 10, 15)
length = len(my_tuple)
print("Length of tuple:", length) # 3
#Accessing last element
my_tuple = (100, 200, 300)
last = my_tuple[-1]
print("Last element:", last) # 300
Set Programs:
# Adding an element to a set
my_set = {1, 2, 3}
my_set.add(4)
print("Set after adding:", my_set) # {1, 2, 3, 4}
#Removing an element from a set
my_set = {1, 2, 3, 4}
my_set.remove(2)
print("Set after removing:", my_set) # {1, 3, 4}
#Union of two sets
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
print("Union:", union_set) # {1, 2, 3, 4, 5}
#Intersection of two sets
set1 = {1, 2, 3}
set2 = {2, 3, 4}
intersection = set1.intersection(set2)
print("Intersection:", intersection) # {2, 3}
#Set difference
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5}
difference = set1.difference(set2)
print("Difference:", difference) # {1, 2}
Dictionary Programs:
#Creating a dictionary and accessing a value
my_dict = {"name": "John", "age": 25}
name = my_dict["name"]
print("Name:", name) # John
#Adding a new key-value pair
my_dict = {"name": "Alice", "age": 30}
my_dict["city"] = "New York"
print("Updated Dictionary:", my_dict) # {'name': 'Alice', 'age': 30,
'city': 'New York'}
#Updating a value
my_dict = {"name": "Bob", "age": 22}
my_dict["age"] = 23
print("Updated Age:", my_dict["age"]) # 23
#Accessing dictionary keys
my_dict = {"name": "Sam", "age": 29, "city": "Boston"}
keys = my_dict.keys()
print("Keys:", keys) # dict_keys(['name', 'age', 'city'])
#Accessing dictionary values
my_dict = {"name": "Eva", "age": 35, "city": "Chicago"}
values = my_dict.values()
print("Values:", values) # dict_values(['Eva', 35, 'Chicago'])