16 DAYS Python Course

DAY 1
helloworld1.py
Description
This script prompts the user to enter their first name and surname, then prints a greeting using the provided inputs.
Code and Explanation
print(input("What is your name? ") + " " + input("What is your surname?"))
The script first prompts the user with the message "What is your name?" and collects their input as a string.
It then prompts the user with the message "What is your surname?" and collects their input as a string.
Both inputs are concatenated with a space
" "in between.The concatenated string is printed
Example
What is your name? John
What is your surname? Doe
John Doe
main.py
Description
This script defines a function that prints a personalized greeting message. If the script is run as the main module, it will greet "PyCharm".
Code and Explaination
def print_hi(name):
print(f'Hi, {name}')
if __name__ == '__main__':
print_hi('PyCharm')
Function Definition:
def print_hi(name):defines a function namedprint_hithat takes one argument,name.print(f'Hi, {name}')uses an f-string to format and print the greeting message.
Conditional Execution:
if __name__ == '__main__':checks if the script is being run directly (not imported as a module).print_hi('PyCharm')calls theprint_hifunction with the argument'PyCharm', resulting in the output "Hi, PyCharm".
Example
When run directly:
Hi, PyCharm
When imported and used in another script:
from main import print_hi
print_hi('Alice')
Output:
Hi, Alice
DAY1 project.py
Description
DAY1 project.. This script prompts the user for their favorite color and a common name for a female dog, then prints a creative name for a beer company using the provided inputs.
Code and Explanation
print("The name of your beer company is '" + input("Which color you like ?: ") + " " + input("Lady dog is known by: ") + "'")
The script first prompts the user with "Which color do you like?:" and collects their input as a string.
It then prompts the user with "Lady dog is known by:" and collects their input as a string.
Both inputs are concatenated with a space
" "in between and framed within the string "The name of your beer company is '" and "'".The constructed string is printed.
Example
Which color you like ?: Blue
Lady dog is known by: Bitch
The name of your beer company is 'Blue Bitch'
DAY 2
conversions.py
Description
This script demonstrates how to convert between different numeric types in Python: from float to integer and back to float.
Code and Explanation
pythonCopy codenum1 = 2.1
print(type(num1)) # Output: <class 'float'>
num1is initialized with the value2.1, which is a float.print(type(num1))outputs the type ofnum1, which isfloat.
pythonCopy codenum2 = int(num1)
print(type(num2)) # Output: <class 'int'>
num1is converted to an integer usingint(), and the result is stored innum2.print(type(num2))outputs the type ofnum2, which is nowint.
pythonCopy codenum2 = 10
num1 = float(num2)
print(num1) # Output: 10.0
print(type(num1)) # Output: <class 'float'>
num2is reassigned to10, an integer.num2is then converted to a float and assigned tonum1.print(num1)outputs the float value10.0.print(type(num1))outputs the type ofnum1, which is nowfloat.
formating_strings.py
Description
This script demonstrates string formatting using the format() method to insert variables into strings.
Code and Explanation
x = 10
y = 5
print("My numbers are {} and {}".format(x, y)) # Output: My numbers are 10 and 5
Variables
xandyare set to10and5, respectively.The
printstatement uses theformat()method to insertxandyinto the string at the placeholders{}.The output is
My numbers are 10 and 5.
integers_float.py
Description
This script demonstrates basic arithmetic operations, type conversions, calculating the total bill with tax and tip, and exploring the behavior of the print function and variable types in Python.
Code and Detailed Explanation
age = input("Tell me your age: ")
a = print(age)
print(type(a))
age = input("Tell me your age: "): This line prompts the user to input their age. The input is read as a string and assigned to the variableage.a = print(age): This line prints the value ofageto the console. Theprint()function itself returnsNone, which is then assigned to the variablea.print(type(a)): This line prints the type ofa. Sinceprint()returnsNone, the type ofaisNoneType.
num1 = 10
num2 = 25
num1 = num2
print(num1, num2) # Output: 25 25
num1andnum2are initially set to10and25, respectively.num1is then assigned the value ofnum2, so both become25.print(num1, num2)outputs25 25.
billwt = int(input())
tax = 0.18
tip = 0.05
totaltax = tax * billwt
totaltip = tip * billwt
totalbill = billwt + totaltax + totaltip
print("The Tax is {}".format(totaltax))
print("The Tip is {}".format(totaltip))
print("Total Bill With Tax and Tip is {}".format(totalbill))
The script prompts the user to input the bill weight (
billwt), which is converted to an integer.taxandtipare set to0.18and0.05, respectively.totaltaxis calculated astax * billwt.totaltipis calculated astip * billwt.totalbillis the sum ofbillwt,totaltax, andtotaltip.The script prints the tax, tip, and total bill using
format().
operators.py
Description
This script demonstrates the use of the floor division operator (//) in Python.
Code and Explanation
x = 10
y = 3
print(x // y) # Output: 3
Variables
xandyare set to10and3, respectively.The floor division operator
//dividesxbyyand rounds down to the nearest whole number.The output of
10 // 3is3.
rounding.py
Description
This script demonstrates rounding a float to the nearest integer using the round() function, and also checks the types of variables.
Code and Explanation
value = 96.6666666666666666
a = print(round(value)) # Output: 97
print(type(value)) # Output: <class 'float'>
print(type(a)) # Output: <class 'NoneType'>
valueis set to a float96.6666666666666666.round(value)roundsvalueto the nearest integer, which is97, andprint()outputs this value.print(type(value))outputs the type ofvalue, which isfloat.astores the return value ofprint(), which isNone.print(type(a))outputs the type ofa, which isNoneType.
variables.py
Description
This script demonstrates the use of variables, user input, and string concatenation in Python.
Code and Explanation
name = input("Tell me your name: ")
print("Your name is " + name)
The script prompts the user for their name with
input().print("Your name is " + name)concatenates the string "Your name is " with the user's input and prints it.
first_name = "Julia"
last_name = "Roberts"
full_name = first_name + " " + last_name
print(full_name) # Output: Julia Roberts
first_nameandlast_nameare set to "Julia" and "Roberts", respectively.full_nameconcatenatesfirst_name, a space" ", andlast_name.print(full_name)outputsfull_name, which is "Julia Roberts".
DAY2 project.py
Description
This script calculates the commission based on sales input by the user and uses formatted string literals (f-strings) to display the result.
Code and Explanation
name = input("What is your name ?: ")
b = input("What is your sales ?: ")
c = float(b)
d = c * 13 / 100
commission = round(d, 2)
print(f"Hi {name}, your commissions this month are Rs{commission}")
The script prompts the user for their name and sales.
The sales input (
b) is converted to a float (c).dcalculates 13% ofc.commissionroundsdto 2 decimal places.The script uses an f-string to print the user's name and commission, formatted to two decimal places.
DAY 3
Booleans.py
Description
This script demonstrates the use of Boolean values in Python, logical operations, and membership tests in lists.
Code and Detailed Explanation:
num = 6 > 2 + 3
print(num) # Output: True
print(type(num)) # Output: <class 'bool'>
numis assigned the result of the expression6 > 5(which isTrue).The script prints
numand its type, which isbool.
num = bool(5 > 6)
print(num) # Output: False
num is assigned the result of bool(5 > 6), which converts the expression 5 > 6 to a Boolean (False).
list = [1, 2, 3, 4]
cn = 5 in list
cb = 5 not in list
print(cn) # Output: False
print(cb) # Output: True
cnisFalsebecause5is not in the list.cbisTruebecause5is not in the list.
sets.py
Description
This script demonstrates basic operations with sets in Python, including adding and removing elements, and performing union and discard operations.
Code and Detailed Explanation:
my_set = set((1, 2, 3, 4, 5))
print(my_set) # Output: {1, 2, 3, 4, 5}
print(type(my_set)) # Output: <class 'set'>
my_setis created using thesetconstructor with a tuple.The script prints the set and its type, which is
set.
other_set = {1, 2, 3, 4, 5}
print(other_set) # Output: {1, 2, 3, 4, 5}
print(type(other_set)) # Output: <class 'set'>
other_setis created using curly braces with elements.The script prints the set and its type, which is
set.
s1 = {1, 2, 3}
s1.add(4)
print(s1) # Output: {1, 2, 3, 4}
s1.add(4)adds the element4to the sets1.The script prints the modified set.
s1.remove(1)
print(s1) # Output: {2, 3, 4}
s1.remove(1)removes the element1from the sets1.The script prints the modified set.
s2 = {4, 5, 6}
s3 = s1.union(s2)
print(s3) # Output: {2, 3, 4, 5, 6}
s3 = s1.union(s2)creates a new sets3that contains all elements from both setss1ands2.The script prints the union of the sets.
s3.discard(2)
print(s3) # Output: {3, 4, 5, 6}
s3.discard(2)removes the element2from the sets3if it exists.The script prints the modified set.
s3.pop()
print(s3) # Output: {4, 5, 6} (or any other variation, as sets are unordered)
s3.pop()removes and returns an arbitrary element from the sets3.The script prints the modified set.
s3.clear()
print(s3) # Output: set()
s3.clear()removes all elements from the sets3.The script prints the now empty set.
Tuples.py
Description
This script demonstrates how to work with tuples in Python, including accessing elements and using tuple methods.
Code and Detailed Explanation:
my_tuple = (1, 2, (3, 4), 5)
print(my_tuple[2]) # Output: (3, 4)
print(my_tuple[2][0]) # Output: 3
my_tuplecontains nested tuples.The script accesses the nested tuple
(3, 4)and then the first element3of that nested tuple.
t = (1, 2, 3)
print(t.count(1)) # Output: 1
print(len(t)) # Output: 3
t.count(1)returns the number of occurrences of1in the tuplet.len(t)returns the length of the tuplet.
dictionaries.py
Description
This script demonstrates basic operations with dictionaries in Python, including accessing and modifying dictionary elements.
Code and Detailed Explanation:
my_dictionary = {'c1': 'value1', 'c2': 'value2', 'c3': 'value3'}
print(my_dictionary) # Output: {'c1': 'value1', 'c2': 'value2', 'c3': 'value3'}
print(type(my_dictionary)) # Output: <class 'dict'>
print(my_dictionary['c1']) # Output: value1
The script initializes my_dictionary with some key-value pairs and prints the dictionary, its type, and the value associated with the key 'c1'.
dict = {1: 20, 2: 30, 3: ['RAMA', 'Sita', 'Laxman'], 4: {'c1': 'value1', 'c2': 'value2', 'c3': 'value3'}}
print(dict[3][1]) # Output: Sita
print(dict[3][0].upper()) # Output: RAMA
The dictionary
dictcontains nested lists and dictionaries.The script accesses the second element of the list at key
3and prints it.It also prints the uppercase version of the first element of the list at key
3.
di = {1: 2, 2: 3}
di[3] = 20
print(di) # Output: {1: 2, 2: 3, 3: 20}
print(di.keys()) # Output: dict_keys([1, 2, 3])
print(di.values()) # Output: dict_values([2, 3, 20])
print(di.items()) # Output: dict_items([(1, 2), (2, 3), (3, 20)])
The script adds a new key-value pair to
diand prints the dictionary.It also prints the keys, values, and items of the dictionary.
index.py
Description
This script demonstrates how to find the index of a substring in a string using the index and rindex methods.
Code and Detailed Explanation:
my_text = "Hare Krishna Hare Krishna Krishna Krishna Hare Hare, Hare Rama Hare Rama Rama Rama Hare Hare"
result1 = my_text.index("h")
result2 = my_text.rindex("h")
print(result1) # Output: 42
print(result2) # Output: 117
my_text.index("h")returns the index of the first occurrence of "h".my_text.rindex("h")returns the index of the last occurrence of "h".
lists.py
Description
This script demonstrates basic operations with lists in Python, including concatenation, appending, and sorting.
Code and Detailed Explanation:
my_list = ['a', 'b', 'c']
my_list2 = ['d', 'e', 'f']
my_list3 = my_list + my_list2
my_list3.append('g')
print(my_list3) # Output: ['a', 'b', 'c', 'd', 'e', 'f', 'g']
The script concatenates
my_listandmy_list2intomy_list3.It appends 'g' to
my_list3and prints the list.
deleted = my_list3.pop(0)
print(my_list3) # Output: ['b', 'c', 'd', 'e', 'f', 'g']
print(deleted) # Output: a
my_list3.pop(0)removes and returns the first element ofmy_list3.The script prints the modified list and the deleted element.
my_list3.pop()
print(my_list3) # Output: ['b', 'c', 'd', 'e', 'f']
my_list3.pop()removes and returns the last element ofmy_list3.The script prints the modified list.
list = ['d', 'h', 'a']
list.sort()
list.reverse()
print(list) # Output: ['h', 'd', 'a']
The script sorts the list in ascending order and then reverses it, printing the result.
methods.py
Description
This script demonstrates various string methods in Python, including upper, lower, split, find, and replace, as well as the join method.
Code and Detailed Explanation:
my_text = "Hare Krishna Hare Krishna Krishna Krishna Hare Hare, Hare Rama Hare Rama Rama Rama Hare Hare"
a = my_text.upper()
b = my_text.lower()
c = my_text.split()
d = my_text.split("h")
e = my_text.find("H")
f = my_text.replace(",", " ")
print(a) # Output: HARE KRISHNA HARE KRISHNA KRISHNA KRISHNA HARE HARE, HARE RAMA HARE RAMA RAMA RAMA HARE HARE
print(b) # Output: hare krishna hare krishna krishna krishna hare hare, hare rama hare rama rama rama hare hare
print(c) # Output: ['Hare', 'Krishna', 'Hare', 'Krishna', 'Krishna', 'Krishna', 'Hare', 'Hare,', 'Hare', 'Rama', 'Hare', 'Rama', 'Rama', 'Rama', 'Hare', 'Hare']
print(d) # Output: ['Hare Krishna Hare Krishna Krishna Krishna Hare Hare, Hare Rama Hare Rama Rama Rama Hare Hare']
print(e) # Output: 0
print(f) # Output: Hare Krishna Hare Krishna Krishna Krishna Hare Hare Hare Rama Hare Rama Rama Rama Hare Hare
ais the uppercase version ofmy_text.bis the lowercase version ofmy_text.cis a list of words inmy_textsplit by whitespace.dis a list of substrings inmy_textsplit by the character "h".eis the index of the first occurrence of "H".fismy_textwith commas replaced by spaces.
A = "Learning"
B = "Python"
C = "Is Easy"
D = " ".join([A, B, C])
print(D) # Output: Learning Python Is Easy
Dis a string created by joiningA,B, andCwith spaces in between.The script prints the resulting string.
slice.py
Description
This script demonstrates basic string slicing operations in Python.
Code and Detailed Explanation:
name = "Arijit"
fragment1 = name[1:]
fragment2 = name[::2]
print(fragment1) # Output: rijit
print(fragment2) # Output: Aii
fragment1 = name[1:]slices the stringnamefrom the second character to the end.fragment2 = name[::2]slices the stringnamestarting from the beginning and takes every second character.The script prints both slices.
DAY3project.py
Description
This script performs multiple text analysis tasks based on user input. It accepts a block of text and three letters from the user, then provides the following information:
The number of times each letter appears in the text.
The total number of words in the text.
The first and last letters of the text.
The text with words in reverse order.
Whether the word "Python" appears in the text.
Code and Detailed Explanation:
Step 1: User Input
text = input("Enter a text: ")
letters = []
text = text.lower()
letters.append(input("Enter 1st letter: ").lower())
letters.append(input("Enter 2nd letter: ").lower())
letters.append(input("Enter 3rd letter: ").lower())
The script prompts the user to enter a block of text and stores it in the variable
text.The text is converted to lowercase to ensure case-insensitive comparisons.
The user is then prompted to enter three letters, which are also converted to lowercase and stored in the list
letters.
Step 2: Counting Letter Repetitions
print("\n")
print("LETTER REPETITIONS")
letter_repetition1 = text.count(letters[0])
letter_repetition2 = text.count(letters[1])
letter_repetition3 = text.count(letters[2])
print(f"We have found the letter '{letters[0]}' repeated {letter_repetition1} times")
print(f"We have found the letter '{letters[1]}' repeated {letter_repetition2} times")
print(f"We have found the letter '{letters[2]}' repeated {letter_repetition3} times")
The script counts the occurrences of each letter from the
letterslist in thetext.It prints the count for each letter using formatted strings.
Step 3: Counting Words
print("\n")
print("NUMBER OF WORDS")
words = text.split()
print(f"We have found the {len(words)} words in your text")
The text is split into words using the
split()method, which divides the text at whitespace.The script counts the number of words and prints the result.
Step 4: First and Last Letters
print("\n")
print("FIRST AND LAST LETTER")
first_letter = text[0]
last_letter = text[-1]
print(f"The initial letter is '{first_letter}', the final letter is '{last_letter}'")
The script extracts the first and last letters of the text.
It prints these letters.
Step 5: Inverted Text
print("\n")
print("INVERTED TEXT")
words.reverse()
inverted_text = ''.join(words)
print(f"If we order your text backwards it will say '{inverted_text}'")
The words list is reversed using the
reverse()method.The script joins the reversed words into a single string without spaces and prints the result.
Step 6: Checking for the Word "Python"
print("\n")
print("LOOKING FOR THE WORD PYTHON")
is_python = 'Python' in text
dic = {True: "was", False: "was not"}
print(f"The word 'Python' {dic[is_python]} found in the text")
The script checks if the word "Python" (case-sensitive) is in the text.
It uses a dictionary
dicto mapTrueto "was" andFalseto "was not".The script prints whether the word "Python" was found in the text.
DAY4
comparison_operator.py
Part (a)
This part of the script demonstrates the use of comparison operators (==, !=) to compare values and strings. The script also includes a basic conditional statement to illustrate the use of the if-else construct.
my_bool = 10 == 25
print(my_bool) # False, because 10 is not equal to 25
my_bool = 'white' == "white"
print(my_bool) # True, because both strings are identical
my_bool = 100 != 1
print(my_bool) # True, because 100 is not equal to 1
The script compares integers and strings using equality (==) and inequality (!=) operators, printing the results as booleans (True or False).
if 5 == 2:
print("It is correct")
else:
print("It is not correct")
- The
if-elsestatement checks if5 == 2, which isFalse, so it prints "It is not correct".
Part (b)
This part adds complexity to the conditional logic by introducing nested if statements and elif (else if) conditions.
age = 18
school_grade = 10
if age < 19:
print("You are a minor")
if school_grade >= 4:
print("Passed")
else:
print("Better luck next time")
else:
print("You are an adult")
The script checks if
ageis less than 19, then checks if theschool_gradeis 4 or higher.Depending on the conditions, it prints the appropriate message.
pet = 'dog'
if pet == 'cat':
print("Nice cat")
elif pet == 'fish':
print("Nice fish")
else:
print('I don\'t know which animal')
The script checks the value of
petand useselifto handle different possible values (cat,fish, etc.).Since
petis 'dog', theelseclause executes, printing "I don't know which animal".
enumerator.py
This script demonstrates how to use enumerate() with a loop. enumerate() adds a counter to an iterable, returning it as an enumerate object.
my_list = ['q', 'b', 'c']
for item in enumerate(range(1, 51)):
print(item)
The script enumerates over a range of numbers from 1 to 50 and prints each enumerated pair (index, value).
enumerate()is useful for obtaining both index and value in a loop.
for_loop.py
This script shows the use of for loops for iterating over lists and summing values.
my_list = ['a', 'b', 'c']
for letter in my_list:
print(letter)
letter_number = my_list.index(letter) + 1
print(f"letter {letter_number}: {letter}")
- The script iterates over
my_list, printing eachletterand its corresponding position (index + 1).
print("\n")
numbers = [1, 2, 3, 4, 5]
my_value = 0
for number in numbers:
my_value = my_value + number
print(my_value)
print(my_value)
The script calculates the cumulative sum of numbers in the list
numbers.After the loop, it prints the final sum.
logical_operators.py
This script demonstrates the use of logical operators (and, or, not) in Python.
my_bool = 4 < 5 and 5 > 6
print(my_bool) # False, because both conditions are not True
print(10 == 10 or 1 == 0) # True, because one of the conditions is True
print(10 == 10 or 10 == 1) # True, because one condition is True
print(not 'a' != "a") # True, because 'not' negates the False comparison ('a' == "a")
- The script evaluates logical expressions and prints the results as booleans (
TrueorFalse).
text = "Hare Krishna"
my_bool = ('sentence' in text) or ('krishna' not in text)
print(my_bool) # True, because 'krishna' is not in text and 'sentence' is also not in the text
- This part checks for the presence of substrings in the
textvariable usinginandnot inoperators.
matches.py
Part (a)
This part shows traditional if-elif-else matching based on the value of a variable.
series = "N-02"
if series == "N-01":
print("Samsung")
elif series == "N-02":
print("Nokia")
elif series == "N-03":
print("Motorola")
else:
print("This pdt. doesn't exist")
The script checks the value of
seriesand prints the corresponding brand name.If no match is found, it prints "This product doesn't exist".
Part (b)
This part uses the match-case statement, a more Pythonic approach introduced in Python 3.10, for pattern matching.
series = "N-02"
match series:
case "N-01":
print("Samsung")
case "N-02":
print("Nokia")
case "N-03":
print("Motorola")
case _:
print("This product doesn't exist")
- The
match-caseblock checks for the value ofseriesand matches it against specific cases.
Nested Match-Case Example
client = {'name': 'Hanuman', 'age': 24, 'occupation': 'Devotee of Lord Rama'}
movie = {'title': 'KGF2', 'credits': {'main_star': 'Yash', 'music': 'Ravi Basur'}}
items = [client, movie, 'book']
for i in items:
match i:
case {'name': name, 'age': age, 'occupation': occupation}:
print("It is a client")
print(name, age, occupation)
case {'title': title, 'credits': {'main_star': main_star, 'music': music}}:
print("This is a movie")
print(title, main_star, music)
case _:
print("I don't know what this is")
The script matches complex dictionary structures within a list using the
match-casestatement.It prints different outputs based on the structure and content of each dictionary.
min,max.py
This script demonstrates the use of min() and max() functions in Python to find the minimum and maximum values in dictionaries and lists.
cities_population = {"Albuquerque": 559121, "Tulsa": 403505}
my_list = [5**5, 12**2, 3050, 475*2]
print(min(cities_population.keys())) # "Albuquerque" because it comes first alphabetically
print(max(cities_population.values())) # 559121 because it is the highest population
print(max(my_list)) # 3125 because 5**5 is the largest number in the list
- The script uses
min()andmax()to find the smallest and largest values in different data structures.
random_file.py
This script uses the random module to generate random numbers and create lists with comprehensions.
from random import randint
my_random = randint(1, 50)
print(my_random) # Prints a random integer between 1 and 50
from random import *
my_random = uniform(1, 9)
print(my_random) # Prints a random float between 1 and 9
my_list = [ff for ff in 'PYTHON']
print(my_list) # Creates a list of characters ['P', 'Y', 'T', 'H', 'O', 'N']
my_list = [n for n in range(0, 21, 2)]
print(my_list) # Creates a list of even numbers from 0 to 20
my_list = [n/2 for n in range(0, 21, 2)]
print(my_list) # Creates a list of even numbers divided by 2
The script demonstrates generating random numbers using
randintanduniform.It also shows how to use list comprehensions for different purposes.
range.py
This script illustrates the usage of the range() function to generate a sequence of numbers and convert them to a list.
for num in range(1, 21):
print(num) # Prints numbers from 1 to 20
my_list = list(range(1, 101))
print(my_list) # Creates a list of numbers from 1 to 100
range()generates a sequence of numbers, which can be iterated over or converted into a list.
while_loop.py
Part
(a) This script uses a while loop to repeatedly execute a block of code as long as a condition is True.
coins = 5
while coins > 0:
print(f"I have {coins} coins")
coins -= 1 # Decreases the coin count by 1 in each iteration
else:
print("I have no money anymore")
- The script continues to print the number of coins until
coinsbecomes0.
Part (b)
This part demonstrates a while loop with user input.
answer = 'y'
while answer == 'y':
answer = input("Do you want to continue (y/n)? ")
else:
print("Thank you for your response")
- The loop runs as long as the user inputs
'y', and stops when the input is anything else.
Part (c)
This part includes a for loop with break and continue statements.
name = input("Your name: ")
for letter in name:
if letter == 'j':
break # Exits the loop if the letter is 'j'
continue # Skips the remaining code in the loop
print(letter) # This line will not execute because `continue` skips it
- The script iterates over the characters in the user's name, breaks the loop if it encounters 'j', and skips to the next iteration if the
continuestatement is reached.
Part (d)
This part includes a while loop with a pass statement.
age = 18
while age > 18:
pass # Does nothing and continues the loop
print('Hello') # This line is executed because the loop condition is False
- The
passstatement is a null operation; the loop does nothing and immediately exits sinceageis not greater than 18.
zip.py
This script demonstrates the use of zip() to combine multiple lists and iterate over them simultaneously.
names = ['Krishna', 'Balaram']
age = [18, 20]
cities = ['Goloka Vrindavan', 'Vaikuntha']
DHAM = list(zip(names, age, cities))
for name, age, city in DHAM:
print(f"{name} is {age} years old, and lives in the {city} dham.")
- The
zip()function combinesnames,age, andcitiesinto tuples and then iterates over these tuples to print formatted strings.
DAY4project.py
Importing randint:
from random import randint- The
randintfunction from therandommodule generates a random integer between the given range, inclusive of both endpoints.
- The
Initializing Variables:
guess = 0 secret_number = randint(1, 100) estimation = 0 name = input("Username: ")guess: Tracks the number of guesses the user has made.secret_number: Stores the randomly generated secret number that the user has to guess.estimation: Stores the user's current guess.name: Stores the user's name, which is used for personalized messages.
Introduction Message:
print(f"OK {name}, I have thought of a number between 1 and 100\n You have 8 guesses to guess")- A welcome message informs the user of the game rules and the number of guesses they have.
The While Loop (Main Game Loop):
while guess < 8: estimation = int(input("What is the number: ")) guess += 1The loop runs until the user has made 8 guesses (
guess < 8).The user's guess is taken as input and converted to an integer (
int()).The number of guesses is incremented by 1 after each guess (
guess += 1).
Conditional Statements (Checking the Guess):
if estimation < secret_number: print("My number is lower") elif estimation > secret_number: print("My number is higher") else: print(f"Congratulations {name}! You have guessed in {guess} attempts") breakThe script compares the user's guess (
estimation) with the secret number (secret_number):If the guess is lower than the secret number, it prints "My number is lower."
If the guess is higher, it prints "My number is higher."
If the guess is correct, it congratulates the user and breaks out of the loop.
End of Game Message:
if estimation != secret_number: print(f"Sorry {name}, you have run out of attempts\n BETTER LUCK NEXT TIME")- If the loop ends without the user guessing the correct number, the script prints a message indicating that they have run out of attempts.
Summary:
Purpose: The game challenges the user to guess a randomly selected number between 1 and 100 within 8 attempts.
Features:
Feedback after each guess (whether the guess is too high or too low).
Personalized messages using the user's name.
A congratulatory message if the user guesses correctly, or a "better luck next time" message if they fail.
DAY5
create_function.py
Script:
def greet(name):
print("Hello " + name)
greet('Rama')
greet('Hanuman')
Explanation:
Purpose: This script defines a simple function
greet()that takes anameas an argument and prints a greeting message.Function
greet(name):The function concatenates "Hello " with the provided
nameand prints the result.The function is called twice with different names: 'Rama' and 'Hanuman'.
Output:
Hello Rama Hello Hanuman
dynamic_functions.py
(a) Checking if a Number is in Range
def check_3_digits(number):
return number in range(1, 100)
result = check_3_digits(103)
print(result)
Function
check_3_digits(number):Takes a number as input and checks if it falls within the range 1 to 99.
Returns
Trueif the number is in the range, otherwiseFalse.Output:
False(because 103 is not in the range).
(b) Checking if a List Contains a 3-Digit Number
def check_3_digits(list1):
for n in list1:
if n in range(100, 1000):
return True
return False
result = check_3_digits([555, 99, 6000])
print(result)
Function
check_3_digits(list1):Iterates through the list
list1and checks if any number is a 3-digit number (between 100 and 999).Returns
Trueif at least one 3-digit number is found; otherwise, returnsFalse.Output:
True(because 555 is a 3-digit number).
(c) Returning All 3-Digit Numbers in a List
def check_3_digits(list1):
three_digits_list = []
for n in list1:
if n in range(100, 1000):
three_digits_list.append(n)
return three_digits_list
result = check_3_digits([555, 99, 600])
print(result)
Function
check_3_digits(list1):Creates a new list
three_digits_listcontaining all 3-digit numbers from the input listlist1.Returns the list of 3-digit numbers.
Output:
[555, 600]
function_example.py
Script:
coffee_prices = [('Cappuccino', 1.5), ('Espresso', 1.2), ('Mocha', 1.9)]
def most_expensive_coffee(list_of_prices):
highest_price = 0
my_most_expensive_coffee = ''
for coffee, price in list_of_prices:
if price > highest_price:
highest_price = price
my_most_expensive_coffee = coffee
return my_most_expensive_coffee, highest_price
print(most_expensive_coffee(coffee_prices))
Explanation:
Function
most_expensive_coffee(list_of_prices):Takes a list of tuples containing coffee names and their prices.
Iterates through the list to find the coffee with the highest price.
Returns the name and price of the most expensive coffee.
Output:
('Mocha', 1.9)
functions_interactions.py
Script:
from random import shuffle
# Initial list
sticks = ['-', '--', '---', '----']
# Mixing sticks
def mix(my_list):
shuffle(my_list)
return my_list
# Choose number
def try_your_luck():
a_try = ''
while a_try not in ['1', '2', '3', '4']:
a_try = input("Choose a number: ")
return int(a_try)
# Check player's try
def verify_try(a_list, a_try):
if a_list[a_try - 1] == '-':
print("Wash the dishes")
else:
print("This time you are safe")
print(f'You got {a_list[a_try - 1]}')
mixed_sticks = mix(sticks)
selection = try_your_luck()
verify_try(mixed_sticks, selection)
Explanation:
Purpose: This script simulates a simple game where the user picks a stick from a shuffled list, and the result tells them if they need to wash the dishes.
Function
mix(my_list):- Shuffles the list of sticks and returns the shuffled list.
Function
try_your_luck():Prompts the user to choose a number between 1 and 4.
Ensures the input is valid and returns it as an integer.
Function
verify_try(a_list, a_try):Checks if the selected stick is the shortest one (represented by '-').
Prints a message based on the user's choice.
Example Output:
After choosing a number:
Choose a number: 3 This time you are safe You got ---
help.py
Script:
dic = {'key1': 100, 'key2': 200}
a = dic.popitem()
print(a)
print(dic)
Explanation:
Purpose: Demonstrates the use of the
popitem()method on a dictionary.Method
popitem():Removes and returns the last key-value pair from the dictionary as a tuple.
The dictionary is modified in place.
Output:
('key2', 200) {'key1': 100}
kwargs.py
(a) Function with **kwargs
def a_sum(**kwargs):
for key, value in kwargs.items():
print(f'{key}={value}')
a_sum(x=3, y=5, z=2)
Function
a_sum(**kwargs):Accepts any number of keyword arguments.
Iterates over the dictionary of arguments and prints each key-value pair.
Output:
x=3 y=5 z=2
(b) Sum Function with **kwargs
def a_sum(**kwargs):
total = 0
for key, value in kwargs.items():
print(f'{key}={value}')
total += value
return total
print(a_sum(x=3, y=5, z=2))
Function
a_sum(**kwargs):Adds up the values of all keyword arguments and returns the total sum.
Output:
10
(c) Function with *args and **kwargs
def test(num1, num2, *args, **kwargs):
print(f'The first number is {num1}')
print(f'The second number is {num2}')
for arg in args:
print(f'args={arg}')
for key, value in kwargs.items():
print(f'{key}={value}')
args = [100, 200, 300, 400]
kwargs = {'x': 'one', 'y': 'two', 'z': 'three'}
test(15, 50, *args, **kwargs)
Function
test(num1, num2, *args, **kwargs):Demonstrates the use of positional arguments (
num1,num2),*args, and**kwargs.Prints the values of all arguments passed to the function.
Output:
The first number is 15 The second number is 50 args=100 args=200 args=300 args=400 x=one y=two z=three
return.py
Script:
def multiply(num1, num2):
return num1 * num2
print(multiply(5, 10))
Explanation:
Function
multiply(num1, num2):Multiplies two numbers and returns the result.
Output:
50
args.py
(a) Sum Function with *args
def a_sum(*args):
total = 0
for arg in args:
total += arg
return total
print(a_sum(5, 6, 5))
Function
a_sum(*args):Accepts any number of positional arguments.
Adds up all the arguments and returns the sum.
Output:
16
(b) Simplified Sum Function with *args
def a_sum(*args):
return sum(args)
print(a_sum(5, 6, 5, 6, 80))
Function
a_sum(*args):A simpler version of the previous function using Python's built-in
sum()function.Output:
102
Exercises
(a) Exercise 1: Return Distinct Values
def return_distincts(a, b, c):
a_sum = a + b + c
a_list = [a, b, c]
if a_sum > 15:
return max(a_list)
elif a_sum < 10:
return min(a_list)
else:
a_list.sort()
return a_list[1]
print(return_distincts(2, 10, 5))
Function
return_distincts(a, b, c):Takes three numbers, sums them, and returns:
The maximum value if the sum is greater than 15.
The minimum value if the sum is less than 10.
The middle value if the sum is between 10 and 15.
Output:
5
(b) Exercise 2: Unique Sorted Letters
def ola_words(word):
my_set = set()
for letter in word:
my_set.add(letter)
my_list = list(my_set)
my_list.sort()
return my_list
print(ola_words('HANUMAN'))
Function
ola_words(word):Converts the word into a set of unique letters, sorts them, and returns the sorted list.
Output:
['A', 'H', 'M', 'N', 'U']
(c) Exercise 3: Counting Zeroes
def counting_zeroes(*args):
count = 0
for n in args:
if args[count] == 0 and args[count + 1] == 0:
return True
else:
count += 1
return False
print(counting_zeroes(1, 2, 3, 4, 5, 6, 0, 4, 5, 6))
Function
counting_zeroes(*args):Checks if there are two consecutive zeroes in the input arguments.
Returns
Trueif found, otherwiseFalse.Output:
False
(d) Exercise 4: Count Prime Numbers
def count_primes(numbers):
prime_numbers = [2]
iterations = 3
if numbers < 2:
return 0
while iterations <= numbers:
for n in range(3, iterations, 2):
if iterations % n == 0:
iterations += 2
break
else:
prime_numbers.append(iterations)
iterations += 2
print(prime_numbers)
return len(prime_numbers)
print(count_primes(50))
Function
count_primes(numbers):Counts and returns the number of prime numbers up to the given number.
Output:
15(and prints the list of prime numbers up to 50:[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47])
DAY5project.py
Code Breakdown
1. Importing Modules
from random import choice
choice: Imported from therandommodule, this function is used to randomly select a word from a list of possible words.
2. Variable Initialization
words = ['sri rama','sita maa','laxman','hanuman']
correct_letters = []
incorrect_letters = []
tries = 6
right_answers = 0
game_over = False
words: List containing the possible words to be guessed.correct_letters: List that stores the letters guessed correctly.incorrect_letters: List that stores the letters guessed incorrectly.tries: The number of attempts the player has to guess the word.right_answers: Counter to keep track of the number of correct guesses.game_over: Boolean variable that indicates whether the game is over.
3. choose_word() Function
def choose_word(list_of_words):
chosen_word = choice(list_of_words)
different_letters = len(set(chosen_word))
return chosen_word, different_letters
Purpose: Selects a random word from the list and calculates the number of unique letters.
Parameters:
list_of_words(list) - The list from which a word is chosen.Returns:
chosen_word: The selected word.different_letters: The number of unique letters in the chosen word.
4. ask_letters() Function
def ask_letters():
chosen_letter = ''
is_valid = False
alphabet = 'abcdefghijklmnopqrstuvwxyz'
while not is_valid:
chosen_letter = input("Please choose a letter: ")
if chosen_letter in alphabet and len(chosen_letter) == 1:
is_valid = True
else:
print("You haven't chosen a correct alphabet")
return chosen_letter
Purpose: Prompts the player to input a letter, validating the input to ensure it is a single alphabet character.
Returns: The chosen valid letter.
5. show_new_board() Function
def show_new_board(chosen_word):
hidden_list = []
for l in chosen_word:
if l in correct_letters:
hidden_list.append(l)
else:
hidden_list.append('-')
print(''.join(hidden_list))
Purpose: Displays the current state of the word with correctly guessed letters revealed and the rest hidden as dashes (
-).Parameters:
chosen_word(str) - The word being guessed.
6. check_letter() Function
def check_letter(chosen_letter, hidden_word, tries, matches):
end = False
if chosen_letter in hidden_word and chosen_letter not in correct_letters:
correct_letters.append(chosen_letter)
matches += 1
elif chosen_letter in hidden_word and chosen_letter in correct_letters:
print("You have already found the letter, try with another one")
else:
incorrect_letters.append(chosen_letter)
tries -= 1
if tries == 0:
end = lose()
elif matches == unique_letters:
end = win(hidden_word)
return tries, end, matches
Purpose: Checks the player's letter guess against the hidden word and updates the game state.
Parameters:
chosen_letter(str): The letter guessed by the player.hidden_word(str): The word being guessed.tries(int): The remaining attempts.matches(int): The number of correctly guessed unique letters.
Returns:
tries: Updated number of remaining attempts.end: Boolean indicating if the game is over.matches: Updated number of correct guesses.
7. lose() Function
def lose():
print("You don't have any tries left")
print("The hidden word was " + words)
return True
Purpose: Displays a message when the player runs out of attempts and reveals the hidden word.
Returns:
True, indicating the game is over.
8. win() Function
def win(revealed_word):
show_new_board(revealed_word)
print("Congrats! You guessed the word!!!!!")
return True
Purpose: Displays a congratulatory message when the player guesses the word correctly.
Parameters:
revealed_word(str) - The word that was guessed.Returns:
True, indicating the game is over.
9. Game Loop
words, unique_letters = choose_word(words)
while not game_over:
print('\n' + '*' * 20 + '\n')
show_new_board(words)
print('\n')
print('Incorrect letters: ' + '-'.join(incorrect_letters))
print(f'Tries:{tries}')
print(('\n' + '*' * 20 + '\n'))
letter = ask_letters()
tries, over, right_answers = check_letter(letter, words, tries, right_answers)
game_over = over
- Purpose: Runs the main loop of the game, continuing until the game is over. It displays the current game state, prompts for a letter, checks the letter, and updates the game state accordingly.
Execution Flow
The game selects a random word from the list.
The player is prompted to guess a letter.
The game checks if the guessed letter is in the word and updates the game state.
The game ends when the player either guesses all unique letters or runs out of attempts.
DAY6
path1.py
(a) Exploring Paths
from pathlib import Path
base = Path.home()
guide = Path(base, 'Paris', 'Eiffel_Tower.txt')
guide = Path(base, 'Europe', 'France', Path('Paris', 'Eiffel_Tower.txt'))
guide2 = guide.with_name('Notre_Dam.txt')
print(base)
print(guide)
print(guide2)
print(guide.parent)
print(guide.parent.parent)
print(guide.parent.parent.parent)
print(guide.parent.parent.parent.parent)
Explanation:
Path.home(): This finds where your home is on the computer (like your own special room).
guide: It's like creating a path or a treasure map that shows the way to a file called 'Eiffel_Tower.txt' inside a folder called 'Paris' which is inside another folder called 'France' and so on.
guide2: Imagine you're holding a book, and then you change the book to a different one. This changes the name of the file to 'Notre_Dam.txt'.
guide.parent, guide.parent.parent: These help you find which folder the file is inside (like finding out which box a toy is in, and which bigger box that box is in).
(b) Finding Text Files
from pathlib import Path
base = Path.home()
guide = Path(Path.home(), 'Europe')
for txt in Path(guide).glob('*.txt'):
print(txt)
Explanation:
- .glob('*.txt'): This is like looking through all the drawers in a room to find all the papers with a ".txt" label on them.
(c) Relative Paths
from pathlib import Path
base = Path.home()
guide3 = Path('Europe', 'France', 'Paris', 'Eiffel_Tower.txt')
in_europe = guide3.relative_to(Path('Europe'))
in_france = guide3.relative_to(Path('Europe','France'))
print(in_europe)
print(in_france)
Explanation:
- relative_to: This helps you figure out the path or steps to reach the file from a specific point (like figuring out how to get from your living room to your bedroom).
pathlib1.py
(a) Checking and Reading a File
from pathlib import Path
folder = Path('C:/Users/HP/OneDrive/Desktop/Python Course/DAY 6/test.txt')
print(folder.read_text())
print('\n')
print(folder.name)
print(folder.suffix)
print(folder.stem)
if not folder.exists():
print("This doesn't exists")
else:
print("YES. This file exists.")
Explanation:
folder.read_text(): This reads what’s inside a file, like reading a letter.
folder.name: This tells you the name of the file (like 'test.txt').
folder.suffix: This shows the last part of the file name (like the ".txt").
folder.stem: This shows the name without the ".txt" part.
if not folder.exists(): This checks if the file is there, like checking if your toy is still in its place.
(b) Converting to Windows Path
from pathlib import Path, PureWindowsPath
folder = Path('C:\\Users\\HP\\OneDrive\\Desktop\\Python Course\\DAY 6\\test.txt')
windows_path = PureWindowsPath(folder)
print(windows_path)
Explanation:
- PureWindowsPath: This changes the path to the style that Windows computers use.
write_files.py
(a) Writing to a File
file = open("test1.txt", "w")
file.write("All glories to Srila Prabhupada")
file.close()
Explanation:
open("test1.txt", "w"): This opens a file to write something new into it, like opening your diary to write a new entry.
file.write: This writes something in the file, like writing a note on a piece of paper.
file.close(): This closes the file after writing, like closing your diary after writing.
(b) Appending to a File
file = open("test1.txt", "a")
file.write("!")
file.close()
Explanation:
- "a": This means we are adding more to the file, like adding a sticker to a page in your book.
input_output_1.py
Reading Files in Different Ways
my_file = open('test.txt')
print(my_file)
print('\n')
my_file = open('test.txt')
print(my_file.read())
Explanation:
open('test.txt'): This opens a file so you can read it, like opening a storybook.
my_file.read(): This reads the whole file at once, like reading the whole story at one go.
directories.py
(a) Current Working Directory
import os
path = os.getcwd()
print(path)
Explanation:
- os.getcwd(): This tells you where you are currently on your computer, like knowing which room you're in.
(b) Getting File Parts
import os
path = 'C:\\Users\\HP\\OneDrive\\Desktop\\Python Course\\DAY 6\\test.txt'
a = os.path.dirname(path)
b = os.path.basename(path)
c = os.path.split(path)
print(a)
print(b)
print(c)
Explanation:
os.path.dirname: This tells you the folder the file is in.
os.path.basename: This tells you the file name.
os.path.split: This splits the path into the folder and the file name.
clean_console.py
from os import system
name = input('Your name: ')
age = input('Your age: ')
system('cls')
print(f"Your name is {name} and your age is {age}")
Explanation:
- system('cls'): This clears the screen, like wiping the board clean to write new things.
DAY6project.py
Importing Libraries
import os
from pathlib import Path
from os import system
Explanation:
import os: This allows us to use functions that let us interact with the computer's operating system (like creating or deleting folders).
from pathlib import Path: This helps us work with paths (directions to files and folders) in a way that's easy to understand.
from os import system: This lets us use commands that can do things like clear the screen.
Setting Up the Recipe Path
my_path = Path(Path.home(), 'Recipes')
Explanation:
- my_path: This is the place where all our recipes are stored. It's like a special cupboard for all your recipe books.
Counting the Number of Recipes
def count_recipes(path):
counter = 0
for txt in Path(path).glob('**/*.txt'):
counter += 1
return counter
Explanation:
count_recipes(path): This function counts how many recipe files (like pieces of paper with recipes written on them) are in your cupboard.
counter = 0: We start counting from zero.
for txt in Path(path).glob('/*.txt')**: This looks through every folder and finds all the files that end with ".txt" (which is like finding all your recipe papers).
counter += 1: Every time it finds a recipe, it adds one to the counter.
Starting the Program
def start():
system('cls')
print('-'*50)
print('!'*5 + " Welcome to the recipe book " + '!'*5)
print('-'*50)
print('\n')
print(f"The recipes are in {my_path}")
print(f"Total recipes: {count_recipes(my_path)}")
menu_choice = 'x'
while not menu_choice.isnumeric() or int(menu_choice) not in range(1,7):
print("Choose an option: ")
print('''
[1]-Read Recipe
[2]-Create Recipe
[3]-Create Category
[4]-Delete Recipe
[5]-Delete Category
[6]-End Program''')
menu_choice = input()
return int(menu_choice)
Explanation:
start(): This function starts the program. It's like opening the recipe book to the first page.
system('cls'): This clears the screen, like erasing a chalkboard before starting a new lesson.
print(): These lines print a welcome message and show how many recipes you have.
menu_choice: This is where you choose what you want to do next (like reading a recipe, adding a new one, or stopping the program).
while not menu_choice.isnumeric() or int(menu_choice) not in range(1,7): This makes sure you choose a number between 1 and 6.
Showing Categories
def show_categories(path):
print("Categories: ")
categories_path = Path(path)
categories_list = []
counter = 1
for folder in categories_path.iterdir():
folder_str = str(folder.name)
print(f"[{counter}] - {folder_str}")
categories_list.append(folder)
counter += 1
return categories_list
Explanation:
show_categories(path): This function shows all the categories (or types) of recipes you have, like "Desserts" or "Main Courses."
categories_list = []: We start with an empty list to store all the categories.
for folder in categories_path.iterdir(): This looks through each category folder, like looking through the drawers in your cupboard.
Choosing a Category
def choose_categories(a_list):
correct_choice = 'x'
while not correct_choice.isnumeric() or int(correct_choice) not in range(1, len(a_list) + 1):
correct_choice = input("\nChoose a category: ")
return a_list[int(correct_choice)-1]
Explanation:
choose_categories(a_list): This function lets you pick a category from the list, like choosing which drawer to open.
while not correct_choice.isnumeric() or int(correct_choice) not in range(1, len(a_list) + 1): This makes sure you pick a number that matches one of the categories.
Showing Recipes
def show_recipes(path):
print("These are the recipes: ")
recipes_path = Path(path)
recipes_list = []
counter = 1
for recipe in recipes_path.glob('*.txt'):
recipe_str = str(recipe.name)
print(f"[{counter}] - {recipe_str}")
recipes_list.append(recipe)
counter += 1
return recipes_list
Explanation:
show_recipes(path): This function shows all the recipes in a category, like showing all the recipes in one of your drawers.
for recipe in recipes_path.glob('*.txt'): This looks for all the files that end with ".txt" (like finding all the recipe papers in a drawer).
Choosing a Recipe
def choose_recipes(a_list):
recipe_choice = 'x'
while not recipe_choice.isnumeric() or int(recipe_choice) not in range(1, len(a_list) + 1):
recipe_choice = input("\nChoose a recipe: ")
return a_list[int(recipe_choice)-1]
Explanation:
choose_recipes(a_list): This function lets you pick a recipe from the list, like choosing which recipe paper to read.
while not recipe_choice.isnumeric() or int(recipe_choice) not in range(1, len(a_list) + 1): This makes sure you pick a number that matches one of the recipes.
Reading a Recipe
def read_recipe(recipe):
print(Path.read_text(recipe))
Explanation:
- read_recipe(recipe): This function reads the recipe you picked, like reading the instructions on your recipe paper.
Creating a New Recipe
def create_recipe(path):
exists = False
while not exists:
print("Write the name of your recipe: ")
recipe_name = input() + '.txt'
print("Write your new recipe: ")
recipe_content = input()
new_path = Path(path, recipe_name)
if not os.path.exists(new_path):
Path.write_text(new_path, recipe_content)
print(f"Your recipe {recipe_name} has been created")
exists = True
else:
print("This recipe already exists")
Explanation:
create_recipe(path): This function lets you write a new recipe and save it, like writing a new recipe on a piece of paper and putting it in the drawer.
if not os.path.exists(new_path): This checks if the recipe already exists, so you don't accidentally make two of the same recipes.
Creating a New Category
def create_category(path):
exists = False
while not exists:
print("Write the name of the new category: ")
category_name = input()
new_path = Path(path, category_name)
if not os.path.exists(new_path):
Path.mkdir(new_path)
print(f"Your category {category_name} has been created")
exists = True
else:
print("This category already exists")
Explanation:
create_category(path): This function lets you make a new category, like adding a new drawer to your cupboard.
Path.mkdir(new_path): This creates the new category folder.
Deleting a Recipe
def delete_recipe(recipe):
Path(recipe).unlink()
print(f"The recipe {recipe.name} has been deleted")
Explanation:
delete_recipe(recipe): This function deletes a recipe, like throwing away a recipe paper you no longer need.
Path(recipe).unlink(): This removes the recipe file.
Returning to the Beginning
def return_begining():
return_choice = 'x'
while return_choice.lower() != 'b':
return_choice = input("\nPress 'b' to return to the menu: ")
Explanation:
- return_begining(): This function pauses and waits for you to press 'b' to go back to the main menu, like asking if you're ready to go back to the first page of the recipe book.
Deleting a Category
def delete_category(category):
Path(category).rmdir()
print(f"The category {category.name} has been removed")
Explanation:
delete_category(category): This function deletes a category, like removing a whole drawer from your cupboard.
Path(category).rmdir(): This removes the category folder.
Main Program Loop
finish_program = False
while not finish_program:
menu = start()
if menu == 1:
my_categories = show_categories(my_path)
my_category = choose_categories(my_categories)
my_recipes = show_recipes(my_category)
my_recipe = choose_recipes(my_recipes)
read_recipe(my_recipe)
return_begining()
elif menu == 2
:
my_categories = show_categories(my_path)
my_category = choose_categories(my_categories)
create_recipe(my_category)
return_begining()
elif menu == 3:
create_category(my_path)
return_begining()
elif menu == 4:
my_categories = show_categories(my_path)
my_category = choose_categories(my_categories)
my_recipes = show_recipes(my_category)
my_recipe = choose_recipes(my_recipes)
delete_recipe(my_recipe)
return_begining()
elif menu == 5:
my_categories = show_categories(my_path)
my_category = choose_categories(my_categories)
delete_category(my_category)
return_begining()
elif menu == 6:
finish_program = True
Explanation:
finish_program = False: We start with the program running.
while not finish_program: This keeps the program running until you decide to stop.
menu = start(): This shows the menu and gets your choice of what to do next.
if menu == 1: If you choose to read a recipe, it shows the categories, lets you pick a recipe, and then reads it.
if menu == 2: If you choose to create a recipe, it lets you pick a category and then write your new recipe.
if menu == 3: If you choose to create a category, it lets you make a new one.
if menu == 4: If you choose to delete a recipe, it lets you pick a recipe to delete.
if menu == 5: If you choose to delete a category, it lets you pick a category to delete.
if menu == 6: If you choose to end the program, it stops the loop and closes the program.
DAY7
attributes.py
class Bird:
wings= True
def __init__(self, color, species):
self.color = color
self.species= species
my_bird = Bird('black','tucan')
print(my_bird.color)
print(my_bird.species)
print(f"My bird is a {my_bird.species} and its color is {my_bird.color}.")
print(Bird.wings)
Explanation:
class Bird: We're creating a blueprint (like a recipe) for a bird. This recipe is called a "class."
wings = True: Every bird has wings, so we set
wingstoTruefor all birds.__init__method: This is like the instructions for when we first make a bird. We can decide the color and species (type) of the bird.my_bird = Bird('black', 'tucan'): We're making a bird called
my_bird, and it's a black tucan.print statements: We are printing out the color, species, and information about the bird, and checking if it has wings.
Output:
black
tucan
My bird is a tucan and its color is black.
True
classes.py
class Bird:
pass
my_bird= Bird()
another_bird= Bird()
print(my_bird)
print(another_bird)
print(type(my_bird))
print(type(another_bird))
Explanation:
class Bird: We are defining a
Birdclass, but it has no special instructions or properties yet. It's like an empty box.pass: This tells Python that we're not adding anything to the
Birdclass right now.my_bird = Bird() and another_bird = Bird(): We're creating two different bird objects,
my_birdandanother_bird, from our Bird class.print statements: We are printing out information about these birds, including what type they are.
Output:
<__main__.Bird object at 0x...>
<__main__.Bird object at 0x...>
<class '__main__.Bird'>
<class '__main__.Bird'>
This tells us that my_bird and another_bird are objects of the Bird class.
inheritance.py
(a) Example of Basic Inheritance:
class Animal:
pass
class Bird(Animal):
pass
print(Bird.__bases__)
print(Animal.__subclasses__())
Explanation:
Inheritance: When one class takes the properties and behavior of another class.
class Animal: This is a general class for all animals.
class Bird(Animal): The
Birdclass is a type ofAnimal. It "inherits" from theAnimalclass.Bird.bases: This tells us what
Birdis inheriting from (in this case,Animal).Animal.subclasses(): This shows us all the classes that have inherited from
Animal.
Output:
(<class '__main__.Animal'>,)
[<class '__main__.Bird'>]
(b) Example of Method Inheritance:
class Animal:
def born(self):
print("This animal has been born.")
class Bird(Animal):
pass
Parrot=Bird()
Parrot.born()
Explanation:
born method in Animal: We have a method called
bornin theAnimalclass that says, "This animal has been born."Bird class inherits Animal:
Birdinherits this method, so it can use it too.Parrot=Bird(): We create a bird called
Parrot.Parrot.born(): Even though
bornis in theAnimalclass, theParrotbird can use it becauseBirdinherits fromAnimal.
Output:
This animal has been born.
(c) Example of Using Inherited Attributes:
class Animal:
def __init__(self, age, color):
self.age = age
self.color = color
def born(self):
print("This animal has been born.")
class Bird(Animal):
pass
Parrot = Bird(2, 'green')
print(Parrot.color)
Explanation:
Animal's
__init__method: This method initializes (sets up) everyAnimalwith an age and color.Bird inherits from Animal:
Birddoesn't have its own__init__, so it uses the one fromAnimal.Parrot = Bird(2, 'green'): We create a
Parrotbird, which is 2 years old and green.print(Parrot.color): Even though
colorwas set in theAnimalclass, we can still use it for ourParrot.
Output:
green
extended_inheritance.py
(a) Extending Inheritance with New Methods:
class Animal:
def __init__(self, age, color):
self.age = age
self.color = color
def born(self):
print("This animal has been born.")
def Talk(self):
print("This animal makes a sound")
class Bird(Animal):
def __init__(self,age,color,altitude):
super().__init__(age, color)
self.altitude = altitude
def talk(self):
print("chirp")
def fly(self, feet):
print(f"This bird flies at {feet} feet high.")
Parrot = Bird(2, 'green', 260)
print(Parrot.color)
Parrot.born()
Parrot.talk()
Parrot.fly(200)
print('\n')
my_animal = Animal(5, 'black')
Explanation:
super(): This allows
Birdto useAnimal's__init__method while adding its own attributes likealtitude.Bird's new methods:
Birdadds its own methods liketalkandfly.Parrot: This is a bird that can use both
Animal's methods (likeborn) and its own (liketalkandfly).
Output:
green
This animal has been born.
chirp
This bird flies at 200 feet high.
(b) Multiple Inheritance Example:
class Father:
def talk(self):
print("Hello")
class Mother:
def laugh(self):
print('ha ha')
def talk(self):
print("How are you?")
class Child(Mother, Father):
pass
class Grandchild(Child):
pass
my_grandchild = Grandchild()
my_grandchild.talk()
my_grandchild.laugh()
print(Grandchild.__mro__)
Explanation:
Multiple Inheritance: A class can inherit from more than one class.
Class Father and Mother: Each has a method
talk, but Mother also has a methodlaugh.Class Child(Mother, Father): The
Childclass inherits from bothMotherandFather.Method Resolution Order (MRO): Determines which method gets called when there's a conflict (like two
talkmethods). Here,Mother's method is chosen because it's listed first.
Output:
How are you?
ha ha
(<class '__main__.Grandchild'>, <class '__main__.Child'>, <class '__main__.Mother'>, <class '__main__.Father'>, <class 'object'>)
methods.py
class Bird:
wings= True
def __init__(self, color, species):
self.color = color
self.species= species
def chirp(self):
print(f'tweet, I am {self.color}.')
def fly(self, feet):
print(f"The bird flies {feet} feet high.")
tweetie = Bird('yellow', 'canary')
tweetie.chirp()
tweetie.fly(200)
Explanation:
chirp method: This makes the bird "chirp" by printing out a message.
fly method: This shows how high the bird can fly.
tweetie = Bird('yellow', 'canary'): We create a bird named
Tweetie.tweetie.chirp() and tweetie.fly(200):
Tweetiechirps and flies.
Output:
tweet, I am yellow.
The bird flies 200 feet high.
special_methods.py
my_list = [1,1,1,1,1]
print(len(my_list))
print(my_list)
class Object:
pass
my_object=Object()
print(my_object)
class CD:
def __init__(self,songwriter,title,song):
self.songwriter= songwriter
self.title= title
self.song= song
def __str__(self):
return f'Album:{self.title} by {self.songwriter}'
def __len__(self):
return self.song
def __del__(self):
print('CD has been deleted')
my_cd=CD('HGFSD','UDGH',24)
print(my_cd)
print(len(my_cd))
print(str(my_cd))
del my_cd
Explanation:
__str__: This special method tells Python how to display our object as a string.__len__: This tells Python what to do when we ask for the length of our object.__del__: This method is called when we delete our object, printing a message.
Output:
5
[1, 1, 1, 1, 1]
<__main__.Object object at 0x....>
Album: UDGH by HGFSD
24
Album: UDGH by HGFSD
CD has been deleted
types_of_methods.py
class Bird:
wings= True
def __init__(self, color, species):
self.color = color
self.species = species
def chirp(self):
print(f'tweet, I am {self.color}.')
def fly(self, feet):
print(f"The bird flies {feet} feet high.")
self.chirp()
def paint_black(self):
self.color = 'black'
print(f"Now the color of the bird is {self.color}")
@classmethod
def lay_eggs(cls, number):
print(f'It lays {number} eggs')
cls.wings = False
print(Bird.wings)
@staticmethod
def look():
print("The bird looks")
Bird.look()
print('\n')
Bird.lay_eggs(4)
print('\n')
tweetie = Bird('yellow', 'canary')
tweetie.paint_black()
print('\n')
tweetie.fly(200)
tweetie.wings = False
print(tweetie.wings)
Explanation:
Instance Methods: These are the regular methods like
chirp,fly, andpaint_blackthat operate on instances of the class.Class Methods:
lay_eggsis a class method that affects the class itself, not just individual birds.Static Methods:
lookis a static method, which is a method that doesn't need any information about the bird itself.
Output:
The bird looks
It lays 4 eggs
False
Now the color of the bird is black
The bird flies 200 feet high.
tweet, I am black.
False
polymorphism.py
Defining the Cow and Sheep Classes:
class Cow:
def __init__(self, name):
self.name = name
def talk(self):
print(self.name + ' moos')
class Sheep:
def __init__(self, name):
self.name = name
def talk(self):
print(self.name + ' bleats')
Cow and Sheep Classes: These two classes represent a cow and a sheep. Each has a
nameattribute and atalkmethod.talkMethod: Thetalkmethod for theCowclass makes the cow moo, while for theSheepclass, it makes the sheep bleat. Even though both classes have atalkmethod, the method behaves differently for each animal.
Creating Instances of Cow and Sheep:
cow1 = Cow("Bahula")
sheep1 = Sheep("Cloud")
- cow1 and sheep1: These are objects (or instances) of the
CowandSheepclasses.cow1is named "Bahula," andsheep1is named "Cloud."
Directly Calling talk on Each Object:
cow1.talk()
sheep1.talk()
- Direct Method Call: Here, you directly tell each animal to talk.
cow1moos, andsheep1bleats.
Output:
Bahula moos
Cloud bleats
OR: Using a List to Loop Through the Animals
animals = [cow1, sheep1]
for animal in animals:
animal.talk()
List of Animals: You put both
cow1andsheep1into a list calledanimals.Looping Through the List: You then loop through each animal in the list and call its
talkmethod. Because of polymorphism, Python automatically knows whichtalkmethod to call depending on whether the current animal is a cow or a sheep.
Output:
Bahula moos
Cloud bleats
OR: Using a Function to Make Any Animal Talk
def animal_talks(animal):
animal.talk()
animal_talks(cow1)
animal_talks(sheep1)
Function
animal_talks: This function takes any animal (whether it's a cow, sheep, or any other animal) and calls itstalkmethod.Calling the Function: When you pass
cow1toanimal_talks, it makes the cow moo. When you passsheep1, it makes the sheep bleat.
Output:
Bahula moos
Cloud bleats
DAY7project.py
1. Class Definition: Person
class Person:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
What is a Class?
- A class is like a blueprint for creating objects. For example, if you think of a class as a cookie cutter, then each cookie you make is an object created from that blueprint.
Person Class:
This is a simple class named
Person. It has an__init__method, which is a special method that runs when we create a newPersonobject.__init__takes two arguments:first_nameandlast_name, which are saved as attributes of thePersonobject.
2. Class Definition: Client (Inherits from Person)
class Client(Person):
def __init__(self, first_name, last_name, account_number, balance=0):
super().__init__(first_name, last_name)
self.account_number = account_number
self.balance = balance
Inheritance:
Clientis a subclass ofPerson. This means thatClientinherits all the attributes and methods fromPerson. In simple terms, aClientis also aPerson, but with some additional properties likeaccount_numberandbalance.
__init__Method inClient:The
__init__method inClientcallssuper().__init__(first_name, last_name)to initialize thefirst_nameandlast_nameattributes by using the__init__method fromPerson.The
Clientclass adds two more attributes:account_numberandbalance.balancehas a default value of0.
3. String Representation Method: __str__
def __str__(self):
return f'Client: {self.first_name} {self.last_name}\nAccount Balance {self.account_number}: ${self.balance}'
Purpose:
The
__str__method is a special method used to define how an object should be represented as a string. It’s what gets printed when you useprint()on the object.In this case, it returns a string showing the client's full name and their account balance.
4. Deposit Method: deposit
def deposit(self, amount_deposit):
self.balance += amount_deposit
print('Deposit accepted')
Purpose:
This method takes an amount as input and adds it to the client’s
balance.After updating the balance, it prints
Deposit accepted.
5. Withdraw Method: withdraw
def withdraw(self, amount_withdraw):
if self.balance >= amount_withdraw:
self.balance -= amount_withdraw
print('Withdraw done')
else:
print('Insufficient funds')
Purpose:
This method checks if the client has enough balance to withdraw the requested amount.
If there’s enough balance, it subtracts the amount from
balanceand printsWithdraw done.If the balance is insufficient, it prints
Insufficient funds.
6. Function: create_client
def create_client():
first_name_ct = input("Enter your name: ")
last_name_ct = input("Your last name: ")
account_number = input("Enter your account number: ")
client1 = Client(first_name_ct, last_name_ct, account_number)
return client1
Purpose:
This function creates a new
Clientobject by asking the user for their first name, last name, and account number.It returns the newly created
Clientobject.
7. Function: start
def start():
my_customer = create_client()
print(my_customer)
option = 0
while option != 'E':
print("Choose: Deposit (D), Withdraw (W), or Exit (E)")
option = input()
if option == 'D':
dep_amount = int(input("Deposit amount: "))
my_customer.deposit(dep_amount)
elif option == 'W':
with_amount = int(input("Withdraw amount: "))
my_customer.withdraw(with_amount)
print(my_customer)
print("Thank you for using Python Bank")
Purpose:
The
startfunction is the main function that runs the program.First, it creates a client using
create_client()and prints the client's details.It enters a loop where the user can choose to deposit (
D), withdraw (W), or exit (E).Depending on the user’s choice, it calls the appropriate method (
depositorwithdraw) and prints the updated client details.When the user chooses to exit (
E), it breaks the loop and prints a thank you message.
8. Starting the Program
start()
Purpose:
- This line calls the
startfunction to begin the program.
- This line calls the
Summary:
The script creates a simple banking system where you can create a client, deposit money, withdraw money, and check the account balance.
It uses concepts like classes, inheritance, methods, and user input to simulate basic banking operations.
DAY8
change_text.py
def all_capitals(text):
return text.title()
print(all_capitals("hello world"))
Explanation:
Function Definition: The function
all_capitalstakes some text and makes the first letter of each word a capital letter.Function Call: The function is called with the text "hello world", so it turns into "Hello World".
Output: "Hello World".
decorators.py
(a)
def lowercase(text):
print(text.lower())
def uppercase(text):
print(text.upper())
my_function = uppercase
my_function("Mahabali Hanuman")
Explanation:
Functions:
lowercasemakes all letters small, anduppercasemakes all letters big.Function Assignment:
my_functionis assigned touppercase, so when you callmy_function, it behaves likeuppercase.Output: "MAHABALI HANUMAN".
(b)
def lowercase(text):
print(text.lower())
def uppercase(text):
print(text.upper())
def one_function(function):
return function
one_function(uppercase('Srila Prabhupada'))
Explanation:
one_function: This function takes another function as input and returns it.
Function Call:
one_function(uppercase('Srila Prabhupada'))calls theuppercasefunction and prints "SRILA PRABHUPADA".
(c)
def change_letters(type):
def lowercase(text):
print(text.lower())
def uppercase(text):
print(text.upper())
if type == 'upp':
return uppercase
elif type=='low':
return lowercase
operation = change_letters('upp')
operation('Krishna')
Explanation:
Nested Functions: Inside
change_letters, there are two functions: one makes letters small, the other makes them big.Decision Making: Based on the input (
upp), the function decides whether to useuppercaseorlowercase.Function Call:
operation('Krishna')prints "KRISHNA" becausechange_letters('upp')returned theuppercasefunction.
(d)
def decorator_greeting(function):
def another_function(word):
print("Hello")
function(word)
print('Goodbye')
return another_function
@decorator_greeting
def uppercase(text):
print(text.upper())
def lowercase(text):
print(text.lower())
lowercase('Radha Rani')
uppercase('Radha Rani')
Explanation:
Decorator:
decorator_greetingis a special function that takes another function and wraps it, adding "Hello" before and "Goodbye" after.Function Call: When you call
uppercase('Radha Rani'), it first says "Hello", prints "RADHA RANI", then says "Goodbye".Output:
lowercase: "radha rani"
uppercase:
Hello RADHA RANI Goodbye
error_handling.py
(a)
def addition():
n1=int(input("The first number: "))
n2=int(input("The second number: "))
print(n1+n2)
print("Thanks for adding"+ n1)
try:
addition()
except:
print("Something is wrong here")
else:
print("You did great")
finally:
print("That's all")
Explanation:
Try-Except Block: It helps catch errors. If something goes wrong, the program doesn't crash, it says "Something is wrong here".
Finally Block: This always runs, no matter what.
Problem: The code has an error in
print("Thanks for adding"+ n1)because you can't add a number and text directly.Output:
The first number: (input) The second number: (input) Error message Something is wrong here That's all
(b)
def addition():
n1=int(input("The first number: "))
n2=int(input("The second number: "))
print(n1+n2)
print("Thanks for adding"+ n1)
try:
addition()
except TypeError:
print("Something is wrong here")
except ValueError:
print("This is not a number")
else:
print("You did great")
finally:
print("That's all")
Explanation:
Multiple Excepts: This handles specific types of errors. For example,
ValueErrorhappens if you input something that isn't a number.Output: Similar to the first example but more specific in handling errors.
(c)
def ask_number():
while True:
try:
number = int(input("Enter a number: "))
except:
print("That is not a number")
else:
print(f"You have entered number {number}")
break
print("Thank You")
ask_number()
Explanation:
Loop with Error Handling: It keeps asking for a number until you enter one correctly.
Output:
Enter a number: (input) If error: "That is not a number" If correct: "You have entered number (number)" Thank You
file1.py
'''
This module prints something
'''
def function():
number1 = 500
print(number1)
function()
Explanation:
Module: A file in Python with code.
Function:
function()prints the number 500.Output: 500.
generators.py
(a)
def my_function():
return 4
def my_generator():
yield 4
print(my_function())
print(my_generator())
print(next(my_generator()))
Explanation:
Function vs Generator:
my_functionreturns a number, butmy_generatorcan give you a number one at a time when you ask for it usingnext().Output:
4 <generator object ...> 4
(b)
def my_function():
my_list=[]
for x in range (1,5):
my_list.append(x*10)
return my_list
def my_generator():
for x in range (1,5):
yield x * 10
print(my_function())
print(my_generator())
g= my_generator()
print(next(g))
print(next(g))
Explanation:
Generator Efficiency:
my_generatorcreates numbers on the fly (10, 20, 30, 40), so it uses less memory thanmy_function.Output:
[10, 20, 30, 40] <generator object ...> 10 20
(c)
def my_generator():
x=1
yield x
x+=1
yield x
x+=1
yield x
g = my_generator()
print(next(g))
print(next(g))
print(next(g))
Explanation:
Step-by-Step Generation: The generator gives you
1, then2, then3each time you ask for the next value.Output:
1 2 3
test.py
import unittest
import change_text
class TestChangeText(unittest.TestCase):
def test_uppercase(self):
word='study'
result=change_text.all_capitals(word)
self.assertEqual(result,'Study')
if __name__ == '__main__':
unittest.main()
Explanation:
Testing:
unittestchecks ifall_capitalschanges "study" to "Study" correctly.Test: If the function works, the test passes; otherwise, it fails.
DAY8project
tickets.py
1. Function Definitions
a. perfume_tickets function:
def perfume_tickets():
for n in range(1, 10000):
yield f'P - {n}'
Explanation:
This function is a generator that creates tickets for perfume products.
How it works: It uses a
forloop to go through numbers from 1 to 9999.Yield: Each time you call
next()on this generator, it gives you a ticket with the format'P - number', wherenumberstarts at 1 and goes up by 1 each time you call it.Example: The first time you call
next(p), it might return"P - 1", and the next time,"P - 2".
b. medicine_tickets function:
def medicine_tickets():
for n in range(1, 10000):
yield f'M - {n}'
Explanation:
This function works exactly like
perfume_tickets, but it generates tickets for medicines.The format of the ticket is
'M - number'.
c. cosmetic_tickets function:
def cosmetic_tickets():
for n in range(1, 10000):
yield f'C - {n}'
Explanation:
- Similarly, this function generates tickets for cosmetics with the format
'C - number'.
- Similarly, this function generates tickets for cosmetics with the format
2. Creating Generator Objects
p = perfume_tickets()
m = medicine_tickets()
c = cosmetic_tickets()
Explanation:
Creating Generators: Here, the code creates instances of the three generators:
pfor perfume tickets.mfor medicine tickets.cfor cosmetic tickets.
These generators are used later in the code to provide tickets when requested.
3. decorator Function
def decorator(product):
print('\n' + '*' * 23)
print('Your number is:')
if product == 'P':
print(next(p))
elif product == 'M':
print(next(m))
else:
print(next(c))
print('Please wait for your turn')
print('*' * 23 + '\n')
Explanation:
This function is called when a ticket is needed.
Choosing the Product: Based on the product type (
'P','M', or'C'), it prints the next ticket from the corresponding generator.Decorative Output: The function adds a decorative border of
'*'around the ticket information to make it look nice.Example: If you choose
'P', it might print something like:*********************** Your number is: P - 1 Please wait for your turn ***********************
main.py
1. Importing the tickets Module
import tickets
Explanation:
- This line imports the
tickets.pymodule so that its functions and variables can be used inmain.py.
- This line imports the
2. ask Function
def ask():
print('Welcome to Python Drugstore')
while True:
print('[P] - Perfume\n[M] - Medicine\n[C] - Cosmetics')
try:
my_product = input('Choose your product: ').upper()
['P', 'M', 'C'].index(my_product)
except ValueError:
print("That is not valid option")
else:
break
tickets.decorator((my_product))
Explanation:
Greeting: It starts by welcoming the user to the Python Drugstore.
Product Choice:
Loop: The code enters a loop where it asks the user to choose a product: Perfume (
P), Medicine (M), or Cosmetics (C).Error Handling: If the user enters something other than
P,M, orC, it prints "That is not a valid option" and asks again.
Calling the Decorator: Once a valid product is chosen, the
decoratorfunction fromtickets.pyis called to print the ticket.
3. start Function
def start():
while True:
ask()
try:
another_ticket = input('Do you want another ticket? [Y] [N]').upper()
['Y', 'N'].index(another_ticket)
except ValueError:
print('Not a valid option')
else:
if another_ticket == 'N':
print('Thanks for visiting our Python Drugstore.')
break
Explanation:
Loop for Multiple Tickets:
After calling the
askfunction, it asks the user if they want another ticket (Yfor Yes,Nfor No).Error Handling: If the user enters something other than
YorN, it prints "Not a valid option" and asks again.
Ending the Loop:
- If the user chooses
N, it prints "Thanks for visiting our Python Drugstore." and exits the loop, ending the program.
- If the user chooses
4. Running the Program
start()
Explanation:
- This line starts the whole process by calling the
startfunction.
- This line starts the whole process by calling the
Summary
tickets.pyhandles generating tickets for different products.main.pymanages user interaction, asking which product they want a ticket for, and then using thetickets.pymodule to generate and print that ticket.The program is user-friendly, ensuring that valid input is received and providing multiple chances to get a ticket for different products.
DAY9
mod_collections.py
(a) Using Counter
from collections import Counter
numbers = [1,2,3,4,5,6,7,8,10,3,1,5,6,6,7]
print(Counter(numbers))
print(Counter('Hare Krishna'))
sentence = 'Simple living High Thinking'
print(Counter(sentence.split()))
series = Counter([1,2,3,4,5,6,7,8,6,9,5,3,9])
print(series.most_common())
print(list(series))
Explanation:
Counter(numbers): Counts how many times each number appears in the list. For example,6appears 3 times.Counter('Hare Krishna'): Counts how many times each letter appears in the string. For example,aappears 2 times.sentence.split(): Splits the sentence into words and counts how many times each word appears.series.most_common(): Shows the most common elements first.list(series): Converts theCounterobject into a list of elements.
(b) Using defaultdict
from collections import defaultdict
my_dict = {'one':'green', 'two' : 'blue', 'three' : 'orange'}
print(my_dict['two'])
print('\n')
my_dict1 = defaultdict(lambda: 'Hare Krishna')
my_dict1['one'] = 'green'
print(my_dict1['two'])
print(my_dict1)
Explanation:
my_dict: A regular dictionary. If you ask for a key not in the dictionary, it gives an error.defaultdict(lambda: 'Hare Krishna'): A dictionary that gives a default value'Hare Krishna'for any key not found.my_dict1['two']: Since'two'is not inmy_dict1, it returns'Hare Krishna'.
(c) Using namedtuple
from collections import namedtuple
my_tuple = (87,34,4)
print(my_tuple[1])
person = namedtuple('person', ['name','height','weight'])
Krishna = person('Krishna',8,70)
print(Krishna.height)
print(Krishna[2])
Explanation:
namedtuple: Creates a special kind of tuple where you can access values by names instead of numbers.Krishna.height: Accesses the height from theKrishnatuple, which is8.Krishna[2]: Accesses the weight from theKrishnatuple by index, which is70.
os_shutil.py
(a) Using os
import os
print(os.getcwd())
file = open('course.txt1','w')
file.write('test.txt')
file.close()
Explanation:
os.getcwd(): Prints the current working directory (where your code is running).open('course.txt1','w'): Creates a new file namedcourse.txt1and opens it for writing.file.write('test.txt'): Writes the text'test.txt'into the file.file.close(): Closes the file when done.
(b) Using shutil
import shutil
shutil.move('course.txt1','C:\\Users\\HP\\OneDrive')
Explanation:
shutil.move(): Moves the filecourse.txt1to the specified folder (OneDrive).
(c) Using send2trash
import send2trash
send2trash.send2trash('course.txt1')
Explanation:
send2trash.send2trash(): Moves the filecourse.txt1to the recycle bin (so it’s not permanently deleted).
(d) Using os.walk
import os
print(os.walk('C:\\Users\\HP\\OneDrive\\Documents\\Wondershare'))
path = 'C:\\Users\\HP\\OneDrive\\Documents\\Wondershare'
for folder, subfolder, file in os.walk(path):
print(f'In folder: {folder}')
print(f'Subfolders are: ')
for sub in subfolder:
print(f'\t{sub}')
print('Files are: ')
for fi in file:
if fi.startswith('2015'):
print(f'\t{fi}')
print('\t')
Explanation:
os.walk(): Goes through all the folders and files in the specified path.Printing: Shows which folders and files are present, and lists files starting with
'2015'.
date_time.py
(a) Using datetime
import datetime
my_time = datetime.time(17, 20)
print(type(my_time))
print(my_time)
print(my_time.hour)
print('\n')
my_day = datetime.date(2025,1,12)
print(my_day)
print(my_day.ctime())
print(my_day.today())
Explanation:
datetime.time(17, 20): Creates a time object for 5:20 PM.datetime.date(2025,1,12): Creates a date object for January 12, 2025.my_day.ctime(): Prints the date in a readable string format.my_day.today(): Prints today’s date.
(b) Modifying datetime
from datetime import datetime
my_date = datetime(2023, 10, 30, 10, 15, 23)
my_date = my_date.replace(month=11)
print(my_date)
Explanation:
datetime(): Creates a date and time object.my_date.replace(month=11): Changes the month to November.
(c) Calculating Days
from datetime import date
birth = date(1995,2,3)
death = date(2025,1,3)
life = death - birth
print(life.days)
Explanation:
date(): Creates date objects for birth and death.death - birth: Calculates the number of days between these two dates.
(d) Calculating Time Difference
from datetime import datetime
wokeup = datetime(2022, 10 , 5, 7,30)
went_to_sleep = datetime(2022, 10, 5, 23, 45)
wakefullness = went_to_sleep - wokeup
print(wakefullness.seconds)
Explanation:
datetime(): Creates date and time objects for waking up and going to sleep.went_to_sleep - wokeup: Calculates the time difference in seconds.
measure_time.py
(a) Measuring Execution Time
import time
def for_test(number):
my_list = []
for num in range(1, number + 1):
my_list.append(num)
return my_list
def while_test(number):
my_list = []
counter = 1
while counter <= number:
my_list.append(counter)
counter +=1
return my_list
beginning = time.time()
for_test(10000)
ending = time.time()
print(ending - beginning)
beginning = time.time()
while_test(10000)
ending = time.time()
print(ending - beginning)
Explanation:
time.time(): Gets the current time in seconds since the epoch (a long time ago).for_test()andwhile_test(): Functions to create a list of numbers usingforandwhileloops.Timing: Measures how long each function takes to run.
(b) Using timeit
import timeit
def while_test(number):
my_list = []
counter = 1
while counter <= number:
my_list.append(counter)
counter +=1
return my_list
declaration = '''
for_test(10)
'''
my_setup = '''
def for_test(number):
my_list = []
for num in range(1, number + 1):
my_list.append(num)
return my_list
'''
length = timeit.timeit(declaration, my_setup, number= 100000)
print(length)
declaration2 = '''
while_test(10)
'''
my_setup2 = '''
def while_test(number):
my_list = []
counter = 1
while counter <= number:
my_list.append(counter)
counter +=1
return my_list
'''
length2 = timeit.timeit(declaration2, my_setup2, number= 100000)
print(length2)
Explanation:
timeit.timeit(): Measures how long it takes to run a piece of code a certain number of times (100,000 here).
math_module.py
import math
result = math.floor(38.343)
result1 = math.ceil(38.343)
result2 = math.pi
result3 = math.log(100,2)
result4 = math.tan(256)
result5 = math.sin(256)
result6 = math.cos(256)
print(result)
print(result2)
print(result3)
print(result4)
print(result5)
print(result6)
Explanation:
math.floor(): Rounds down a number.math.ceil(): Rounds up a number.math.pi: Value of π (Pi).math.log(): Calculates the logarithm (log base 2 here).math.tan(),math.sin(),math.cos(): Trigonometric functions.
regular_expressions.py
(a) Finding Patterns
import re
text = 'if you need help call in this number (222)-223-2345'
word = 'help' in text
print(word)
pattern = 'pencil'
pattern1 = 'help'
search = re.search(pattern, text)
search1 = re.search(pattern1, text)
if search:
print(search)
print(search.span())
print(search.start())
print(search.end())
else:
print("No match found for pattern:", pattern)
if search1:
print(search1)
print(search1.span())
print(search1.start())
print(search1.end())
else:
print("No match found for pattern:", pattern1)
search2 = re.findall(pattern, text)
print(search2)
print(len(search2))
for finding in re.finditer(pattern, text):
print(finding.span())
Explanation:
re.search(): Finds the first occurrence of a pattern in text.re.findall(): Finds all occurrences of a pattern.re.finditer(): Finds all occurrences and gives more details.
(b) Matching Phone Numbers
import re
text = 'call to 234-456-4567 right now'
pattern = r'\d\d\d-\d\d\d-\d\d\d\d'
pattern1 = r'\d{3}-\d{3}-\d{4}'
pattern2 = re.compile(r'(\d{3})-(\d{3})-(\d{4})')
result = re.search(pattern, text)
result1 = re.search(pattern1, text)
result2 = re.search(pattern2, text)
print(result)
print(result1)
print(result2)
print(result.group())
print(result1.group())
print(result2.group())
Explanation:
r'\d\d\d-\d\d\d-\d\d\d\d': Pattern to match phone numbers.re.compile(): Compiles a pattern for reusing.
(c) Checking Passwords
import re
password = input("Password: ")
pattern = r'D{1}\w{7}'
check = re.search(pattern, password)
print(check)
Explanation:
r'D{1}\w{7}': Pattern to match passwords (one uppercase letter followed by seven word characters).
(d) Matching Patterns
import re
text = 'Monday and Sunday this store is closed'
search = re.search(r'Monday|Sunday', text)
search1 = re.search(r'....lose.', text)
search2 = re.search(r'^\D', text)
search3 = re.findall(r'[^\s]', text)
search4 = re.findall(r'[^\s]+', text)
search5 = re.search(r'^\D$', text)
print(search.group() if search else None)
print(search1.group() if search1 else None)
print(search2.group() if search2 else None)
print(''.join(search3))
print(' '.join(search4))
print(search5.group() if search5 else None)
Explanation:
- Patterns: Matching specific words or characters using regular expressions.
compress.py
(a) Creating a Zip File
import zipfile
my_zip = zipfile.ZipFile('file_compressed.zip','w')
my_zip.write('My_Text_A.txt')
my_zip.write('My_Text_B.txt')
my_zip.close()
Explanation:
zipfile.ZipFile('file_compressed.zip','w'): Creates a new zip file.my_zip.write(): Adds files to the zip.
(b) Extracting from a Zip File
import zipfile
open_zip = zipfile.ZipFile('file_compressed.zip','r')
open_zip.extractall()
Explanation:
zipfile.ZipFile('file_compressed.zip','r'): Opens a zip file for reading.open_zip.extractall(): Extracts all files from the zip.
(c) Creating a Zip Archive
import shutil
source_folder = 'C:\\Users\\HP\\OneDrive\\Desktop\\Static'
destination_file = 'all_compressed'
shutil.make_archive(destination_file, 'zip', source_folder)
Explanation:
shutil.make_archive(): Creates a zip archive of a folder.
(d) Unpacking a Zip Archive
import shutil
shutil.unpack_archive('all_compressed.zip', 'extraction_finished', 'zip')
Explanation:
shutil.unpack_archive(): Extracts files from a zip archive.
DAY9project.py
1. Importing Libraries
import shutil
import re
import os
import time
import datetime
from pathlib import Path
import math
shutil: For file operations, like unpacking archives.re: For working with regular expressions.os: For interacting with the operating system (e.g., walking through directories).time: For measuring time intervals.datetime: For working with dates and times.Pathfrompathlib: For handling file system paths.math: For mathematical functions (like rounding).
2. Unpacking the Archive
shutil.unpack_archive('Project+Day+9.zip', 'C:\\Users\\HP\\Downloads', 'zip')
shutil.unpack_archive(): Extracts the contents of'Project+Day+9.zip'to the'C:\\Users\\HP\\Downloads'directory. It expects the file to be in ZIP format.
3. Setting Up Variables
start = time.time()
path = 'C:\\Users\\HP\\Downloads\\My_Big_Directory'
my_pattern = r'N\D{3}-\d{5}'
today = datetime.date.today()
numbers_found = []
files_found = []
start = time.time(): Records the current time to measure how long the search process takes.path: Directory path where the files will be searched.my_pattern: Regular expression pattern to match strings likeN123-45678.today: Stores today’s date.numbers_found: List to store serial numbers found in files.files_found: List to store names of files where serial numbers were found.
4. Defining Functions
(a) find_number() Function
def find_number(file, pattern):
this_file = open(file, 'r')
text = this_file.read()
if re.search(pattern, text):
return re.search(pattern, text)
else:
return ''
find_number(file, pattern): Searches for the givenpatternin the specifiedfile.open(file, 'r'): Opens the file in read mode.text = this_file.read(): Reads the entire content of the file.re.search(pattern, text): Searches for thepatternin the file content.returnre.search(pattern, text): Returns the matched object if found.return '': Returns an empty string if no match is found.
(b) create_lists() Function
def create_lists():
for folder, subfolder, file in os.walk(path):
for a in file:
result = find_number(Path(folder,a ), my_pattern)
if result != '':
numbers_found.append(result.group())
files_found.append(a.title())
create_lists(): Walks through all files in the specified directory and collects serial numbers and filenames.os.walk(path): Iterates through the directory, its subdirectories, and files.for a in file:: Iterates through each file in the current directory.result = find_number(Path(folder,a ), my_pattern): Searches for the pattern in the current file.if result != '':: Checks if a match was found.numbers_found.append(result.group()): Adds the matched serial number tonumbers_found.files_found.append(a.title()): Adds the filename tofiles_foundwith the title case.
(c) show_all() Function
def show_all():
index = 0
print('-' * 50)
print(f'Date of search: {today.month}/{today.day}/{today.year}')
print('\n')
print('FILE\t\t\tSERIAL NUMBER')
print('----\t\t\t-------------')
for a in files_found:
print(f'{a}\t{numbers_found[index]}')
index += 1
print('\n')
print(f'Numbers found: {len(numbers_found)}')
end = time.time()
duration = end - start
print(f'Duration of the search: {math.ceil(duration)} seconds')
print('-' * 50)
show_all(): Displays the results of the search.index = 0: Initializes an index to keep track of the position innumbers_found.print('-' * 50): Prints a line of 50 dashes for formatting.print(f'Date of search: {today.month}/{today.day}/{today.year}'): Prints the date of the search.print('FILE\t\t\tSERIAL NUMBER'): Prints column headers.for a in files_found:: Iterates throughfiles_found.print(f'{a}\t{numbers_found[index]}'): Prints each filename with its corresponding serial number.index += 1: Moves to the next serial number.print(f'Numbers found: {len(numbers_found)}'): Prints the total number of serial numbers found.end = time.time(): Records the end time of the search.duration = end - start: Calculates the duration of the search.print(f'Duration of the search: {math.ceil(duration)} seconds'): Prints the search duration, rounded up to the nearest second.
5. Running the Functions
create_lists()
show_all()
create_lists(): Calls the function to find serial numbers and collect file names.show_all(): Calls the function to display the results of the search.
DAY10
main.py
Importing Libraries
import pygame
import random
import math
from pygame import mixer
pygame: The main library used to create the game, handling graphics, sound, and user input.
random: Used for generating random numbers, such as random enemy positions.
math: Provides mathematical functions like square root, used in collision detection.
mixer: Part of the
pygamelibrary, handles sound effects and background music.
Initializing Pygame
pygame.init()
- Initializes all the Pygame modules, setting up everything needed for the game to run.
Creating the Screen
screen = pygame.display.set_mode((800,600))
- Creates a display window with a size of 800x600 pixels where all game graphics will be rendered.
Title and Icon
pygame.display.set_caption("Space Invasion")
icon = pygame.image.load("Ufo.png")
pygame.display.set_icon(icon)
Sets the title of the game window to "Space Invasion".
Loads an image called "Ufo.png" and sets it as the window icon.
Background Image
background = pygame.image.load("Background.jpg")
- Loads a background image from a file named "Background.jpg".
Adding Music
mixer.music.load('background_music.mp3')
mixer.music.set_volume(150)
mixer.music.play(-1)
Loads a background music file "background_music.mp3".
Sets the volume level to 150.
Plays the music in a loop indefinitely (
-1means it will loop continuously).
Player Variables
img_player = pygame.image.load("Rocket.png")
player_x = 368
player_y = 500
player_x_change = 0
img_player: Loads the player image ("Rocket.png").
player_x: The x-coordinate for the player's position, initially set to 368 pixels.
player_y: The y-coordinate for the player's position, initially set to 500 pixels.
player_x_change: Tracks changes in the player's x-coordinate (left/right movement).
Enemy Variables
img_enemy = []
enemy_x = []
enemy_y = []
enemy_x_change = []
enemy_y_change = []
number_of_enemies = 8
img_enemy: A list to store enemy images.
enemy_x, enemy_y: Lists to store the x and y coordinates of each enemy.
enemy_x_change, enemy_y_change: Lists to store the changes in x and y coordinates for each enemy (movement).
number_of_enemies: The total number of enemies in the game, set to 8.
Initializing Enemies
for e in range(number_of_enemies):
img_enemy.append(pygame.image.load("Enemy.png"))
enemy_x.append(random.randint(0, 736))
enemy_y.append(random.randint(50, 200))
enemy_x_change.append(0.5)
enemy_y_change.append(50)
Loops through the number of enemies and initializes their properties:
Loads the enemy image.
Assigns a random starting x position between 0 and 736 pixels.
Assigns a random starting y position between 50 and 200 pixels.
Sets the horizontal movement speed (
enemy_x_change) to 0.5.Sets the vertical movement step (
enemy_y_change) to 50 pixels.
Bullet Variables
img_bullet = pygame.image.load("Bullet.png")
bullet_x = 0
bullet_y = 500
bullet_x_change = 0
bullet_y_change = 3
visible_bullet = False
img_bullet: Loads the bullet image ("Bullet.png").
bullet_x: The x-coordinate of the bullet, initially set to 0.
bullet_y: The y-coordinate of the bullet, initially set to 500 pixels (same as the player's y-coordinate).
bullet_x_change: The change in x-coordinate (not used here).
bullet_y_change: The speed at which the bullet moves vertically (set to 3 pixels per frame).
visible_bullet: A boolean flag to track if the bullet is currently visible on the screen.
Score Variables
score = 0
my_font = pygame.font.Font('freesansbold.ttf', 32)
text_x = 10
text_y = 10
score: The player's score, initially set to 0.
my_font: Loads a font ("freesansbold.ttf") at size 32 for displaying the score.
text_x, text_y: Coordinates where the score will be displayed on the screen.
End of Game Text
end_font = pygame.font.Font('freesansbold.ttf', 40)
- Loads a font for the "GAME OVER" text, set at size 40.
Final Text Function
def final_text():
my_final_font = end_font.render("GAME OVER", True, (255,255,255))
screen.blit(my_final_font, (200,200))
- final_text(): Renders the "GAME OVER" text on the screen at coordinates (200, 200) using the
end_font.
Show Score Function
def show_score(x, y):
text = my_font.render(f'Score: {score}', True, (255,255,255))
screen.blit(text, (x,y))
- show_score(x, y): Renders the score on the screen at the given coordinates
(x, y)usingmy_font.
Player Function
def player(x,y):
screen.blit(img_player, (x, y))
- player(x, y): Draws the player image at the given
(x, y)coordinates on the screen.
Enemy Function
def enemy(x,y,en):
screen.blit(img_enemy[en], (x, y))
- enemy(x, y, en): Draws the enemy image (from the
img_enemylist) at the given(x, y)coordinates on the screen.
Shoot Bullet Function
def shoot_bullet(x,y):
global visible_bullet
visible_bullet = True
screen.blit(img_bullet, (x+16,y+10))
shoot_bullet(x, y): Draws the bullet at the given
(x, y)coordinates on the screen. The bullet is positioned slightly offset from the player's position.visible_bullet is set to
Trueto indicate that the bullet is now visible on the screen.
Collision Detection Function
def there_is_a_collision(x_1,y_1,x_2,y_2):
distance = math.sqrt(math.pow(x_1 - x_2, 2) + math.pow(y_2 - y_1, 2))
if distance < 27:
return True
else:
return False
- there_is_a_collision(x_1, y_1, x_2, y_2): Checks if two objects (like a bullet and an enemy) have collided by calculating the distance between them. If the distance is less than 27 pixels, it returns
True(indicating a collision); otherwise, it returnsFalse.
Game Loop
is_running = True
while is_running:
- is_running: A flag to control the main game loop. The loop runs as long as
is_runningisTrue.
Background Image
screen.blit(background, (0,0))
- Draws the background image at the top-left corner of the screen.
Event Iteration
for event in pygame.event.get():
- Processes all events (like key presses, mouse movements, etc.) generated during the game.
Closing Event
if event.type == pygame.QUIT:
is_running = False
- Closes the game if the user clicks the close button on the window.
Press Key Event
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player_x_change = -1
if event.key == pygame.K_RIGHT:
player_x_change = 1
if event.key == pygame.K_SPACE:
bullet_sound = mixer.Sound('shot.mp3')
bullet_sound.play()
if not visible_bullet:
bullet_x = player_x
shoot_bullet(bullet_x, bullet_y)
pygame.KEYDOWN: Detects if a key is pressed.
pygame.K_LEFT: Moves the player to the left.
pygame.K_RIGHT: Moves the player to the right.
pygame.K_SPACE: Fires a bullet if it's not already on the screen.
- Plays the bullet firing sound ("shot.mp3").
Release Key Event
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
player_x_change = 0
pygame.KEYUP: Detects if a key is released.
- Stops the player's movement when the left or
right arrow key is released.
Modify Player Location
player_x += player_x_change
- Updates the player's x-coordinate based on the current change (
player_x_change).
Keep Player Inside Screen
if player_x <= 0:
player_x = 0
elif player_x >= 736:
player_x = 736
- Prevents the player from moving off the left or right edge of the screen.
Modify Enemy Location
for enem in range(number_of_enemies):
if enemy_y[enem] > 500:
for k in range(number_of_enemies):
enemy_y[k] = 1000
final_text()
break
enemy_x[enem] += enemy_x_change[enem]
Loops through each enemy, updating their position.
- If an enemy reaches the bottom of the screen (
y > 500), the game ends by displaying the "GAME OVER" text.
- If an enemy reaches the bottom of the screen (
Keep Enemy Inside Screen
if enemy_x[enem] <= 0:
enemy_x_change[enem] = 1
enemy_y[enem] += enemy_y_change[enem]
elif enemy_x[enem] >= 736:
enemy_x_change[enem] = -1
enemy_y[enem] += enemy_y_change[enem]
- Keeps enemies within screen bounds by reversing their direction when they reach the edges and moving them down.
Collision Detection and Response
collision = there_is_a_collision(enemy_x[enem], enemy_y[enem], bullet_x, bullet_y)
if collision:
collision_sound = mixer.Sound('punch.mp3')
collision_sound.play()
bullet_y = 500
visible_bullet = False
score += 1
enemy_x[enem] = random.randint(0, 736)
enemy_y[enem] = random.randint(50, 200)
Checks for a collision between the bullet and an enemy.
If a collision occurs:
Plays the collision sound ("punch.mp3").
Resets the bullet's position and makes it invisible.
Increases the player's score by 1.
Resets the enemy's position to a random location.
Bullet Movement
if bullet_y <= -64:
bullet_y = 500
visible_bullet = False
if visible_bullet:
shoot_bullet(bullet_x, bullet_y)
bullet_y -= bullet_y_change
Moves the bullet upwards each frame.
If the bullet goes off-screen, it resets to the player's position.
If the bullet is visible, it continues to move upwards.
Draw Player
player(player_x, player_y)
- Draws the player on the screen at the current coordinates.
Show Score
show_score(text_x, text_y)
- Displays the current score on the screen.
Update Display
pygame.display.update()
- Updates the screen with all the new drawings and movements for the current frame.
DAY11
new.py
Part (a)
basic_url = 'https://books.toscrape.com/catalogue/page-{}.html'
for p in range(1,11):
print(basic_url.format(p))
Explanation:
basic_url = 'https://books.toscrape.com/catalogue/page-{}.html':- Imagine you have a book website with many pages, and each page shows some books. This line is like a template that tells you how to find those pages. The
{}part is like a blank space that will be filled with the page number later.
- Imagine you have a book website with many pages, and each page shows some books. This line is like a template that tells you how to find those pages. The
for p in range(1,11)::- This line says, "Let's start counting from 1 to 10." We use these numbers to fill in the blank space in the URL so we can look at different pages.
print(basic_url.format(p)):- This line fills in the blank space in the URL with the numbers from 1 to 10 and prints out the full web address for each page. It's like writing down all the addresses where you can find books on the website.
Part (b)
import bs4
import requests
basic_url = 'https://books.toscrape.com/catalogue/page-{}.html'
result = requests.get(basic_url.format('1'))
soup = bs4.BeautifulSoup(result.text, 'html.parser')
print(soup.select('.product_pod'))
print(len(soup.select('.product_pod')))
Explanation:
import bs4andimport requests:- Here, we're bringing in two tools:
requests(to fetch the web page) andbs4(to help us look through the web page).
- Here, we're bringing in two tools:
result = requests.get(basic_url.format('1')):- We're asking the computer to go to the first page of the book website and bring back everything on that page.
soup = bs4.BeautifulSoup(result.text, 'html.parser'):- Once we have the page, we need to organize it in a way that's easy to look through. Think of it as taking all the messy information from the page and putting it neatly into a soup bowl.
print(soup.select('.product_pod')):- We're looking for all the book sections on the page. The
.product_podis like a label that says, "This part is about a book."
- We're looking for all the book sections on the page. The
print(len(soup.select('.product_pod'))):- This counts how many book sections (with the label
.product_pod) we found on the page.
- This counts how many book sections (with the label
Part (c)
import bs4
import requests
basic_url = 'https://books.toscrape.com/catalogue/page-{}.html'
result = requests.get(basic_url.format('1'))
soup = bs4.BeautifulSoup(result.text, 'html.parser')
books = soup.select('.product_pod')
example = books[0].select('.star-rating.Three')
print(example)
print(books)
example1 = books[0].select('a')[1]['title']
print(example1)
Explanation:
books =soup.select('.product_pod'):- We're gathering all the book sections from the page and putting them into a list called
books.
- We're gathering all the book sections from the page and putting them into a list called
example = books[0].select('.star-rating.Three'):- We're looking at the first book in our list and checking if it has a 3-star rating. The
.star-rating.Threeis like a tag that says, "This book has 3 stars."
- We're looking at the first book in our list and checking if it has a 3-star rating. The
print(example):- This shows us whether the first book has that 3-star tag.
print(books):- This prints out all the book sections we found.
example1 = books[0].select('a')[1]['title']:- Here, we're picking out the title of the first book. We look for the second link (
'a'[1]) in the book section and ask for its title.
- Here, we're picking out the title of the first book. We look for the second link (
print(example1):- This prints out the title of the first book.
web_scraping.py
Part (a)
import requests
result = requests.get('https://www.videoschool.com/')
print(type(result))
print(result.text)
Explanation:
import requests:- We're bringing in the
requeststool to help us fetch web pages.
- We're bringing in the
result = requests.get('https://www.videoschool.com/'):- We're asking the computer to go to the
videoschool.comwebsite and bring back everything on the homepage.
- We're asking the computer to go to the
print(type(result)):- This prints out what kind of object
resultis (it's a response object from the server).
- This prints out what kind of object
print(result.text):- This prints out all the text that was found on the
videoschool.comhomepage.
- This prints out all the text that was found on the
Part (b)
import bs4
import requests
result = requests.get('https://www.videoschool.com/')
soup = bs4.BeautifulSoup(result.text, 'html.parser')
print(soup)
print(soup.select('title'))
print(soup.select('p'))
print(len(soup.select('p')))
print(soup.select('h1'))
print(soup.select('title')[0])
print(soup.select('title')[0].getText())
my_p = soup.select('p')[6].getText()
print(my_p)
Explanation:
soup = bs4.BeautifulSoup(result.text, 'html.parser'):- We're taking all the text from the website and organizing it into a soup bowl so we can easily look through it.
print(soup):- This prints out the entire organized content of the page.
print(soup.select('title')):- This looks for the title of the page and prints it out.
print(soup.select('p')):- This looks for all the paragraphs (
<p>) on the page and prints them out.
- This looks for all the paragraphs (
print(len(soup.select('p'))):- This counts how many paragraphs we found on the page.
print(soup.select('h1')):- This looks for all the headings (
<h1>) on the page and prints them out.
- This looks for all the headings (
print(soup.select('title')[0]):- This picks out the first title we found and prints it out.
print(soup.select('title')[0].getText()):- This prints out just the text of the title, without any of the HTML tags.
my_p =soup.select('p')[6].getText():- This selects the seventh paragraph on the page and gets just the text from it.
print(my_p):- This prints out the text from the seventh paragraph.
Part (c)
import bs4
import requests
result = requests.get('https://www.videoschool.com/')
soup = bs4.BeautifulSoup(result.text, 'html.parser')
central_block = soup.select('.fusion-text.fusion-text-1')
central_block1 = soup.select('.fusion-text.fusion-text-1 h5')
central_block2 = soup.select('.fusion-text.fusion-text-1 h5')[0]
print(central_block)
print("\n")
print(central_block1)
print("\n")
print(central_block2)
print("\n")
for h in central_block:
print(h.getText())
print("\n")
for h in central_block1:
print(h.getText())
print("\n")
for h in central_block2:
print(h.getText())
print("\n")
Explanation:
central_block =soup.select('.fusion-text.fusion-text-1'):- We're gathering all parts of the page that have the label
.fusion-text.fusion-text-1.
- We're gathering all parts of the page that have the label
central_block1 =soup.select('.fusion-text.fusion-text-1 h5'):- We're gathering all parts of the page that have the label
.fusion-text.fusion-text-1and also have a heading (<h5>).
- We're gathering all parts of the page that have the label
central_block2 =soup.select('.fusion-text.fusion-text-1 h5')[0]:- We're selecting the first
<h5>heading from the previous list.
- We're selecting the first
print(central_block),print(central_block1),print(central_block2):- These print out the collected sections and headings.
for h in central_block: print(h.getText()):- This goes through each part of
central_blockand prints out just the text.
- This goes through each part of
for h in central_block1: print(h.getText()):- This goes through each part of
central_block1and prints out just the text.
- This goes through each part of
for h in central_block2: print(h.getText())
:
- This prints out just the text from
central_block2.
Part (d)
import bs4
import requests
result = requests.get('https://www.videoschool.com/')
soup = bs4.BeautifulSoup(result.text, 'html.parser')
images = soup.select('img')
print(images)
print("\n")
images1 = soup.select('.img-responsive')
for im in images1:
print(im)
print("\n")
images3 = soup.select('.img-responsive')[0]['src']
print(images3)
print("\n")
images4 = requests.get(images3)
print(images4)
print("\n")
f = open('my_image.jpg', 'wb')
f.write(images4.content)
f.close()
Explanation:
images =soup.select('img'):- We're gathering all the images on the page.
print(images):- This prints out all the image tags.
images1 =soup.select('.img-responsive'):- We're gathering all the images that have the label
.img-responsive.
- We're gathering all the images that have the label
for im in images1: print(im):- This goes through each responsive image and prints it out.
images3 =soup.select('.img-responsive')[0]['src']:- We're picking the first responsive image and getting its source link.
print(images3):- This prints out the link to the first responsive image.
images4 = requests.get(images3):- We're fetching the actual image from the link.
f = open('my_image.jpg', 'wb'):- We're opening a new file called
my_image.jpgwhere we'll save the image.
- We're opening a new file called
f.write(images4.content):- We're saving the image content to the file.
f.close():- We're closing the file to make sure everything is saved properly.
DAY11project.py
1. Imports:
import bs4
import requests
import bs4: This imports the BeautifulSoup library from thebs4package, which is used for parsing HTML and XML documents.import requests: This imports therequestslibrary, which allows you to send HTTP requests in Python, such as getting the HTML content of a webpage.
2. Create a URL template without page number:
basic_url = 'https://books.toscrape.com/catalogue/page-{}.html'
basic_url: This string defines a URL template where{}is a placeholder that will be replaced by the page number during iteration. This template allows you to generate the URLs for each page of the book catalog.
3. Initialize a list to store titles of high-rated books:
high_rated_titles = []
high_rated_titles: This empty list will store the titles of books that have a 4 or 5-star rating.
4. Iterate through pages:
for page in range(1, 51):
for page in range(1,51): This loop iterates over the numbers 1 to 50, representing the pages of the book catalog on the website.
5. Create soup for each page:
url_page = basic_url.format(page)
result = requests.get(url_page)
soup = bs4.BeautifulSoup(result.text, 'html.parser')
url_page = basic_url.format(page): This replaces{}inbasic_urlwith the currentpagenumber, creating the complete URL for the current page.result = requests.get(url_page): This sends an HTTP GET request to the generated URL and stores the response in theresultvariable.soup = bs4.BeautifulSoup(result.text, 'html.parser'): This parses the HTML content of the page (accessible viaresult.text) using BeautifulSoup, making it easier to navigate and search the HTML structure.
6. Select data of books on the page:
books = soup.select('.product_pod')
books =soup.select('.product_pod'): This selects all HTML elements with the classproduct_pod, which represent individual book entries on the page. The result is a list of these elements.
7. Iterate through each book:
for book in books:
for book in books: This loop iterates through each book entry in thebookslist.
8. Check if the book has a 4 or 5-star rating:
if len(book.select('.star-rating.Four')) != 0 or len(book.select('.star-rating.Five')) != 0:
if len(book.select('.star-rating.Four')) != 0 or len(book.select('.star-rating.Five')) != 0: This checks if the current book has a 4-star rating (.star-rating.Four) or a 5-star rating (.star-rating.Five). If the book has either rating, the length of the selected elements will be greater than 0, meaning the condition is true.
9. Store the title of the book:
book_title = book.select('a')[1]['title']
book_title =book.select('a')[1]['title']: This extracts the title of the book. Here’s how it works:book.select('a')selects all<a>(anchor/link) tags within thebookelement.[1]selects the second<a>tag (as Python uses 0-based indexing).['title']extracts the value of thetitleattribute, which contains the book's title.
10. Add the book title to the list:
high_rated_titles.append(book_title)
high_rated_titles.append(book_title): This adds the title of the high-rated book to thehigh_rated_titleslist.
11. Print the titles of all high-rated books:
for b in high_rated_titles:
print(b)
for b in high_rated_titles:: This loop iterates through each title in thehigh_rated_titleslist.print(b): This prints the title of each high-rated book to the console.
DAY12
my_restaurant.py
1. Importing Libraries
from tkinter import *
import random
import datetime
from tkinter import filedialog, messagebox
from tkinter import *: Imports all classes and functions from the Tkinter library, which is used to create the GUI.import random: Imports therandommodule for generating random numbers (used for generating invoice numbers).import datetime: Imports thedatetimemodule for working with dates and times.from tkinter import filedialog, messagebox: Imports specific Tkinter modules for file dialogs and message boxes.
2. Global Variables
operator = ''
food_price = [1.32, 1.65, 2.31, 3.22, 1.22, 1.99, 2.05, 2.65]
drink_price = [0.25, 0.99, 1.21, 1.54, 1.08, 1.10, 2.00, 1.58]
dessert_price = [1.54, 1.68, 1.32, 1.97, 2.55, 2.14, 1.94, 1.74]
operator: A global variable used to keep track of the calculator's current input.food_price,drink_price,dessert_price: Lists that store prices for different categories of items.
3. Calculator Functions
click_button(character)
def click_button(character):
global operator
operator = operator + character
calculator_display.delete(0, END)
calculator_display.insert(END, operator)
Purpose: Updates the display of the calculator when a button is clicked.
Process:
Appends the clicked character to
operator.Updates the calculator display with the new
operator.
delete_all()
def delete_all():
global operator
operator = ''
calculator_display.delete(0, END)
- Purpose: Clears the calculator display and resets the
operator.
get_result()
def get_result():
global operator
result = str(eval(operator))
calculator_display.delete(0, END)
calculator_display.insert(0, result)
operator = ''
Purpose: Evaluates the expression entered in the calculator and displays the result.
Process:
Uses
eval()to compute the result of theoperator.Displays the result and resets the
operator.
4. Order Processing Functions
review_check()
def review_check():
x = 0
for b in food_box:
if food_variables[x].get() == 1:
food_box[x].config(state=NORMAL)
if food_box[x].get() == '0':
food_box[x].delete(0, END)
food_box[x].focus()
else:
food_box[x].config(state=DISABLED)
food_text[x].set('0')
x += 1
x = 0
for b in drink_box:
if drink_variables[x].get() == 1:
drink_box[x].config(state=NORMAL)
if drink_box[x].get() == '0':
drink_box[x].delete(0, END)
drink_box[x].focus()
else:
drink_box[x].config(state=DISABLED)
drink_text[x].set('0')
x += 1
x = 0
for b in dessert_box:
if dessert_variables[x].get() == 1:
dessert_box[x].config(state=NORMAL)
if dessert_box[x].get() == '0':
dessert_box[x].delete(0, END)
dessert_box[x].focus()
else:
dessert_box[x].config(state=DISABLED)
dessert_text[x].set('0')
x += 1
Purpose: Updates the state of the input fields based on the checkboxes.
Process:
Enables or disables input fields based on whether the corresponding checkbox is selected.
Clears the input field if it is disabled.
total_calculation()
def total_calculation():
food_subtotal = 0
p = 0
for unit in food_text:
food_subtotal = food_subtotal + (float(unit.get()) * food_price[p])
p += 1
drink_subtotal = 0
p = 0
for unit in drink_text:
drink_subtotal = drink_subtotal + (float(unit.get()) * drink_price[p])
p += 1
dessert_subtotal = 0
p = 0
for unit in dessert_text:
dessert_subtotal = dessert_subtotal + (float(unit.get()) * dessert_price[p])
p += 1
my_subtotal = food_subtotal + dessert_subtotal + drink_subtotal
my_taxes = my_subtotal * 0.11
my_total = my_subtotal + my_taxes
food_cost_var.set(f'$ {round(food_subtotal, 2)}')
drink_cost_var.set(f'$ {round(drink_subtotal, 2)}')
dessert_cost_var.set(f'$ {round(dessert_subtotal, 2)}')
subtotal_var.set(f'$ {round(my_subtotal, 2)}')
taxes_var.set(f'$ {round(my_taxes, 2)}')
total_var.set(f'$ {round(my_total, 2)}')
Purpose: Calculates the subtotal, taxes, and total cost of the order.
Process:
Computes the subtotal for food, drinks, and desserts.
Calculates taxes (11% of the subtotal).
Updates the display fields with the calculated amounts.
create_invoice()
def create_invoice():
invoice_text.delete(1.0, END)
invoice_number = f'N# - {random.randint(1000, 9999)}'
my_date = datetime.datetime.now()
invoice_date = f'{my_date.month}/{my_date.day}/{my_date.year} - {my_date.hour}:{my_date.minute}'
invoice_text.insert(END, f'Information: \t{invoice_number}\t\t{invoice_date}')
invoice_text.insert(END, f'*' * 47 + '\n')
invoice_text.insert(END, f'Items\t\tQuantity\tItems Cost\n')
invoice_text.insert(END, f'-' * 54 + '\n')
x = 0
for f in food_text:
if f.get() != '0':
invoice_text.insert(END, f'{food_list[x]}\t\t{f.get()}\t'
f'$ {int(f.get()) * food_price[x]}\n')
x += 1
x = 0
for d in drink_text:
if d.get() != '0':
invoice_text.insert(END, f'{drink_list[x]}\t\t{d.get()}\t'
f'$ {int(d.get()) * drink_price[x]}\n')
x += 1
x = 0
for e in dessert_text:
if e.get() != '0':
invoice_text.insert(END, f'{dessert_list[x]}\t\t{e.get()}\t'
f'$ {int(e.get()) * dessert_price[x]}\n')
x += 1
invoice_text.insert(END, f'*' * 47 + '\n')
invoice_text.insert(END, f'Food Subtotal: \t\t\t{food_cost_var.get()}\n')
invoice_text.insert(END, f'Drink Subtotal: \t\t\t{drink_cost_var.get()}\n')
invoice_text.insert(END, f'Dessert Subtotal: \t\t\t{dessert_cost_var.get()}\n')
invoice_text.insert(END, f'-' * 54, '\n')
invoice_text.insert(END, f'Subtotal: \t\t\t{subtotal_var.get()}\n')
invoice_text.insert(END, f'Taxes: \t\t\t{taxes_var.get()}\n')
invoice_text.insert(END, f'Total: \t\t\t{total_var.get()}\n')
invoice_text.insert(END, f'*' * 47 + '\n')
invoice_text.insert(END, f'See you soon')
Purpose: Creates an invoice with details of the order and its total cost.
Process:
Generates an invoice number and date.
Lists ordered items, their quantities, and costs.
Displays subtotal, taxes, and total cost.
save_invoice()
def save_invoice():
invoice_info = invoice_text.get(1.0, END)
my_file = filedialog.asksaveasfile(mode='w', defaultextension='.txt')
my_file.write(invoice_info)
my_file.close()
messagebox.showinfo('Notification', 'Your invoice has
been saved.')
Purpose: Saves the generated invoice to a text file.
Process:
Opens a file dialog to select the save location.
Writes the invoice text to the selected file.
Displays a confirmation message.
reset_all()
def reset_all():
for unit in food_text:
unit.set('0')
for unit in drink_text:
unit.set('0')
for unit in dessert_text:
unit.set('0')
food_cost_var.set('$ 0')
drink_cost_var.set('$ 0')
dessert_cost_var.set('$ 0')
subtotal_var.set('$ 0')
taxes_var.set('$ 0')
total_var.set('$ 0')
for box in food_box:
box.deselect()
for box in drink_box:
box.deselect()
for box in dessert_box:
box.deselect()
food_box[0].config(state=NORMAL)
drink_box[0].config(state=NORMAL)
dessert_box[0].config(state=NORMAL)
food_box[0].focus()
invoice_text.delete(1.0, END)
Purpose: Resets all input fields and selections to their default state.
Process:
Sets all input fields to '0'.
Resets all cost fields to '$ 0'.
Deselects all checkboxes and enables all input fields.
Clears the invoice text.
5. Main GUI Setup
root = Tk()
root.title('My Restaurant - Invoicing System')
root.geometry('950x700')
root.config(bg='light blue')
root = Tk(): Creates the main application window.root.title('My Restaurant - Invoicing System'): Sets the title of the window.root.geometry('950x700'): Sets the size of the window.root.config(bg='light blue'): Sets the background color of the window.
6. Frames and Layout
Top Panel
top_frame = Frame(root, bg='light blue', pady=20, width=950, height=100)
top_frame.pack(side=TOP)
title_label = Label(top_frame, text='Welcome to My Restaurant', font=('arial', 40, 'bold'), bg='light blue', fg='black')
title_label.grid(row=0, column=0, padx=20)
top_frame: A frame at the top of the window for the title.title_label: Displays the title of the application.
Left Panels (Food, Drink, Dessert)
- Food Panel
food_panel = Frame(root, bg='light blue', width=500, height=500)
food_panel.pack(side=LEFT)
food_list = ['Burger', 'Pizza', 'Hot Dog', 'French Fries', 'Sandwich', 'Chicken Wings', 'Pasta', 'Salad']
food_price = [1.32, 1.65, 2.31, 3.22, 1.22, 1.99, 2.05, 2.65]
food_box = []
food_text = []
food_variables = []
for i in range(8):
food_variables.append(IntVar())
food_box.append(Checkbutton(food_panel, text=food_list[i], variable=food_variables[i], onvalue=1, offvalue=0, bg='light blue', command=review_check))
food_box[i].grid(row=i, column=0, padx=10, pady=10, sticky=W)
food_text.append(StringVar())
Entry(food_panel, textvariable=food_text[i], state=DISABLED, width=10).grid(row=i, column=1, padx=10, pady=10)
Purpose: Creates checkboxes and entry fields for food items.
Process:
Creates a list of food items and their prices.
Adds checkboxes for each food item.
Adds entry fields to input quantities.
Drink and Dessert Panels: Similar setup as the food panel.
7. Calculator Panel
calc_frame = Frame(root, bg='light blue', width=300, height=500)
calc_frame.pack(side=RIGHT)
calculator_display = Entry(calc_frame, font=('arial', 20, 'bold'), bg='white', fg='black', bd=20, width=18, borderwidth=2, justify=RIGHT)
calculator_display.grid(row=0, column=0, columnspan=4)
button_texts = ['7', '8', '9', '/', '4', '5', '6', '*', '1', '2', '3', '-', '0', '.', '=', '+']
for i, text in enumerate(button_texts):
button = Button(calc_frame, text=text, padx=20, pady=20, font=('arial', 18, 'bold'), command=lambda t=text: click_button(t))
button.grid(row=i//4 + 1, column=i%4)
Button(calc_frame, text='C', padx=20, pady=20, font=('arial', 18, 'bold'), command=delete_all).grid(row=5, column=0)
Button(calc_frame, text='=', padx=20, pady=20, font=('arial', 18, 'bold'), command=get_result).grid(row=5, column=3)
Purpose: Creates a calculator with buttons for digits, operations, and functions.
Process:
Adds buttons for calculator operations and numbers.
Configures button commands to handle input and calculations.
8. Invoice Panel
invoice_frame = Frame(root, bg='light blue', width=300, height=500)
invoice_frame.pack(side=BOTTOM, fill=BOTH)
invoice_text = Text(invoice_frame, font=('arial', 12, 'bold'), bg='white', fg='black', width=45, height=20, bd=10, padx=10, pady=10)
invoice_text.grid(row=0, column=0)
Button(invoice_frame, text='Save Invoice', font=('arial', 12, 'bold'), command=save_invoice).grid(row=1, column=0, pady=10)
Button(root, text='Total', font=('arial', 12, 'bold'), command=total_calculation).pack(side=LEFT, padx=10)
Button(root, text='Reset', font=('arial', 12, 'bold'), command=reset_all).pack(side=RIGHT, padx=10)
Purpose: Creates a text area for the invoice and buttons to save and reset.
Process:
Adds a
Textwidget for displaying the invoice.Adds buttons to calculate totals, reset the form, and save the invoice.
9.
# Prevent window from closing
application.mainloop()
application.mainloop() is what keeps your Tkinter window open and interactive. It continually checks for user inputs and updates the GUI accordingly. Without it, the window would close immediately after being displayed.
Conclusion
This script is a complete restaurant invoicing system with a graphical interface. It allows users to select food, drinks, and desserts, calculate costs, and generate invoices. The code uses Tkinter to create a functional GUI application with various interactive elements.
DAY13
virtual_assistant.py
1. Importing Necessary Libraries
import pyttsx3
import speech_recognition as sr
import pywhatkit
import yfinance as yf
import pyjokes
import webbrowser
import datetime
import wikipedia
pyttsx3: This library allows the assistant to convert text to speech.speech_recognition: Enables the assistant to capture and recognize voice input.pywhatkit: A Python library to perform tasks like searching on Google or playing YouTube videos.yfinance: Used to fetch stock market data.pyjokes: Provides a collection of programming jokes.webbrowser: Allows opening web pages in a browser.datetime: Used to get the current date and time.wikipedia: Fetches summaries from Wikipedia.
2. Transform Audio into Text
def transform_audio_into_text():
r = sr.Recognizer()
with sr.Microphone() as source:
r.pause_threshold = 0.8
print("You can now speak")
audio = r.listen(source)
try:
request = r.recognize_google(audio, language="eng-gb")
print("You said " + request)
return request
except sr.UnknownValueError:
print("Oops! I didn't understand what you said")
return "I am still waiting"
except sr.RequestError:
print("Oops! there is no service")
return "I am still waiting"
except:
print("Oops! Something went wrong")
return "I am still waiting"
sr.Recognizer(): Creates a Recognizer instance to process audio.sr.Microphone(): Opens the microphone to listen for input.r.listen(source): Captures the audio.r.recognize_google(): Uses Google's speech recognition API to convert audio to text.Error Handling: Various exceptions handle errors like unrecognized speech or connection issues.
3. Text-to-Speech Function
def speak(message):
engine = pyttsx3.init()
engine.say(message)
engine.runAndWait()
pyttsx3.init(): Initializes the text-to-speech engine.engine.say(message): Converts the textmessageto speech.engine.runAndWait(): Waits until the speaking is done.
4. Informing the Day of the Week
def ask_day():
day = datetime.date.today()
week_day = day.weekday()
calendar = {0: 'Monday', 1: 'Tuesday', 2: 'Wednesday', 3:'Thursday', 4:'Friday', 5:'Saturday', 6:'Sunday'}
speak(f'Today is {calendar[week_day]}')
datetime.date.today(): Retrieves today's date.day.weekday(): Converts the date into a weekday index (0 for Monday, 6 for Sunday).calendar: A dictionary mapping indexes to day names.speak(): The assistant announces the current day.
5. Informing the Time
def ask_time():
time = datetime.datetime.now()
time = f'At this moment it is {time.hour} hours and {time.minute} minutes'
speak(time)
datetime.datetime.now(): Retrieves the current time.time.hourandtime.minute: Extracts the hour and minute from the current time.speak(): The assistant announces the current time.
6. Initial Greeting
def initial_greeting():
'''Say greeting'''
# speak('Jay Sri Rama, Hanuman')
initial_greeting(): This function is commented out, but it is meant to deliver an initial greeting.
7. Main Function of the Assistant
def my_assistant():
initial_greeting()
go_on = True
while go_on:
my_request = transform_audio_into_text().lower()
if 'open youtube' in my_request:
speak('Here you go')
webbrowser.open('https://www.youtube.com')
continue
elif 'open browser' in my_request:
speak('Of course, I am on it')
webbrowser.open('https://www.google.com')
continue
elif 'what time it is' in my_request:
ask_time()
continue
elif 'what day it is' in my_request:
ask_day()
continue
elif 'do a wikipedia search for' in my_request:
speak('I am looking for it')
my_request = my_request.replace('do a wikipedia search for','')
answer = wikipedia.summary(my_request, sentences=1)
speak('according to wikipedia: ')
speak(answer)
continue
elif 'search the internet for' in my_request:
speak('of course, right now')
my_request = my_request.replace('search the internet for','')
pywhatkit.search(my_request)
speak('this is what I found')
continue
elif 'play' in my_request:
speak("oh, what a great idea! I'll play it right now")
pywhatkit.playonyt(my_request)
continue
elif 'joke' in my_request:
speak(pyjokes.get_joke())
continue
elif 'stock price' in my_request:
share = my_request.split()[-2].strip()
portfolio = {'apple': 'APPL', 'amazon': 'AMZN', 'google': 'GOOGL'}
try:
searched_stock = portfolio[share]
searched_stock = yf.Ticker(searched_stock)
price = searched_stock.info['regularMarketPrice']
speak(f'I fount it! The price of {share} is {price}')
continue
except:
speak("I am sorry, but I didn't find it")
continue
elif 'goodbye' in my_request:
speak('I am going to take rest. Let me know if you need any help')
break
my_assistant()
initial_greeting(): (Optional) Initiates a greeting.go_on = True: Keeps the assistant running in a loop.transform_audio_into_text().lower(): Listens for commands and converts them to lowercase for comparison.Various
ifconditions: Checks the user’s command and performs the corresponding task:Open YouTube or Browser: Opens the respective websites.
Tell Time or Day: Uses
ask_time()andask_day()functions.Wikipedia Search: Searches Wikipedia and returns a summary.
Play YouTube Video: Plays a video using the
pywhatkitlibrary.Tell a Joke: Retrieves and speaks a joke.
Fetch Stock Price: Looks up the price of a stock from a predefined portfolio.
Goodbye: Ends the loop and stops the assistant.
This virtual assistant is a powerful tool that can perform a variety of tasks through voice commands, making it a handy project for learning how to integrate multiple Python libraries for real-world applications.
DAY14
facial_recognizer.py
This script is designed to recognize and compare faces from two images. It uses the cv2 (OpenCV) library for image processing and face_recognition for face detection and encoding.
1. Importing Libraries
import cv2
import face_recognition as fr
cv2: OpenCV is a library used for computer vision tasks. Here, it's used for image processing.face_recognition: This library is built on top ofdliband provides tools for recognizing and manipulating faces.
2. Loading Images
# Load Images
control_picture = fr.load_image_file('PictureA.jpg')
test_picture = fr.load_image_file('PictureB.jpg')
fr.load_image_file(): Loads an image from a file into a format that can be processed. Here, two images are loaded:PictureA.jpgandPictureB.jpg.
3. Converting Images to RGB
# Transform images into rgb
control_picture = cv2.cvtColor(control_picture, cv2.COLOR_BGRA2BGR)
test_picture = cv2.cvtColor(test_picture, cv2.COLOR_BGRA2BGR)
cv2.cvtColor(): Converts the color space of the images from BGRA (Blue, Green, Red, Alpha) to BGR (Blue, Green, Red), which is required for face recognition.
4. Locating Faces in Images
# Locate control face
face_A_location = fr.face_locations(control_picture)[0]
coded_face_A = fr.face_encodings(control_picture)[0]
# Locate test face
face_B_location = fr.face_locations(control_picture)[0]
coded_face_B = fr.face_encodings(control_picture)[0]
fr.face_locations(): Detects faces in the image and returns their locations as a list of tuples (top, right, bottom, left). The[0]index is used to select the first face found.fr.face_encodings(): Converts the face in the image to a 128-dimensional encoding, which is a unique identifier for that face.
5. Drawing Rectangles Around Faces
# Show rectangles
cv2.rectangle(control_picture,
(face_A_location[3], face_A_location[0]),
(face_A_location[1], face_A_location[2]),
(0, 255, 0),
2)
# Show rectangles
cv2.rectangle(control_picture,
(face_A_location[3], face_A_location[0]),
(face_A_location[1], face_A_location[2]),
(0, 255, 0),
2)
cv2.rectangle(test_picture,
(face_B_location[3], face_B_location[0]),
(face_B_location[1], face_B_location[2]),
(0, 255, 0),
2)
cv2.rectangle(): Draws rectangles around the detected faces in both images. The rectangle is drawn from the top-left corner(x1, y1)to the bottom-right corner(x2, y2). The color(0, 255, 0)is green, and the thickness of the rectangle is 2 pixels.
6. Comparing Faces
# Perform comparison
result = fr.compare_faces([coded_face_A], coded_face_B)
# Measurement of distances
distance = fr.face_distance([coded_face_A], coded_face_B)
fr.compare_faces(): Compares the encoded faces to see if they match. It returns a list ofTrueorFalse.fr.face_distance(): Computes the Euclidean distance between the face encodings. A smaller distance means a closer match.
7. Displaying the Result
# Show results
cv2.putText(test_picture,
f'{result} {distance.round(2)}',
(50, 50),
cv2.FONT_HERSHEY_COMPLEX,
1,
(0, 255, 0),
2)
cv2.putText(): Adds the result (True/False) and the distance on the test image at position(50, 50)with the specified font, size, color, and thickness.
8. Displaying the Images
# Show images
cv2.imshow('My Control Picture', control_picture)
cv2.imshow('My Test Picture', test_picture)
# Keep the program working
cv2.waitKey(0)
cv2.imshow(): Displays the images with rectangles and text.cv2.waitKey(0): Keeps the window open until a key is pressed.
work_attendance.py
This script uses facial recognition to mark attendance by comparing the faces captured by a webcam with pre-stored images of employees.
1. Importing Libraries
import cv2
import face_recognition as fr
import os
import numpy
from datetime import datetime
cv2,face_recognition: As explained before, used for image processing and face recognition.os: Used for interacting with the operating system (e.g., to list files).numpy: Used for numerical operations, especially with arrays.datetime: Used to fetch the current date and time.
2. Loading Employee Images
# Create database
path = 'Employees'
my_images = []
employees_names = []
employees_list = os.listdir(path)
for name in employees_list:
this_image = cv2.imread(f'{path}\\{name}')
my_images.append(this_image)
employees_names.append(os.path.splitext(name)[0])
print(employees_list)
path = 'Employees': Specifies the directory containing the employee images.os.listdir(path): Lists all files in theEmployeesdirectory.cv2.imread(): Reads each image file.os.path.splitext(name)[0]: Extracts the file name without the extension and adds it to theemployees_nameslist.
3. Encoding Employee Faces
# Encode images
def encode(images):
# Create new list
encoded_list = []
# Convert all images to rgb
for image in images:
image = cv2.cvtColor(image, cv2.COLOR_BGRA2BGR)
# Encode
encoded = fr.face_encodings(image)[0]
# Add to the list
encoded_list.append(encoded)
# Return encoded list
return encoded_list
encode(): A function that takes a list of images, converts them to RGB, and encodes the faces. The encoded faces are stored inencoded_list.
4. Recording Attendance
# Record attendance
def record_attendance(person):
f = open('register.csv', 'r+')
data_list = f.readlines()
register_names = []
for line in data_list:
newcomer = line.split(',')
register_names.append(newcomer[0])
if person not in register_names:
right_now = datetime.now()
string_right_now = right_now.strftime('%H:%M:%S')
f.writelines(f'\n{person},{string_right_now}')
record_attendance(): Opens a CSV file namedregister.csvto log attendance. It checks if the person is already recorded for the day. If not, it logs the current time against the person's name.
5. Capturing and Processing Webcam Image
encoded_employees_list = encode(my_images)
# Take a webcam picture
capture = cv2.VideoCapture(0, cv2.CAP_DSHOW)
# Read the captured image
success, image = capture.read()
if not success:
print('Capture could not be taken')
else:
# Recognise a face in that capture
captured_face = fr.face_locations(image)
# Encode the captured face
encoded_captured_face = fr.face_encodings(image, captured_face)
cv2.VideoCapture(0, cv2.CAP_DSHOW): Opens the webcam.capture.read(): Captures an image from the webcam.fr.face_locations(): Detects faces in the captured image.fr.face_encodings(): Encodes the detected faces.
6. Matching Captured Face with Database
# Search for a match
for face, location_face in zip(encoded_captured_face, captured_face):
matches = fr.compare_faces(encoded_employees_list, face)
distances = fr.face_distance(encoded_employees_list, face)
print(distances)
match_index = numpy.argmin(distances)
# Show coincidences if any
if distances[match_index] > 0.6:
print('Does not match any of our employees')
else:
# Search for the name of the employee found
employees_name = employees_names[match_index]
fr.compare_faces(): Compares the captured face with all encoded faces in the database.numpy.argmin(distances): Finds the index of the closest match (small
est distance).
distances[match_index] > 0.6: If the minimum distance is greater than 0.6, it's considered not a match; otherwise, the employee's name is retrieved.
7. Displaying and Logging the Match
# Display the rectangle and name
cv2.rectangle(image,
(location_face[3], location_face[0]),
(location_face[1], location_face[2]),
(0, 255, 0),
2)
cv2.rectangle(image,
(location_face[3], location_face[2] - 35),
(location_face[1], location_face[2]),
(0, 255, 0),
cv2.FILLED)
cv2.putText(image,
employees_name,
(location_face[3] + 6, location_face[2] - 6),
cv2.FONT_HERSHEY_COMPLEX,
1,
(0, 255, 0),
2)
# Register the attendance
record_attendance(employees_name)
cv2.rectangle(): Draws rectangles around the detected face and a filled rectangle for the name.cv2.putText(): Displays the name of the employee on the image.record_attendance(employees_name): Logs the employee's name and time in the attendance register.
8. Displaying the Image
# Show the capture
cv2.imshow('My webcam capture', image)
cv2.waitKey(0)
cv2.imshow(): Displays the captured image with the detected face and employee name.cv2.waitKey(0): Keeps the window open until a key is pressed.
Conclusion
These scripts utilize facial recognition technology to compare and identify faces in images and videos. The first script (facial_recognizer.py) focuses on comparing two images, while the second script (work_attendance.py) captures a real-time image from a webcam, compares it with a database of known faces, and logs attendance based on matches.
DAY 15
Check out my Github account for the documentation...!
DAY 16
Here in DAY 16 a website is being designed using Django
Used virtual environments in Python and Django. Configured URLs, created table tasks, and other necessities
Detailed documentation on DAY 16 will come soon... Work in Progress!!!