Posts

Showing posts from May, 2025

Exercise 2 (Time Module)

#Create a python program capable of gretting you with Good Morning, Good Afternoon, and Good Evening. Your program should use time module to get the current hour. #Solution 1 import time t = time.strftime('%H: %M: %S') timestamp = int(time. strftime('%H')) minutes = int(time. strftime('%M')) seconds = int(time. strftime('%S')) print("Hours", "=", timestamp) print("Minutes", "=", minutes) print("Seconds", "=", seconds) if timestamp >0 and timestamp <12:     print("Good Morning") elif timestamp >=12 and timestamp <17:     print("Good Afternoon") elif timestamp >=17 and timestamp <20:     print("Good Evening") else:     print("Good Night") # output =  # Hours = 21 # Minutes = 22 # Seconds = 38 # Good Night

Basic Calculator(Exercise 1)

num1 = int(input("Enter first number")) num2 = int(input("Enter second number")) operator = str(input("Enter the operator")) if operator == "+":     print(num1 + num2) elif operator == "-":     print(num1 - num2) elif operator == "*":     print(num1 * num2) elif operator == "/":     print(num1 / num2) elif operator == "%":     print(num1 % num2) elif operator == "//":     print(num1 // num2) else:     print("Invalid Input") #output =  # Enter first number100 # Enter second number20 # Enter the operator+ # 120 # output = # Enter first number100 # Enter second number20 # Enter the operator- # 80 # output =  # Enter first number100 # Enter second number20 # Enter the operator* # 2000 # output = # Enter first number100 # Enter second number20 # Enter the operator/ # 5.0 # output = # Enter first number100 # Enter second number20 # Enter the operator% # 0

Raising Custom Error

''' Raising Custom Error: In Python, we can raise custom error by using the "raise" keyword. ''' #Example: a = int(input("Enter a value between 5 and 9")) if(a<5 or a>9):     raise ValueError("Value should be between 5 and 9") # output = # Enter a value between 5 and 9 10 # Traceback (most recent call last): #   File "c:\Users\sindh\OneDrive\Desktop\Python Codes\Raising Custom Error.py", line 4, in <module> #     raise ValueError("Value should be between 5 and 9") # ValueError: Value should be between 5 and 9 salary = int(input("Enter the salary amount: ")) if not 50000 < salary < 70000:     raise ValueError("Not a valid salary") # output = # Enter the salary amount: 10000 # Traceback (most recent call last): #   File "c:\Users\sindh\OneDrive\Desktop\Python Codes\Raising Custom Error.py", line 18, in <module> #     raise ValueError("Not a valid salary...

Finally Clause

''' Finally Clause: It is also a part of exception handling. When we use exception using try and except block, we can include a finally block at the end. The finally block is always executed, so it is generally used for doing the concluding tasks like closing file resources or closing database connection or maybe ending the program execution with a delightful message. Syntax: try:     statements which could generate exceptions except:     solution of generated exception finally:     Block of code which is going to execute at any situation  The finally block is executed irrespective of the outcome of the try...except...else block. ''' try:     l = (1, 5, 7, 13)     i = int(input("Enter the index: "))     print(l[i]) except:     print("Some error occurred") finally:     print("I am always executed") # output =  # Enter the index: 0 # 1 # I am always executed # output =  # Enter the index: 4 # So...

Exception Handling

''' Exception Handling: It is the process of responding to unwanted or unexpected events when a computer program runs. It deals with these events to avoid the program or system crashing. Without this process, exception would disrupt the normal operation of the program. ''' a = 5 print(f"Multiplication table of {a} is: ") for i in range(1, 11):   print(f"{int(a)} X {i} = {int(a) * i}") #output = Multiplication table of 5 is:  # 5 X 1 = 5 # 5 X 2 = 10 # 5 X 3 = 15 # 5 X 4 = 20 # 5 X 5 = 25 # 5 X 6 = 30 # 5 X 7 = 35 # 5 X 8 = 40 # 5 X 9 = 45 # 5 X 10 = 50 a = input("Enter the number") print(f"Multiplication table of {a} is: ") for i in range(1, 11):   print(f"{int(a)} X {i} = {int(a) * i}") #output = # Enter the number12 # Multiplication table of 12 is: # 12 X 1 = 12 # 12 X 2 = 24 # 12 X 3 = 36 # 12 X 4 = 48 # 12 X 5 = 60 # 12 X 6 = 72 # 12 X 7 = 84 # 12 X 8 = 96 # 12 X 9 = 108 # 12 X 10 = 120 # a = input("Ente...

for Loop with else

''' else statement in Loop: We have learnt before that else clause is used with if-statement. But Python allows the else keyword to be used with for and while loops too. The else block appears after the body of the loop. The statements in the else block will be executed after all the iterations are completed. The program exits the loop after else block is executed. ''' #Example: for i in range(5):     print(i) else:     print("Sorry no i") #output = 0 1 2 3 4 #Sorry no i for i in[]:     print(i) else:     print("Sorry no i") #output = Sorry no i for i in range(6):     print(i)     if i == 4:         break else:     print("Sorry no i") # output =  # 0 # 1 # 2 # 3 # 4 #Here else-statement didn't execute because loop is completed after the if-statement. i = 0 while i<7:     print(i)     i = i + 1     if i == 4:         break else:    ...

Dictionary Methods

''' Dictionary Methods: Dictionary uses several built-in methods for manipulation. 1.update() 2.clear() ''' ''' 1.update() This method updates the value of the key provided to it if the item already exists in the dictionary, else it creates a new value-pair. ''' ep1 = {2402: 92, 1001: 88, 1806: 45, 2810: 57} ep2 = {3583: 61, 9361: 90, 2539: 73, 3748: 44} ep1.update(ep2) print(ep1)              #output = {2402: 92, 1001: 88, 1806: 45, 2810: 57, 3583: 61, 9361: 90, 2539: 73, 3748: 44} ''' Removing items from dictionary: 2.clear() This method clears all the items from the dictionary. 3.pop() This method removes the key-value pair whose key is passed as a parameter. 4. popitem() This method removes the last key-value pair from the dictionary. 5.del() This keyword is used to remove a dictionary item. ''' ep1 = {2402: 92, 1001: 88, 1806: 45, 2810: 57} ep1.clear() print(ep1)            #output = {} ep1 = {2402: 92, 1001: ...

Dictionaries

''' Dictionaries in Python: In Python, dictionary is a built-in data type that stores data as key-value pairs. They stores multiple items in a single variable. They are separated by commas and enclosed within curly brackets{}. They are ordered collection of data items. Key Characteristics: 1. Ordered: Items do not have a defined order in Python versions < 3.7. In Python 3.7+, they maintain insertion order. 2. Mutable: We can change, add, or remove items. 3. Indexed by Keys: Each value is accessed using a unique key. 4. Keys Must Be Unique: Duplicate keys are not allowed. Syntax: dictionary_name = {     "key1": "value1",     "key2": "value2",     "key3": "value3" } ''' #Example: dic = {     "Sindhu": "Human Being",     "Lion"  : "Animal",     "Parrot": "Bird" } print(dic["Sindhu"])             #output = Human Being print(dic["L...

Set Methods in Python

''' Set Methods in Python: Sets in Python more or less work in the same work as sets in mathematics. We can operations like union and intersection on the sets just like in mathematics. ''' ''' 1. union() and update() The union() and update() methods prints all the items that are present in the two sets. The union() method returns a new set. The update() method adds items into the existing set from an another set. ''' s1 = {1, 7, 9, 3} s2 = {5, 3, 8, 9} print(s1.union(s2))           #output = {1, 3, 5, 7, 8, 9} print(s1, s2)                 #output = {1, 3, 9, 7} {8, 9, 3, 5}     #Both the sets remains untouched s1.update(s2) print(s1, s2)                 #output = {1, 3, 5, 7, 8, 9} {8, 9, 3, 5}  #Here s1 is updated with the values that s1 doesn't have, but s2 has. cities1 = {"Tokyo", "Madrid", "Berlin", "Delhi"} cities2 = {"Tokyo", "Kabul", "Seoul"...

Sets in Python

''' Python Sets: In Python, a set is an unordered collection of unique elements.  Sets are useful when we need to store a collection of items without any duplicates. Key Characteristics of Sets: 1. Unordered: The items have no defined order, and their position can change. 2. Unique Elements: No duplicate values are allowed. 3. Mutable: Sets can be modified after creation (elements can be added or removed). 4. Heterogeneous: A set can contain elements of different data types. ''' s1 = {1, 2, 3, 4} print(s1)                #output = {1, 2, 3, 4} s2 = {1, 1, 2, 3, 4, 4} print(s2)                #output = {1, 2, 3, 4}   #Duplicates are automatically removed info = {"Sindhu", 24, True, 2002} print(info)              #output = {24, True, 2002, 'Sindhu'}  #Here we can see that the items in set occur in random order, and hence they cannot be accessed using index...

Recursion in Python

''' Recursion in Python: It is the process of defining something in terms of itself. A physical world example would be to place two parallel mirrors facing each other. Any object in between them would be reflected recursively. ''' ''' Python Recursive Functions: In Python, we know that a function can call other functions. It is even possible for the function to call itself. These types of functions are termed as recursive functions. ''' #factorial (7) = 7*6*5*4*3*2*1 #factorial (6) = 6*5*4*3*2*1 #factorial (5) = 5*4*3*2*1 #factorial (0) = 1 #factorial (n) = n * factorial (n-1) def factorial(n):     if(n == 0 or n ==1):         return 1     else:         return n * factorial (n-1) #Here we have called the function factorial (n-1) with function factorial (n).      print(factorial (3))             #output = 6 print(factorial (4))             #outp...

Docstrings

''' Docstring in Python: A docstring in Python is a special type of comment used to describe a module, class, method, or function.  It is a string literal that appears as the first statement in the definition of the object it documents.  Docstrings are typically enclosed in triple quotes (""" or '' to allow multi-line text. Why Use Docstrings? Documentation: Explains what the code does, its parameters, return values, exceptions, etc. Readability: Makes code easier to understand for other developers (or your future self). Automatic Documentation: Tools like help() and pydoc use docstrings to display information. ''' #Example: def square(n):     '''Takes in a number n, returns the square of n'''     print(n**2) square(10)               #output = 100 #Here '''Takes in a number n, returns the square of n''' is a docstring which will not appear in the output. print(square.__doc__)    #output = Tak...

f-Strings

''' f-string(Formatted string literals) in Python is a way to embed expressions directly in string literals, making string formatting more readable and efficient. Introduced in Python 3.6, f-strings are prefixed with the letter f or F and allow us to include expressions within curly braces {} that are evaluated at runtime. ''' #Example: message = "Hey My name is {} and I am from {}" name = "Sindhu" country = "India" print(message.format(name, country))           #output = Hey My name is Sindhu and I am from India print(message.format(country, name))           #output = Hey My name is India and I am from Sindhu message1 = "Hey My name is {1} and I am from {0}" print(message1.format(country, name))          #output = Hey My name is Sindhu and I am from India   print(f"Hey My name is {name} and I am from {country}")   #output = Hey My name is Sindhu and I am from India print(f"Hey My name is...