fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
# Output:
# apple
# banana
# cherry
colors = ("red", "green", "blue")
for color in colors:
print(color)
# Output:
# red
# green
# blue
for char in "hello":
print(char)
# Output:
# h
# e
# l
# l
# o
person = {"name": "John", "age": 30, "city": "New York"}
for key in person:
print(key, person[key])
# Output:
# name John
# age 30
# city New York
def my_function(*args):
for arg in args:
print(arg)
my_function("apple", "banana", "cherry")
# Output:
# apple
# banana
# cherry
def my_function(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
my_function(name="Alice", age=30, city="New York")
# Output:
# name: Alice
# age: 30
# city: New York
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1="Emil", child2="Tobias", child3="Linus")
# Output:
# The youngest child is Linus
Example of Default Parameter Value
def my_function(country="Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
# Output:
# I am from Sweden
# I am from India
# I am from Norway
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus")
# Output:
# The youngest child is Linus
def my_function(*args):
for arg in args:
print(arg)
my_function("apple", "banana", "cherry")
# Output:
# apple
# banana
# cherry
def my_function(**kid):
print("His last name is " + kid["lname"])
my_function(fname="Tobias", lname="Refsnes")
# Output:
# His last name is Refsnes
def my_function(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
my_function(name="Alice", age=30, city="New York")
# Output:
# name: Alice
# age: 30
# city: New York
def print_student_info(**info):
for key, value in info.items():
print(f"{key}: {value}")
print_student_info(name="John", age=18, grade="A")
# Output:
# name: John
# age: 18
# grade: A
class BankAccount:
def __init__(self, account_number, owner, balance=0):
self.account_number = account_number
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
print(f"Deposited {amount}. New balance is {self.balance}.")
def withdraw(self, amount):
if amount > self.balance:
print("Insufficient funds!")
else:
self.balance -= amount
print(f"Withdrew {amount}. New balance is {self.balance}.")
def display_account(self):
print(f"Account Number: {self.account_number}, Owner: {self.owner}, Balance: {self.balance}")
# Create instances of the BankAccount class
acc1 = BankAccount("123456", "Alice")
acc2 = BankAccount("789012", "Bob", 500)
# Access attributes and methods
print(acc1.balance) # Output: 0
print(acc2.owner) # Output: Bob
acc1.deposit(100) # Output: Deposited 100. New balance is 100.
acc2.withdraw(200) # Output: Withdrew 200. New balance is 300.
acc1.display_account() # Output: Account Number: 123456, Owner: Alice, Balance: 100
acc2.display_account() # Output: Account Number: 789012, Owner: Bob, Balance: 300
Example of Inheritance in Python
# Base class or Parent class
class Person:
def __init__(self, firstName, lastName):
self.firstName = firstName
self.lastName = lastName
def printFullName(self):
print(self.firstName + ' ' + self.lastName)
# Derived class or Child class
class Student(Person):
def __init__(self, firstName, lastName, studentID):
super().__init__(firstName, lastName) # Calling the constructor of the Parent class
self.studentID = studentID
def printStudentID(self):
print(f"Student ID: {self.studentID}")
# Creating an object of the Base class
personObj = Person("John", "Doe")
personObj.printFullName() # Output: John Doe
# Creating an object of the Derived class
studentObj = Student("Jane", "Doe", "S12345")
studentObj.printFullName() # Output: Jane Doe
studentObj.printStudentID() # Output: Student ID: S12345
Multiple Inheritance
# Base class 1
class Person:
def __init__(self, firstName, lastName):
self.firstName = firstName
self.lastName = lastName
def printFullName(self):
print(self.firstName + ' ' + self.lastName)
# Base class 2
class Employee:
def __init__(self, employeeID):
self.employeeID = employeeID
def printEmployeeID(self):
print(f"Employee ID: {self.employeeID}")
# Derived class inheriting from both Person and Employee
class Manager(Person, Employee):
def __init__(self, firstName, lastName, employeeID, department):
Person.__init__(self, firstName, lastName)
Employee.__init__(self, employeeID)
self.department = department
def printDetails(self):
self.printFullName()
self.printEmployeeID()
print(f"Department: {self.department}")
# Creating an object of the derived class
managerObj = Manager("Alice", "Smith", "E6789", "Sales")
managerObj.printDetails()
# Output:
# Alice Smith
# Employee ID: E6789
# Department: Sales
Method Overriding
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def speak(self):
print("Dog barks")
# Creating objects of both classes
animalObj = Animal()
dogObj = Dog()
animalObj.speak() # Output: Animal speaks
dogObj.speak() # Output: Dog barks
Using super() to call the parent class methods
You can use super() to call the parent class methods and constructors.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} makes a sound")
class Cat(Animal):
def __init__(self, name, age):
super().__init__(name) # Call the constructor of the Animal class
self.age = age
def speak(self):
super().speak() # Call the speak method of the Animal class
print(f"{self.name} meows and is {self.age} years old")
# Creating an object of the derived class
catObj = Cat("Whiskers", 3)
catObj.speak()
# Output:
# Whiskers makes a sound
# Whiskers meows and is 3 years old
Class Variables and Instance Variables
Class variables are shared across all instances of the class, whereas instance variables are unique to each instance.
class Car:
wheels = 4 # Class variable
def __init__(self, color, model):
self.color = color # Instance variable
self.model = model # Instance variable
# Creating objects of the Car class
car1 = Car("Red", "Sedan")
car2 = Car("Blue", "SUV")
print(f"Car1: {car1.color}, {car1.model}, Wheels: {car1.wheels}")
print(f"Car2: {car2.color}, {car2.model}, Wheels: {car2.wheels}")
# Output:
# Car1: Red, Sedan, Wheels: 4
# Car2: Blue, SUV, Wheels: 4
# Modifying class variable
Car.wheels = 5
print(f"Car1: {car1.color}, {car1.model}, Wheels: {car1.wheels}")
print(f"Car2: {car2.color}, {car2.model}, Wheels: {car2.wheels}")
# Output:
# Car1: Red, Sedan, Wheels: 5
# Car2: Blue, SUV, Wheels: 5
Class Methods and Static Methods
Class methods and static methods can be defined using @classmethod and @staticmethod decorators.
class MathOperations:
@staticmethod
def add(x, y):
return x + y
@classmethod
def multiply(cls, x, y):
return x * y
Using static method
print(MathOperations.add(5, 3)) # Output: 8
Using class method
print(MathOperations.multiply(5, 3)) # Output: 15
# Initial sets
fruits = {"apple", "banana", "cherry"}
colors = {"red", "blue", "green"}
numbers = {1, 2, 3, 4, 5}
more_numbers = {4, 5, 6, 7, 8}
primes = {2, 3, 5, 7}
# add()
fruits.add("orange")
print("After add():", fruits)
# Output: {'orange', 'cherry', 'apple', 'banana'}
# clear()
colors.clear()
print("After clear():", colors)
# Output: set()
# copy()
fruits_copy = fruits.copy()
print("After copy():", fruits_copy)
# Output: {'orange', 'cherry', 'apple', 'banana'}
# difference()
diff = numbers.difference(more_numbers)
print("After difference():", diff)
# Output: {1, 2, 3}
# difference_update()
numbers.difference_update(more_numbers)
print("After difference_update():", numbers)
# Output: {1, 2, 3}
# discard()
fruits.discard("banana")
print("After discard():", fruits)
# Output: {'orange', 'cherry', 'apple'}
# intersection()
inter = fruits.intersection({"apple", "mango"})
print("After intersection():", inter)
# Output: {'apple'}
# intersection_update()
fruits.intersection_update({"apple", "mango"})
print("After intersection_update():", fruits)
# Output: {'apple'}
# isdisjoint()
is_disjoint = numbers.isdisjoint(primes)
print("After isdisjoint():", is_disjoint)
# Output: True
# issubset()
is_subset = {1, 2}.issubset(numbers)
print("After issubset():", is_subset)
# Output: True
# issuperset()
is_superset = numbers.issuperset({1, 2})
print("After issuperset():", is_superset)
# Output: True
# pop()
popped_element = fruits_copy.pop()
print("After pop():", popped_element, fruits_copy)
# Output: apple {'orange', 'cherry', 'banana'} (popped element may vary)
# remove()
fruits_copy.add("banana") # Re-adding for demonstration
fruits_copy.remove("banana")
print("After remove():", fruits_copy)
# Output: {'orange', 'cherry'}
# symmetric_difference()
sym_diff = {1, 2, 3}.symmetric_difference({3, 4, 5})
print("After symmetric_difference():", sym_diff)
# Output: {1, 2, 4, 5}
# symmetric_difference_update()
a = {1, 2, 3}
b = {3, 4, 5}
a.symmetric_difference_update(b)
print("After symmetric_difference_update():", a)
# Output: {1, 2, 4, 5}
# union()
union_set = {1, 2, 3}.union({3, 4, 5})
print("After union():", union_set)
# Output: {1, 2, 3, 4, 5}
# update()
update_set = {1, 2, 3}
update_set.update({3, 4, 5})
print("After update():", update_set)
# Output: {1, 2, 3, 4, 5}
Dictionary Methods
clear()
Description: Removes all elements from the dictionary.
Example:
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
thisdict.clear()
print(thisdict)
# Output: {}
copy()
Description: Returns a copy of the dictionary.
Example:
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
mydict = thisdict.copy()
print(mydict)
# Output: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
fromkeys()
Description: Returns a dictionary with the specified keys and value.
Example:
keys = ('key1', 'key2', 'key3')
value = 0
newdict = dict.fromkeys(keys, value)
print(newdict)
# Output: {'key1': 0, 'key2': 0, 'key3': 0}
get()
Description: Returns the value of the specified key.
Example:
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
model = thisdict.get("model")
print(model)
# Output: Mustang
items()
Description: Returns a list containing a tuple for each key-value pair.
Example:
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
items = thisdict.items()
print(items)
# Output: dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])
keys()
Description: Returns a list containing the dictionary's keys.
Example:
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
keys = thisdict.keys()
print(keys)
# Output: dict_keys(['brand', 'model', 'year'])
pop()
Description: Removes the element with the specified key.
Example:
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
thisdict.pop("model")
print(thisdict)
# Output: {'brand': 'Ford', 'year': 1964}
popitem()
Description: Removes the last inserted key-value pair.
Example:
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
thisdict.popitem()
print(thisdict)
# Output: {'brand': 'Ford', 'model': 'Mustang'}
setdefault()
Description: Returns the value of the specified key. If the key does not exist, inserts the key with the specified value.
Example:
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
color = thisdict.setdefault("color", "red")
print(thisdict)
# Output: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}
update()
Description: Updates the dictionary with the specified key-value pairs.
Example:
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
thisdict.update({"color": "red"})
print(thisdict)
# Output: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}
values()
Description: Returns a list of all the values in the dictionary.
Example:
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
values = thisdict.values()
print(values)
# Output: dict_values(['Ford', 'Mustang', 1964])
nion of two lists means combining the elements of both lists, excluding any duplicates. You can use the union() method or the | operator.
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
# Using set.union() method
union_result = list(set(list1).union(set(list2)))
print("Union using union():", union_result)
# Using | operator
union_result_operator = list(set(list1) | set(list2))
print("Union using | operator:", union_result_operator)
Intersection
Intersection of two lists refers to elements that are common to both lists. You can use the intersection() method or the & operator.
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
# Using set.intersection() method
intersection_result = list(set(list1).intersection(set(list2)))
print("Intersection using intersection():", intersection_result)
# Using & operator
intersection_result_operator = list(set(list1) & set(list2))
print("Intersection using & operator:", intersection_result_operator)
Difference
The difference between two lists is the set of elements that are only in the first list but not in the second. Use the difference() method or the - operator.
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
# Using set.difference() method
difference_result = list(set(list1).difference(set(list2)))
print("Difference using difference():", difference_result)
# Using - operator
difference_result_operator = list(set(list1) - set(list2))
print("Difference using - operator:", difference_result_operator)
Symmetric Difference
Symmetric difference between two lists refers to elements in either of the lists but not in both. Use the symmetric_difference() method or the ^ operator.
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
# Using set.symmetric_difference() method
sym_diff_result = list(set(list1).symmetric_difference(set(list2)))
print("Symmetric Difference using symmetric_difference():", sym_diff_result)
# Using ^ operator
sym_diff_result_operator = list(set(list1) ^ set(list2))
print("Symmetric Difference using ^ operator:", sym_diff_result_operator)
These operations convert lists to sets temporarily to perform the operations since sets inherently do not allow duplicate elements and support these mathematical set operations. After performing the operation, the result is converted back to a list.
Creating a Module
A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py added.
Let's create a module named mymodule.py:
# mymodule.py
def greeting(name):
print("Hello, " + name)
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Using the Module
You can now use the module you've created by importing it into your script.
# main.py
import mymodule
mymodule.greeting("Jonathan")
a = mymodule.person1["age"]
print(a)
Datetime
import datetime
# Create a date object
x = datetime.datetime.now()
# Print the date object
print(x)
# Access and print individual attributes
print("Year:", x.year)
print("Month:", x.month)
print("Day:", x.day)
print("Hour:", x.hour)
print("Minute:", x.minute)
print("Second:", x.second)
# Format the date and print it
formatted_date = x.strftime("%Y-%m-%d %H:%M:%S")
print("Formatted date and time:", formatted_date)
JSON in Python
import json
# JSON string
json_string = '{"name": "John", "age": 30, "city": "New York"}'
# Convert JSON string to Python dictionary
python_dict = json.loads(json_string)
print("Converted JSON to Python dictionary:")
print(python_dict)
# Access dictionary values
print("\nAccessing values from Python dictionary:")
print(f"Name: {python_dict['name']}")
print(f"Age: {python_dict['age']}")
print(f"City: {python_dict['city']}")
# Convert Python dictionary to JSON string
json_string = json.dumps(python_dict)
print("\nConverted Python dictionary to JSON string:")
print(json_string)
# Convert Python dictionary to formatted JSON string
json_string = json.dumps(python_dict, indent=4, sort_keys=True)
print("\nFormatted JSON string:")
print(json_string)
Using map() Function in Python
The map() function in Python is used to apply a function to all the items in an input list. Here are some examples to demonstrate its usage:
Basic Example
Example function to square a number
def square(num):
return num ** 2
# List of numbers
numbers = [1, 2, 3, 4, 5]
# Applying map() function
squared_numbers = map(square, numbers)
# Converting map object to list
squared_numbers_list = list(squared_numbers)
print(squared_numbers_list)
# Output: [1, 4, 9, 16, 25]
# List of numbers
numbers = [1, 2, 3, 4, 5]
# Using lambda function to square the numbers
squared_numbers = map(lambda x: x ** 2, numbers)
# Converting map object to list
squared_numbers_list = list(squared_numbers)
print(squared_numbers_list)
# Output: [1, 4, 9, 16, 25]
# Define a function that returns the length of a string
def myfunc(n):
return len(n)
# Apply the function to each item in the tuple using map()
x = map(myfunc, ('apple', 'banana', 'cherry'))
# Convert the map object to a list and print it
print(list(x))
# Output: [5, 6, 6]
# Define a function that adds two numbers (or concatenates two strings)
def myfunc(a, b):
return a + b
# Apply the function to each pair of items in the tuples using map()
x = map(myfunc, ('apple', 'banana', 'cherry'), ('orange', 'lemon', 'pineapple'))
# Convert the map object to a list and print it
print(list(x))
# Output: ['appleorange', 'bananalemon', 'cherrypineapple']
uppercase_strings = map(to_uppercase, strings)
# Define a function that adds two numbers
def add(a, b):
return a + b
# Two lists of numbers
list1 = [1, 2, 3]
list2 = [4, 5, 6]
# Apply the function to each pair of items in the lists using map()
summed_list = map(add, list1, list2)
# Convert the map object to a list and print it
print(list(summed_list))
# Output: [5, 7, 9]
Summary
print each element of list, tuple.
print each char of string
print key and value of dictionary
print each element of function using args.
print particular element of function using args.
print each key and value of function using **kwargs.
print particular value of dictionary using function using **kwargs.
- program defines a BankAccount class to create bank account instances with an account number, owner, and balance. It provides methods to deposit and withdraw funds and display account details.
2.This program defines a base class Person
and a derived class Student
to represent
individuals and students respectively. The Person
class includes attributes for
first and last names and a method to print the full name. The Student
class inherits
from Person
and adds a student ID attribute and a method to print the student ID
Cheatsheet
for key in person:
print(key, person[key])
def my_function(*args):
for arg in args:
def my_function(*kids):
print("The youngest child is " + kids[2])
def my_function(**kwargs):
for key, value in kwargs.items():
def my_function(**kid):
print("His last name is " + kid["lname"])
Top comments (0)