Complete python course
What is python?
Python is a high-level, interpreted programming language that is widely used
for various purposes such as web development, scientific computing, data
analysis, artificial intelligence, and more. Created in the late 1980s and
released in 1991, by Guido van Rossum, Python is known for its simplicity,
readability, implicitly typed language, and ease of use, making it an ideal
language for beginners and experts alike.
HOW TO SAVE FILE?
By using (.py) in the end of file name.
HOW TO PRINT TEXT?
By using
print(“Hello world”)
print(‘Hello world’)
print(“’Hello world”’)
Note: Here is no need of any semicolon in python.
HOW TO USE COMMENT?
# for single line
“””Multiple line “””
1
DATA TYPES
TYPES OF NUMBER?
1. Int: - Used to define integer numbers.
2. Float: - used to define float/decimal value.
3. Complex: - number that can be expressed in the form: a + bi.
Other types:
Boolean: Boolean is a data type that can have one of two possible values:
(True and False).
Note: T of True and F of False will be capital.
HOW TO FIND DATA TYPES?
By using (Type) keyword with variable name.
2
What is different between implicit and explicit typed language?
Implicit Typed Language: No explicit type declaration is required.
Explicit Typed Language: Explicit type declaration is required before
using a variable.
WHAT IS CASTING?
Casting is the process of converting a value from one data type to another
data type.
3
WHAT IS RANDOM?
A value or event that is unpredictable, lacks a regular pattern.
WHAT IS STRING?
String is a sequence of characters, such as letters, numbers, or
symbols, enclosed in quotes.
Strings are immutable, meaning you can't change them after they're
created.
Strings can be enclosed in single quotes (') or double quotes (") or
Triple quotes (“’ “’).
SLICE STRING
Slice refers to a subset of characters or elements from a larger string.
4
WHAT IS MULTILINE STRING?
Multiline string is a string that spans multiple lines.
HOW TO FIND LENGTH OF STRING?
By using Len (variable) keyword.
How to use slice in string?
HOW TO TAKE INPUT NAME AND SHOW FIRST AND LAST CHAR OF NAME
5
SLICING BY PUTTING NEGATIVE INDEX
STRING METHOD (UPPER, LOWER, STRIP, SLICE, REPLACE, SPLIT)
Bool in python?
6
WHAT IS IDENTATION?
Indentation refers to the spaces or tabs used to indent a block of code.
HOW TO INTRECT WITH EACH CHARACTER?
HOW TO CHECK WORD IN STRING?
WHAT IS ESCAPE SEQUENCE?
Escape sequence is a special sequence of characters that represents a
character or action that cannot be represented by a single character.
7
HOW TO TAKE CHARACTER, NUMBER, AND DECIMAL VALUE IN INPUT?
To check if a certain phrase or character is present in a string, we can use
the keyword in.
CHECK IF NOT:
HOE TO SLICE TEXT OR WORD IN STRING/SENTENCE?
F-STRING:
8
They allow you to embed expressions inside string literals, using the {}
syntax.
UPPERCASE, LOWERCASE, SWIPCASE, TITLE, AND SENTENCE TYPE METHOD IN
STRING:
SIMPLE CALCULATOR:
9
HOW TO CREATE RANDOM PASSWORD WITH GIVEN RANGE?
SPLIT ():
The split () function in Python is a string method that splits a string into a list
of substrings based on a specified separator.
Example:
Write a code which is used to take address and then split it into words,
then print word and their length correctly.
What is the purpose of the format () method in Python strings?
What is List?
10
List is collection of multiple data of types of data
List is ordered and changeable.
Allow duplicate values
It is creating by using square bracket.
ORDERED AND ALLOW DUPLICATE VALUE:
HOW TO CHECK VALUE THROUGH INDEX.
APPEND AND INSERT:
(Append is used to add data in end in list. Whenever
insert is used to add data at specific index list. Insert
(Startindex. value)
11
LIST CONSTRUCTOR
List constructor is a way to create a new list from an
existing iterable, such as another list.
RANGE OF INDEXS:
By default start and end index:
12
Checking value in list:
How to change index value:
HOW TO REMOVE VALUE:
Pop () (USED TO REMOVE SPECIFIC INDEX)
13
CLEAR THE COMPLETE LIST:
Loop
through a list
Range of
Indexes
Check if Item Exists
Change Item Value
14
Change a Range of Item Values
Insert Items
How to clear the list?
Loop Through the Index Numbers
15
• List comprehension offers a shorter syntax when you want to
create a new list based on the values of an existing list .
APPEND AND EXTEND
How to find sum of number (sum)
How to find minimum/lowest or maximum /highest value is list
16
Print(bool(0))#False
Tuples:
- Immutable: Tuples cannot be changed after they are created.
- Ordered: Tuples maintain the order in which elements were added.
- Indexed: Tuples can be indexed, allowing access to specific
elements.
- Defined using parentheses: my_tuple = (1, 2, 3)
- Can contain duplicate values: my_tuple = (1, 2, 2, 3)
Since tuples are immutable, they do not have a built-in
append(), or insert() method.
- Supports slicing: my_tuple[1:3]
-Data type: - A tuple can contain different data types:
Sets:
- Mutable: Sets can be changed after they are created.
- Unordered: Sets do not maintain the order in which elements were
added.
- Unindexed: Sets cannot be indexed, and elements cannot be
accessed by index.
17
-Data type:- A tuple can contain different data types:
- Defined using curly brackets: my_set = {1, 2, 3}
- Cannot contain duplicate values: my_set = {1, 2, 2, 3}
becomes my_set = {1, 2, 3}
-cannot be referred to by index or key.
- Supports union, intersection, and difference operations: my_set1 &
my_set2, my_set1 | my_set2, etc.
Note: you can remove items and add new items.
Duplicate value in set and tuple:
SET
TUPLE
Length function
18
Create Tuple with One Item
To create a tuple with only one item, you have to add a comma
after the item, otherwise
Python will not recognize it as a tuple.
#NOT a tuple:-
this_tuple = ("apple")
print(type(this_tuple))
#b/c here is not comma .
THE LIST AND SET CONSTRUCTOR:-
Access Sets and Tuple Items
19
How to accessing set: - you can loop through the set items using a
for loop, or ask if a specified value is presenting a set, by using the in
keyword.
Accessing tuple:-
ADD ITEM IN SET:
20
Note:- We cannot leave empty set otherwise it show
type dictionary.
thisset= {} print(type(thisset) #display <class ‘Dict’>
my_set = set() #you have to explicit define it is set.
print(my_set) # Output: set()
REMOVE ITEM FROM SET AND TUPLE:
SET: To remove an item in a set, use the remove (), or the
discard () method.
Note: - If the item to remove does not exist, remove () will
raise an error.
- If the item to remove does not exist, discard () will NOT
raise an error.
21
TUPLE: Tuples are unchangeable, so you cannot
remove items from it, but you can use the same
workaround as we used for changing and
adding tuple items:
HOW TO DELETE TUPLE
thistuple=("akash","faheem")
del thistuple
print(thistuple)
LOOP ITEM IN TUPLE AND SET
22
Loop Through the Index Numbers
Using a While Loop
23
Python – Join Tuples and Sets
Sets in Python are unordered collections of unique elements, and they don't support
concatenation using +. Instead, you can use the union () method or the | operator
to combine two sets.
There are several ways to join two or more sets in Python.
• The union () and update () methods joins all items from both sets.
• The intersection () method keeps ONLY the duplicates.
• The difference () method keeps the items from the first set that are not in the
other set(s).
• The symmetric difference () method keeps all items EXCEPT the duplicates.
24
Python – Multiple Join
25
Python set Method
PYTHON-TUPLE PYTHON
Python has two built-in methods that you can use on tuples.
Count () x = [Link] (“apple”) Returns the number of times a specified value
occurs in a tuple
Index () x = [Link] (“cherry”) Searches the tuple for a specified value and returns the position
of where it was found.
You have a dataset of transaction types, and you
want to count the frequency of each type.
DICTIONARY
# Dictionaries are used to store data values in
# Key: value pairs.
# • A dictionary is a collection which is ordered,
26
# Changeable and do not allow duplicates.
# • Note: As of Python version 3.7, dictionaries
# are ordered. In Python 3.6 and earlier,
# Dictionaries are unordered.
Dictionary constructor
27
Get () Method
Get Keys and values
Get Items
#The items () method will return each item in a
dictionary, as
# Tuples in a list.
28
CHECK IF KEY IS EXIST
Change Dictionary Items
UPDATE DICTIONARY
The update() method will update the dictionary with the items from
the given argument.
29
Add Dictionary Items
Adding an item to the dictionary is done by using a new index key and assigning a
value to it:
Remove Dictionary Items
The pop() method removes the item with the specified key name:
POP ITEM METHOD
The popitem() method removes the last inserted item (in versions before 3.7, a
random item is removed instead):
30
Del keyword
The del keyword removes the item with the specified key name:
del thisdict["model"]
Note: - we can delete dictionary.
Note: - we can clear full dictionary.
LOOP THROUGH DICTIONARY
You can loop through a dictionary by using a for loop.
• When looping through a dictionary, the return value are the keys of the dictionary,
but there are methods to return the values as well.
31
VALUE METHOD
You can also use the values () method to return values of a
dictionary:
32
KEY METHOD
You can use the keys() method to return the keys of a
dictionary:
Loop through both keys and values, by using the items() method:
COPY A DICTIONARY:
You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2
will only be a reference to dict1, and changes made in dict1 will
automatically also be made in dict2.
• There are ways to make a copy, one way is to use the built-in Dictionary
method copy().
33
NESTED DICTIONARY
HOW TO ACCESS VALUE AND KEY IN NESTED DICTIONARY
34
HOW TO ACCESS VALUE AND KEY IN NESTED DICTIONARY
using loop
DICTIONARY METHOD
Method Description
clear() Removes all the elements from the
dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys
and value
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key
value pair
keys() Returns a list containing the dictionary's
keys
pop() Removes the element with the specified key
35
popitem() Removes the last inserted key-value pair
setdefault() Returns the value of the specified key. If the
key does not exist: insert the key, with the
specified value
update() Updates the dictionary with the specified key-
value pairs
values() Returns a list of all the values in the dictionary
CONDITIONS
IF STATEMENT:
An "if statement" is written by using the if keyword.
36
ELIF:
The elif keyword is Python's way of saying "if the previous conditions were
not true, then try this condition".
IF-ELSE:
SHORT HAND IF
If you have only one statement to execute, you can put it on the
same line as the if statement.
SHORT HAND IF……..ELSE
37
AND KEYWORD
The and keyword is a logical operator, and is used to combine conditional
statements:
OR KEYWORD
The or keyword is a logical operator, and is used to combine conditional
statements:
• Test if a is greater than b, OR if a is greater than c:
NOT KEYWORD
The not keyword is a logical operator
NESTED IF STATEMENT:
38
The pass statement:
The pass statement in Python is a placeholder when a statement is required
syntactically, but no execution of code is necessary.
LOOPS:
While loop
With the while loop we can execute a set of statements as long as a
condition is true.
39
The Break statement
With the break statement we can stop the loop even if the while condition is
true:
The Continue statement
With the continue statement we can stop the current iteration, and continue
with the next:
The Else Statement
With the else statement we can run a block of code once when the condition
no longer is true:
40
FUNCTION
A function is a block of code which only runs when it is called.
• You can pass data, known as parameters, into a function.
41
• A function can return data as a result.
In Python a function is defined using the def keyword:
• To call a function, use the function name followed by parenthesis:
What is Arguments?
Information can be passed into functions as arguments.
Arguments Vs Parameter
• The terms parameter and argument can be used for the same thing:
information that are passed into a function.
• From a function's perspective:
• A parameter is the variable listed inside the parentheses in the function
definition.
• An argument is the value that is sent to the function when it is called.
What is class?
Class is a template for creating objects. It defines a set of attributes (data)
and methods (functions) that can be used to manipulate and interact with
objects created from the class.
42
def __init__(self):
The __init__ function in Python is a special method that serves as a
constructor for a class.
class myclass:
def __init__(self,name,rollno):
[Link]=name
self.roll_no=rollno
p1 = myclass("John", 36)
print([Link])
print(p1.roll_no)
def __str__()function
The __str__() function controls what should be returned when the class object is represented as
a string. • If the __str__() function is not set, the string representation of the object is returned:
What is Inheritance?
Inheritance allows us to define a class that inherits all the methods and properties from another class. •
Parent class is the class being inherited from, also called base class. • Child class is the class that inherits
from another class, also called derived class.
43
class Person:
def __init__(self, fname, lname):
[Link] = fname
[Link] = lname
def printname(self):
print([Link], [Link])
class Student(Person):
def __init__(self, fname, lname):
#Parent Class __init__() functin
Person.__init__(self, fname, lname)
x = Student(”Ahmed", ”Ali")
[Link]()
All Lab_Task
#LAB 2
1. Calculate Area of a Rectangle: Write a program to calculate the area of a rectangle given
its length and width.
44
2. Convert Kilometers to Miles: Write a program to convert distance from kilometers to
miles.
3. Calculate Simple Interest: Write a program to calculate simple interest given principal
amount, rate, and time.
4. Calculate Body Mass Index (BMI): Write a program to calculate BMI given weight and
height.
5. Convert Seconds into Hours, Minutes, and Seconds: Write a program to convert time from
seconds to hours, minutes, and seconds.
6. Compute the Perimeter of a Circle: Write a program to calculate the perimeter of a circle
given its radius.
7. Swap Two Numbers Without a Temporary Variable: Write a program to swap two numbers
without using a temporary variable.
8. Calculate Discounted Price: Write a program to calculate the final price after applying a
discount.
9. Calculate Average Marks: Write a program to calculate the average marks of a student
given marks in five subjects.
10. Calculate Travel Time: Write a program to calculate the time required to travel a certain
distance at a given speed.
11. Calculate Monthly EMI for a Loan: Write a program to calculate the monthly EMI for a
loan given principal amount, interest rate, and loan duration.
12. Currency Converter (USD to INR): Write a program to convert USD to INR given an
exchange rate.
13. Grocery Bill Calculator: Write a program to calculate the total bill amount with a 5%
discount if the total exceeds $100.
14. Car Fuel Consumption Calculator: Write a program to calculate fuel consumption in km/l
given distance traveled and fuel used.
15. Water Bill Calculator: Write a program to calculate the water bill based on usage in liters.
16. Tip Calculator for Restaurants: Write a program to calculate the tip amount and total
amount to pay given a bill amount and tip percentage.
17. Internet Data Cost Calculator: Write a program to calculate the cost of an internet plan
based on data usage in GB.
18. Calories Burned Calculator: Write a program to calculate calories burned given weight,
exercise duration, and MET value.
19. Speed Fine Calculator: Write a program to calculate a speeding fine based on a given
speed limit and actual speed.
20. Internet Download Time Calculator: Write a program to calculate the time required to
download a file given file size and internet speed.
45
LAB#03
1. Calculate Average Daily Temperature: Calculate average temperature for a week given a
list of temperatures.
2. Analyze Monthly Sales Data: Find total, average, highest, and lowest sales from a list of
daily sales.
3. Filter Out Students Who Scored Above 80%: Extract students with scores above 80% from
a list of scores.
4. Stock Price Analysis: Find highest, lowest, and average stock prices from a list of prices.
5. Most Frequent Customer Orders: Find the most frequently ordered item from a list of
orders.
6. Filtering Products Based on Price Range: Extract products with prices between $50 and
$100 from a list of prices.
7. Extracting Even and Odd Numbers: Separate even and odd jersey numbers from a list of
numbers.
8. Count Occurrences of Words in a List: Count occurrences of each word in a list of words.
9. Employee Performance Rankings: Sort scores and extract top 5 performers (use sort() or
sorted()).
10. Customer Order History Management: Remove canceled orders and count product
occurrences (use remove() and count()).
11. Product Inventory Updates: Update inventory list by appending new quantities and
removing out-of-stock items (use append() and remove()).
12. Unique Event Attendees: Remove duplicates and sort names alphabetically (use set and
sort()).
13. Course Registration List Update: Add new registrations and slice list for workshop
invitation (use append() and list slicing).
14. Daily Expense Tracker: Insert missing expense and compute total expense (use insert()
and sum()).
15. Social Media Post Likes Analysis: Sort list and find post with highest likes (use sort() or
max()).
16. Survey Response Frequency: Count occurrences of each response (use count() or
dictionary).
17. Library Book Collection Management: Remove duplicates and add new titles (use set and
insert()).
18. Real Estate Listings Filter: Filter properties by price range and sort (use list
comprehension and sort()).
#LAB #04
46
1. Unique Voters List using Sets: Find unique voter names from a list with duplicates (use
set).
2. Store Product Prices with Dictionary: Store product prices and display price of a product
given by user (use dictionary).
3. Count Occurrence of Words in Sentence: Count word occurrences in a sentence (split
string and use dictionary).
4. Tuple for Geolocation Coordinates: Store coordinates (latitude, longitude) of tourist
attractions (use tuple).
5. Remove Duplicates from Shopping List: Remove duplicates from shopping list (use set).
6. Inventory System using Dictionary: Update and check stock of each item (use dictionary).
7. Set Operations for Workshop Participants: Find who attended both "Python" and "Data
Science" workshops (use set intersection).
8. Tuple Unpacking for Student Grades: Display students with their scores (use tuple
unpacking).
9. Dictionary of Country-Capital Pairs: Store countries and capitals, return capital for a given
country (use dictionary).
10. Set Membership Checker: Check if username already exists (use set membership).
11. Remove Duplicates from List of Strings: Remove duplicates from list of strings (use set).
12. Convert Tuple to String: Convert tuple to string (use join() method).
13. Find Common Customers: Find customers who visited both branches (use set
intersection).
14. Store Employee Records: Store employee data (use dictionary with tuple values).
15. Remove Duplicate Cities: Create unique list of cities (use set).
16. Daily Temperatures: Store daily temperatures (use tuple).
17. Word Frequency in Article: Count word occurrences (split string and use dictionary).
18. Product Inventory System: Update product quantities (use dictionary).
19. Countries in Asia and Commonwealth: Find countries in both groups (use set
intersection).
20. Monthly Expenses Tracker: Track expenses (use dictionary).
#LAB 5
Q1. Divisible by 7 and Multiples of 5
Write a Python program to find those numbers which are divisible by 7 and multiples of 5,
between 1500 and 2700 (both included).
Hint: Use a loop to iterate through numbers from 1500 to 2700 and check if the number is
divisible by both 7 and 5.
Q2. Number Guessing Game
47
Write a Python program to guess a number between 1 and 9.
Note: User is prompted to enter a guess. If the user guesses wrong then the prompt appears
again until the guess is correct, on successful guess, user will get a "Well guessed!"
message, and the program will exit.
Q3. Construct Pattern (Diamond Pattern)
Write a Python program to construct a diamond pattern using a nested for loop.
Q4. Reverse a Word
Write a Python program that accepts a word from the user and reverses it.
Q5. Count Even and Odd Numbers
Write a Python program to count the number of even and odd numbers in a series of
numbers.
Q6. Fibonacci Series Between 0 and 50
Write a Python program to get the Fibonacci series between 0 and 50.
Note: The Fibonacci Sequence is the series of numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, ... . Every
next number is found by adding up the two numbers before it.
Q7. Password Validity Checker
Write a Python program to check the validity of passwords input by users.
Validation: At least 1 letter between [a-z] and 1 letter between [A-Z]. At least 1 number
between [0-9]. At least 1 character from [$#@]. Minimum length 6 characters. Maximum
length 16 characters.
Q8. Vowel or Consonant Checker
Write a Python program to check whether an alphabet is a vowel or consonant.
Q9. Hotel Room Booking Based on Budget
Ask the user for their budget and suggest a room type based on the amount.
Q10. Student Grade Evaluation
Input marks and determine grade using if-elif-else.
Q11. ATM Cash Withdrawal Simulation
Using if-else and while, simulate an ATM that allows only 3 tries.
Q12. Email Validation from List
Using for, if, and continue, check if all emails contain '@' and '.'.
Q13. Count Vowels in a Sentence
Use a for loop and if to count vowels in a given string.
Q14. Number Guessing Game (Random + While Loop)
Use while, if, and break to create a guessing game.
48
Q15. Electricity Bill Calculator
Use if-elif-else to calculate bill based on units.
Q16. Multiplication Table Generator
Use for loop to generate multiplication table of any number.
Q17. Draw Rectangle Pattern with Stars
Use nested loops to print a rectangular star pattern.
Q18. Prime Number Checker (Using Loop and Flag)
Ask a number and use loop to check if it's a prime number.
And here are the additional lab questions:
Task 1. Library Fine Calculator
A library charges a fine for late book returns. Write a program that asks the number of late
days and calculates the fine or shows a warning.
Task 2. Class Attendance Checker
A student must have at least 75% attendance to sit in the final exam. Ask total number of
classes and classes attended. Print if the student is allowed to sit for the exam or not.
Task 3. Password Authentication System
Create a login system that allows a user to enter their password. They get 3 attempts only. If
they fail all three times, show “Account Locked.”
Task 4. Digital Clock (1 to 12 Format)
Simulate a 12-hour digital clock using a loop. Display the hour and minute for each time
from 1:00 to 12:59.
Task 5. Discount Calculator for Online Shopping
Create a discount calculator that gives discounts based on order amount.
Task 6. Elevator Floor Display
Simulate an elevator moving from Ground floor (G) to 10th floor, skipping the 4th floor
(superstition). Display each floor as the elevator passes it.
Task 7. Bus Ticket Fare Calculator
A bus fare system charges based on age. Ask user for age and print fare.
Task 8. Username Validation
Write a program that asks for a username. It should be at least 6 characters long and must
not contain any spaces. If not, show an error message.
Task 9. Number Pattern Pyramid
Create a pyramid pattern of numbers using loops.
49