1) Simple Calculator Using Functions:
def add(n1, n2):
return n1 + n2
def sub(n1, n2):
return n1 - n2
def mul(n1, n2):
return n1 * n2
def div(n1, n2):
return n1 / n2
print("Please select operation -\n"
"1. Add\n"
"2. Subtract\n"
"3. Multiply\n"
"4. Divide\n")
sel = int(input("Select operation (1-4): "))
n1 = int(input("Enter first number: "))
n2 = int(input("Enter second number: "))
if sel == 1:
print(n1, "+", n2, "=", add(n1, n2))
elif sel == 2:
print(n1, "-", n2, "=", sub(n1, n2))
elif sel == 3:
print(n1, "*", n2, "=", mul(n1, n2))
elif sel == 4:
print(n1, "/", n2, "=", div(n1, n2))
else:
print("Invalid input")
2) Simple Interest Calculator in python without functions:
principle = float(input("Enter the principle amount: "))
rate = float(input("Enter the annual interest rate (%): "))
time = float(input("Enter the time in years: "))
simple_interest = (principle * rate * time) / 100
total_amount = principle + simple_interest
print("-" * 30)
print(f"Principle Amount: ${principle:,.2f}")
print(f"Annual Interest Rate: {rate}%")
print(f"Time Period: {time} years")
print("-" * 30)
print(f"Simple Interest: ${simple_interest:,.2f}")
print(f"Total Amount: ${total_amount:,.2f}")
print("-" * 30)
OUTPUT:
Enter the principle amount: 100000
Enter the annual interest rate (%): 10
Enter the time in years: 3
------------------------------
Principle Amount: $100,000.00
Annual Interest Rate: 10.0%
Time Period: 3.0 years
------------------------------
Simple Interest: $30,000.00
Total Amount: $130,000.00
------------------------------
3) Factorial of a Number using Loop:
num = 7
factorial = 1
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
OUTPUT:
The factorial of 7 is 5040
Factorial of a Number using Recursion:
def factorial(x):
if x == 1 or x == 0:
return 1
else:
return (x * factorial(x-1))
num = 7
result = factorial(num)
print("The factorial of", num, "is", result)
OUTPUT:
The factorial of 7 is 5040
Factorial Using an Iterative For Loop:
n=6
f=1
for i in range(1,n+1):
f =f*i
print(f)
Using a Recursive Function:
def fact(n):
return 1 if n <= 1 else n * fact(n-1)
print(fact(6))
4) Develop a program to generate Fibonacci sequence of length
(N). Read N from the console:
N = int(input("Enter number of terms? "))
def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
if N <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(N):
print(recur_fibo(i))
OUTPUT:
Enter number of terms? 9
Fibonacci sequence:
0
1
1
2
3
5
8
13
21
EXAMPLE:
def test(var):
print ("Inside test()")
print("Argument is ", var)
print("Example of function with arguments")
x="hello"
test(x)
y=20
test(y)
print("Over!!")
OUTPUT:
Example of function with arguments
Inside test()
Argument is hello
Inside test()
Argument is 20
Over!!
def test(var) :
print ("Inside test()")
print("Argument is ", var)
print("Example of function with arguments")
x="hello"
test(x*3)
y=20
test(y*3)
print("Over!!")
OUTPUT:
Example of function with arguments
Inside test()
Argument is hellohellohello
Inside test()
Argument is 60
Over!!
5. PROGRAM TO DEMONSTRATE ORDER OF OPERATIONS:
result_1 = 5 + 10 * 2
print(f"Result 1 (standard precedence): {result_1}")
print(f"Result 1 (standard precedence):", result_1)
result_2 = (5 + 10) * 2
print(f"Result 2 (parentheses used): {result_2}")
result_3 = 3 * 2 ** 3
print(f"Result 3 (exponentiation before multiplication): {result_3}")
result_4 = 100 / 10 * 5
print(f"Result 4 (same precedence, left-to-right): {result_4}")
# Combining arithmetic and comparison operators
result_5 = 5 + 5 == 10
print(f"Result 5 (arithmetic before comparison): {result_5}")
result_6 = 5 + 3 == 10
print(f"Result 6 (arithmetic before comparison): {result_6}")
result_7 = 11 == 10 + 2
print(f"Result 7 (arithmetic after comparison): {result_7}")
name = "Alex"
age = 0
if name == "Alex" or name == "John" and age >= 2:
print("Result 8 (logical operators): Welcome!")
else:
print("Result 8 (logical operators): Good Bye!!")
result_9 = 2 ** 3 ** 2
print(f'Result 9 (arithmetic after comparison): {result_9}')
result_10 = 100 + 200 / 10 - 3 * 10
print(f'Result 10 (arithmetic after comparison): {result_10}')
OUTPUT:
Result 1 (standard precedence): 25
Result 1 (standard precedence): 25
Result 2 (parentheses used): 30
Result 3 (exponentiation before multiplication): 24
Result 4 (same precedence, left-to-right): 50.0
Result 5 (arithmetic before comparison): True
Result 6 (arithmetic before comparison): False
Result 7 (arithmetic after comparison): False
Result 8 (logical operators): Welcome!
Result 9 (arithmetic after comparison): 512
Result 10 (arithmetic after comparison): 90.0
6. STRING OPERATIONS PROGRAM:
print("--- 1. Basic String Operations ---")
str1 = "Hello"
str2 = "Python"
# Concatenation:
result_concat = str1 + " " + str2
print(f"Concatenation: {result_concat}")
result_concat2 = str1 + str2
print(f"Concatenation: {result_concat2}")
# Repetition:
result_repeat = str1 * 3
print(f"Repetition: {result_repeat}")
result_repeat2 = 3 * str1
print(f"Repetition: {result_repeat2}")
# Length:
result_length = len(result_concat)
print(f"Length: {result_length}")
print(f"Length:",result_length)
# Membership: Checking if a substring exists using 'in'
is_present = "Python" in result_concat
print(f"Membership check ('Python' in string): {is_present}")
# Indexing: Accessing individual characters (0-based index)
print(f"Indexing (first character): {result_concat[0]}")
print(f"Negative Indexing (last character): {result_concat[-1]}")
# Slicing: Extracting a portion of the string
result_slice = result_concat[0:5]
print(f"Slicing (indices 0 to 4): {result_slice}")
result_slice_end = result_concat[6:]
print(f"Slicing (from index 6 to end): {result_slice_end}")
result_reverse = result_concat[::-1]
print(f"Slicing (reversed string): {result_reverse}")
# --- 2. Common String Methods ---
print("\n--- 2. Common String Methods ---")
text = " Welcome to Python Programming! "
# Case manipulation
print(f"Original: '{text}'")
print(f"Uppercase: '{[Link]()}'")
print(f"Lowercase: '{[Link]()}'")
print(f"Title case: '{[Link]()}'")
# Stripping whitespace
print(f"Stripped: '{[Link]()}'")
# Finding and replacing
substring_find = [Link]("Python")
print(f"Find 'Python' (index): {substring_find}")
result_replace = [Link]("Python", "Java")
print(f"Replace 'Python' with 'Java': '{result_replace}'")
substring_find = [Link]("to")
print(f"Find 'to' (index): {substring_find}")
result_replace = [Link]("to", "at")
print(f"Replace 'to' with 'at': '{result_replace}'")
# Splitting and joining
words = [Link]().split()
print(f"Split into list: {words}")
result_join = "-".join(words)
print(f"Join list with '-': {result_join}")
result_join = "*".join(words)
print(f"Join list with '*': {result_join}")
result_join = "".join(words)
print(f"Join list with '': {result_join}")
result_join = " ".join(words)
print(f"Join list with ' ': {result_join}")
# --- 3. String Formatting ---
print("\n--- 3. String Formatting ---")
name = "Alice"
age = 30
# Using f-strings (Python 3.6+)
result_fstring = f"Name: {name}, Age: {age}"
print(f"f-string formatting: {result_fstring}")
# Using the format() method
result_format = "Name: {}, Age: {}".format(name, age)
print(f"format() method: {result_format}")
# Using f-strings for precise formatting (e.g., floating point)
pi_value = 3.14159
print(f"Formatted Pi (2 decimal places): {pi_value:.2f}")
7. Simple Calculator Using Functions:
def add(n1, n2):
return n1 + n2
def sub(n1, n2):
return n1 - n2
def mul(n1, n2):
return n1 * n2
def div(n1, n2):
return n1 / n2
def mod(n1, n2):
return n1 % n2
def floordiv(n1, n2):
return n1 // n2
def exponent(n1, n2):
return n1 ** n2
print("Please select operation -\n"
"1. Add\n"
"2. Subtract\n"
"3. Multiply\n"
"4. Divide\n"
"5. Modulus\n"
"6. Floor Division\n"
"7. Exponentiation\n")
sel = int(input("Select operation (1-7): "))
n1 = int(input("Enter first number: "))
n2 = int(input("Enter second number: "))
if sel == 1:
print(n1, "+", n2, "=", add(n1, n2))
elif sel == 2:
print(n1, "-", n2, "=", sub(n1, n2))
elif sel == 3:
print(n1, "*", n2, "=", mul(n1, n2))
elif sel == 4:
print(n1, "/", n2, "=", div(n1, n2))
elif sel == 5:
print(n1, "%", n2, "=", mod(n1, n2))
elif sel == 6:
print(n1, "//", n2, "=", floordiv(n1, n2))
elif sel == 7:
print(n1, "**", n2, "=", exponent(n1, n2))
else:
print("Invalid input")
TYPES OF ERRORS IN PYTHON:
1. Syntax Errors
Definition:
Syntax errors occur when the rules (syntax) of the Python
language are violated.
These errors are detected by the interpreter before the
program executes.
Example:
if x > 5
print("Greater")
Error: Missing colon : after the condition.
Correct Code:
if x > 5:
print("Greater")
Handling:
Carefully check the syntax.
Use an IDE or editor that highlights syntax mistakes.
Follow proper indentation and punctuation.
2. Runtime Errors (Exceptions)
Definition:
Runtime errors occur during program execution.
The program is syntactically correct, but an error happens while
running.
Common Examples:
Division by zero
Invalid type operations
File not found
Example:
a = 10
b=0
print(a/b)
Error: ZeroDivisionError
Handling Runtime Errors: Python provides exception handling using try
and except.
Example:
try:
a = 10
b=0
print(a/b)
except ZeroDivisionError:
print("Division by zero is not allowed")
Output:
Division by zero is not allowed
You can also use:
finally → always executed
else → executed if no exception occurs
Example:
try:
num = int(input("Enter a number: "))
except ValueError:
print("Invalid input")
else:
print("You entered:", num)
finally:
print("Program completed")
3. Logical Errors
Definition:
Logical errors occur when the program runs without crashing but produces
incorrect results due to incorrect logic.
Example:
# To find average
a = 10
b = 20
avg = a + b / 2
print(avg)
Problem: Operator precedence causes wrong result.
Correct Code:
avg = (a + b) / 2
print(avg)
Handling:
Test the program with different inputs
Use debugging
Verify algorithm logic carefully
Summary
Error
Description Example Handling
Type
Syntax Violation of Python Missing colon, wrong
Correct syntax
Error grammar indentation
Runtime
Occurs during execution Division by zero Use try-except
Error
Logical Program runs but gives Debug and
Wrong formula
Error wrong output correct logic
A user-defined function (UDF) in Python is a reusable block of code
created by a programmer to perform a specific task.
Unlike built-in functions such as print() or len(), UDFs allow for custom
logic and help in organizing large programs into smaller, more
manageable, and modular components.
Key Characteristics and Syntax
Functions are defined using the def keyword, followed by a function
name, parentheses (), and a colon :
Header: The definition starts with def, the function name, and
optional parameters in parentheses, ending with a colon.
Body: The code block within the function must be indented. This
body of code executes only when the function is called.
Calling a Function: To run the code inside a function, you call it by
its name followed by parentheses, passing any required arguments.
return Statement: An optional return statement can be used to
send a value back to the calling part of the program. If
no return statement is present, the function automatically
returns None.
Docstrings: A string literal immediately after the function header
serves as documentation (docstring) for the function, explaining its
purpose.
A function helps to:
Reuse code
Improve readability
Reduce repetition
Break a program into smaller modules
EXAMPLE:
# Program to illustrate
# the use of user-defined functions
def add_numbers(x,y):
sum = x + y
return sum
num1 = 5
num2 = 6
print("The sum is", add_numbers(num1, num2))
def calculate_area(length, width):
area = length * width
return area
rectangle_area = calculate_area(10, 5)
print(f"The area is: {rectangle_area}")
Parameters:
Parameters are variables listed in the function definition. They act as
placeholders for values passed to the function.
def multiply(x, y): # x and y are parameters
return x * y
Arguments:
Arguments are the actual values passed to the function when it is called.
result = multiply(4, 5) # 4 and 5 are arguments
print(result)
Scope of Variables in Python
Scope refers to the region of a program where a variable is accessible.
There are mainly two types:
1. Local Scope
2. Global Scope
Local Variables: A variable declared inside a function is called a local
variable, It can be accessed only inside that function.
def display():
x = 10 # local variable
print("Value of x:", x)
display()
Global Variables: A variable declared outside a function is called a global variable. It can be
accessed throughout the program.
x = 50 # global variable
def show():
print("Value of x:", x)
show()
Using Global Keyword: If we want to modify a global variable inside a function, we use the
global keyword.
x = 10
def change():
print(x)
global x
x = 20
change()
print(x)
x = 10
def change():
global x
print(x)
x = 20
change()
print(x)
Develop a Python program using string operations and generate the following output:
hellohellohellohello
helloFriend
str1 = "hello"
str2 = "Friend"
result1 = str1 * 4
result2 = str1 + str2
print(result1)
print(result2)
Develop a Python program using separate functions to perform string operations and
generate the following output:
hellohellohellohello
helloFriend
def repeat_string(text, n):
return text * n
def join_strings(str1, str2):
return str1 + str2
def main():
word = "hello"
result1 = repeat_string(word, 4)
print(result1)
result2 = join_strings(word, "Friend")
print(result2)
main()