You are on page 1of 42

ADHOC NETWORK- Tech Company

Introduction to Python

Python is a high-level programming language known for its simplicity


and readability. It was created by Guido van Rossum and first released in
1991. Python emphasizes code readability and simplicity, making it an
excellent choice for beginners and experienced programmers alike.
Overview of Python:
General Purpose: Python is a versatile language suitable for various
applications, including web development, data analysis, artificial
intelligence, scientific computing, automation, and more.
Easy to Learn: Python's syntax is straightforward and easy to understand,
making it an ideal language for beginners. It uses indentation to define
code blocks, which enhances readability.
Interpreted Language: Python is an interpreted language, meaning that
code is executed line by line by an interpreter. This allows for interactive
coding and rapid development.
Dynamic Typing: Python is dynamically typed, meaning you don't need
to declare variable types explicitly. Variable types are inferred at runtime,
simplifying code development.
Rich Standard Library: Python comes with a vast standard library that
provides support for various tasks such as file I/O, networking, regular
expressions, and more. This reduces the need for external dependencies
in many cases.
Cross-Platform: Python is available on multiple platforms, including
Windows, macOS, and Linux, making it a portable language for
developing applications that can run on different operating systems.
Popular Frameworks: Python has several popular frameworks and
libraries that extend its capabilities for specific domains. For web
development, frameworks like Django and Flask are widely used. For
data science and machine learning, libraries like NumPy, Pandas, and
TensorFlow are popular choices.

1|Page
ADHOC NETWORK- Tech Company
Versatile Toolset: Python is equipped with various development tools,
including integrated development environments (IDEs) like PyCharm,
text editors like VS Code and Sublime Text, and online interpreters like
Jupyter Notebook.
Open Source: Python is open-source software, meaning its source code
is freely available and can be modified and distributed by anyone. This
fosters collaboration and innovation within the Python community.

Overall, Python's simplicity, versatility, and vibrant ecosystem make it a


powerful language for developing a wide range of applications, from
simple scripts to complex software systems. Whether you're a beginner
or an experienced developer, Python offers a welcoming and supportive
environment for learning and building projects.

2|Page
ADHOC NETWORK- Tech Company

Programs:

1. Write a simple program to display 'Hello World!’


print("Hello World!")
Output:

print (): It’s a built-in function is used to output the text or other data to the
console

3|Page
ADHOC NETWORK- Tech Company
2. Write a program to implement basic calculator operations
num1 = float (input ("Enter the first number: "))
num2 = float (input ("Enter the second number: "))
op = input ("Enter operator (+, -, *, /, %): ")
if op == "+":
print (num1 + num2)
elif op == "-":
print (num1 - num2)
elif op == "*":
print (num1 * num2)
elif op == "%":
print (num1 % num2)
elif op == "/":
if num2! = 0:
print (num1 / num2)
else:
print ("Error: Division by zero!")
else:
print ("Invalid operator")
Output:

input (): function is used to accept input from the user through the
keyboard

4|Page
ADHOC NETWORK- Tech Company
3. Write a program to implement Simple Interest Calculator
principal = float (input ("Enter the principal amount: "))
rate = float (input ("Enter the annual interest rate (%): "))
time = float (input ("Enter the time period in years: "))
simple_interest = (principal * rate * time) / 100
print ("Simple interest:", simple_interest)
Output:

The print () function in Python ends with a newline character ("\n"),


which means that each call to print () will start a new line. However, when you
specify end=" ", it changes the default behaviour so that the print statement
doesn't end with a newline character but with a space character instead. This
means that subsequent calls to print () will continue on the same line,
separated by spaces.

5|Page
ADHOC NETWORK- Tech Company
4. Write a program to implement Fibonacci series
n = int (input ("Enter the number of terms: "))
n1, n2 = 0, 1
if n <= 0:
print ("Please enter a positive number")
elif n == 1:
print ("Fibonacci sequence up to the given number", n, "is: ", n1)
else:
print ("Fibonacci sequence is: ")
print (n1, end=" ")
print (n2, end=" ")
for i in range (2, n): # python for loop – iterates over a range of sequence
of numbers generated from 2 to n-1
next_term = n1 + n2
print (next_term, end=" ")
n1, n2 = n2, next_term
Output:

range (): it is used to generate sequence of numbers

6|Page
ADHOC NETWORK- Tech Company
5. Write a program to implement Recursive Factorial in python
def factorial(n):
if n == 0:
return 1
else:
return n * factorial (n - 1)

num = int (input ("Enter a number to find its factorial: "))


print ("Factorial of", num, "is:", factorial(num))
Output:

Factorial formula: n(n-1)!


Function: Block of statements, it won’t be invoked until you call it
explicitly
Actual Parameters: Parameters or Arguments inside the calling function
Formal Parameters: Arguments inside the called function

7|Page
ADHOC NETWORK- Tech Company
6. Write a program to implement Relational operations
num1 = float (input ("Enter the first number: "))
num2 = float (input ("Enter the second number: "))
op = input ("Enter operator (<, <=,>,>=,!=,==): ")
if op == "<":
print (num1 < num2)
elif op == "<=":
print (num1 <= num2)
elif op == ">":
print (num1 > num2)
elif op == ">=":
print (num1 >= num2)
elif op == "==":
print (num1 == num2)
elif op == “! =":
print (num1! = num2)
else:
print ("Invalid operator")
Output:

8|Page
ADHOC NETWORK- Tech Company
7. Write a program to implement Sum of digits of a given number
def sum_of_digits(n):
sum = 0
while n > 0:
rem = n % 10
sum = sum + rem
n = n // 10
return sum

num = int (input ("Enter the number: "))


print ("Sum of digits:", sum_of_digits(num))
Output:

9|Page
ADHOC NETWORK- Tech Company
8. Write a program to check whether given number is leap year or not
def is_leap_year(year):
if (year % 4 == 0 and year % 100! = 0) or (year % 400 == 0):
return True
else:
return False

year = int (input ("Enter a year: "))


if is_leap_year(year):
print (year, "is a leap year.")
else:
print (year, "is not a leap year.")
Output:

10 | P a g e
ADHOC NETWORK- Tech Company
9. Write a program to check given number is Palindrome or not.
def is_palindrome(num):
return str(num) == str(num)[::-1]

num = int (input ("Enter a number: "))


if is_palindrome(num):
print (num, "is a palindrome.")
else:
print (num, "is not a palindrome.")
Output:

11 | P a g e
ADHOC NETWORK- Tech Company
10.Write a program to check whether a given number is even or odd.
num = int (input ("Enter a number: "))

if num % 2 == 0:
print (num, "is an even number.")
else:
print (num, "is an odd number.")
Output:

12 | P a g e
ADHOC NETWORK- Tech Company
11.Write a program to find the sum of natural numbers up to a given
number.
def sum_of_natural_numbers(n):
return n * (n + 1) // 2
num = int (input ("Enter the number: "))
if num< 0:
print ("Please enter a positive number.")
else:
print ("Sum of natural numbers up to", num, "is",
sum_of_natural_numbers(num))
Output:

13 | P a g e
ADHOC NETWORK- Tech Company
12.Write a program to implement for loop to print Sequential Count
for count in range (1, 6):
print(count)
Output:

for loop syntax:


for item in iterable:
# code block to be executed for each item
Note: The for loop is used to iterate over a sequence (such as a list,
tuple, string, or range) or any iterable object.

14 | P a g e
ADHOC NETWORK- Tech Company
13.Write a program to implement while loop to print Sequential Count
count = 1 # Initializing the loop variable

while count <= 5: # while loop with condition


print(count)
count = count + 1 # updating the count by incrementing it to 1

Output:

while loop syntax:


while condition:
# code block to be executed repeatedly
# While loops are used when you want to execute a block of code
repeatedly as long as a specified condition is true.
Note: You have to explicitly handle initialization and updation of loop
variable outside of the loop and within the loop, respectively.

15 | P a g e
ADHOC NETWORK- Tech Company
14. Write a program to perform addition of numbers using function.
def add (n1, n2):
return n1 + n2

num1 = int (input ("Enter the first number: "))


num2 = int (input ("Enter the second number: "))
print ("Addition of", num1, "and", num2, "is:", add (num1, num2))

Output:

16 | P a g e
ADHOC NETWORK- Tech Company
15.Write a program to implement Arithmetic operators using functions in
while loop.
def add (x, y):
return x + y

def subtract (x, y):


return x - y

def multiply (x, y):


return x * y

def divide (x, y):


if y == 0:
return "Cannot divisible by zero!!!"
else:
return x / y

print ("Select the operation:")


print ("1. Addition")
print ("2. Subtractraction")
print ("3. Multiplication")
print ("4. Division")

while True:
choice = input ("Enter choice (1/2/3/4): ")

17 | P a g e
ADHOC NETWORK- Tech Company
if choice in ('1', '2', '3', '4'): # The in operator checks whether the value
of choice matches any of the elements in the tuple ('1', '2', '3', '4')
num1 = int (input ("Enter first number: "))
num2 = int (input ("Enter second number: "))

if choice == '1':
print ("Addition of given numbers is: ", add (num1, num2))
elif choice == '2':
print ("Subtraction of given numbers is: ", subtract (num1, num2))
elif choice == '3':
print ("Multiplication of given numbers is: ", multiply (num1, num2))
elif choice == '4':
print ("Division of given numbers is: ", divide (num1, num2))
else:
print ("Please enter a valid input!!")

again = input ("Do you want to repeat the operations again? (yes/no):
")
if again.lower() != 'yes':
break
Output:

18 | P a g e
ADHOC NETWORK- Tech Company

Tuples:
These are defined by the symbol, parentheses (). It is an immutable
(cannot be modified – cannot add, remove, or change elements). The
elements in a tuple maintains the order in which they were defined.

Loops can be controlled using looping control statements like break,


continue. Break is used to exit the loop, Continue is used to skip the
current iteration and move to the next one.

19 | P a g e
ADHOC NETWORK- Tech Company
16.Write a program to find the biggest of three numbers
num1 = float (input ("Enter the first number: "))
num2 = float (input ("Enter the second number: "))
num3 = float (input ("Enter the third number: "))

if num1 >= num2 and num1 >= num3:


greatest = num1
elif num2 >= num1 and num2 >= num3:
greatest = num2
else:
greatest = num3

print ("The greatest number is:", greatest)

Output:

20 | P a g e
ADHOC NETWORK- Tech Company
Logical operators:
These symbols are used to combine the logical relationships between
variables or values in a programming language. They are typically used in
conditional statements, loops, and other control structures to make imp
decisions based on conditions.

17.Write a program to implement Logical Operators


x = int(input("Enter the value of x: "))
y = int(input("Enter the value of y: "))

print(x, "> 0 and", x, "< 10 is:", x > 0 and x < 10)


print(x, "> 0 and", y, "> 10 is:", x > 0 and y > 10)
print(x, "> 10 or", y, "> 10 is:", x > 10 or y > 10)
print(x, "% 2 == 0 and", y, "% 2 == 0 is:", x % 2 == 0 and y % 2 == 0)
print("not (", x, "+", y, "> 15) is:", not (x + y) > 15)
Output:

21 | P a g e
ADHOC NETWORK- Tech Company
Assignment Operators:
These are used to assign values to variables. They involve using the =
operator to assign the value on the right-hand side to the variable on the
left-hand side.
18.Write a program to implement Assignment Operators
x = int(input("Enter the initial value of x: "))

print("Initial value of x:", x)

# Assigning values to x using different assignment operators

x += 5 # (Equivalent to x = x + 5)
print("Value of x after addition assignment is :", x)

x -= 3 # (Equivalent to x = x - 3)
print("Value of x after subtraction assignment is :", x)

x *= 2 # (Equivalent to x = x * 2)
print("Value of x after multiplication assignment is :", x)

x //= 4 # (Equivalent to x = x // 4)
print("Value of x after division assignment is :", x)

x %= 3 # (Equivalent to x = x % 3)
print("Value of x after modulus assignment is :", x)

x **= 2 # (Equivalent to x = x ** 2)
print("Value of x after exponentiation assignment is :", x)

x /= 2 # (Equivalent to x = x / 2)
print("Value of x after floor division or integer/floor division assignment
is :", x)
Output:

22 | P a g e
ADHOC NETWORK- Tech Company

23 | P a g e
ADHOC NETWORK- Tech Company
Bitwise Operators:
Bitwise operators in Python are used to perform operations on individual
bits of integer numbers.
19.Write a program to implement Bitwise Operators in python
x = int(input("Enter the value of x: "))
y = int(input("Enter the value of y: "))

# Bitwise AND - Returns 1 if both the bits are 1, otherwise returns 0.


result_and = x & y
print("Bitwise AND of", x, "and", y, "is:", result_and)

# Bitwise OR - Returns 1 if at least one of them is 1, otherwise returns 0.


result_or = x | y
print("Bitwise OR of", x, "and", y, "is:", result_or)

# Bitwise XOR - Returns 1 if both the bits differ, otherwise returns 0.


result_xor = x ^ y
print("Bitwise XOR of", x, "and", y, "is:", result_xor)

“”” Bitwise NOT - Inverts the bits. Returns the complement of the
number, including the sign bit.“””
result_not_x = ~x
print("Bitwise NOT of", x, "is:", result_not_x)

# Bitwise Left Shift - Shifts the bits toleft by a specific num of positions.
shift_bits = int(input("Enter the number of bits to left shift x by: "))
result_left_shift = x <<shift_bits
print("Bitwise Left Shift of", x, "by", shift_bits, "bits is:", result_left_shift)

# Bitwise Right Shift - Shifts the bits to right by a specific num of


positions.
shift_bits = int(input("Enter the number of bits to right shift y by: "))
result_right_shift = y >>shift_bits
print("Bitwise Right Shift of", y, "by", shift_bits, "bits is:",
result_right_shift)

Output:
24 | P a g e
ADHOC NETWORK- Tech Company

25 | P a g e
ADHOC NETWORK- Tech Company
20.Write a program to implement perfect squares between 1 and 50
def is_perfect_square(num):
return int(num**0.5)**2 == num

for i in range (1, 51):


if is_perfect_square(i):
print (i, end=" ")

Output:

21. Write a program to implement type conversions in python


int_num = int(input("\nEnter an integer value: "))
print("Given data belongs to : ",type(int_num))
float_num = float(int_num)
print("Integer to float conversion is:", float_num," - ",type(float_num))

float_num = float(input("\nEnter a float value: "))


print("Given data belongs to : ",type(float_num))
int_num = int(float_num)
print("Float to integer conversion is:", int_num," - ",type(int_num))

str_num = input("\nEnter a string representing an integer value: ")


print("Given data belongs to : ",type(str_num))
int_from_str = int(str_num)
print("String to integer conversion is:", int_from_str," -
",type(int_from_str))

str_float = input("\nEnter a string representing a float number: ")

26 | P a g e
ADHOC NETWORK- Tech Company
print("Given data belongs to : ",type(str_float))
float_from_str = float(str_float)
print("String to float conversion is:", float_from_str," -
",type(float_from_str))

int_str = int(input("\nEnter an integer value: "))


print("Given data belongs to : ",type(int_str))
str_from_int = str(int_str)
print("Integer to string conversion is:", str_from_int," -
",type(str_from_int))

float_str = float(input("\nEnter a float number: "))


print("Given data belongs to : ",type(float_str))
str_from_float = str(float_str)
print("Float to string conversion is:", str_from_float," -
",type(str_from_float))

Output:

27 | P a g e
ADHOC NETWORK- Tech Company

28 | P a g e
ADHOC NETWORK- Tech Company
22.Write a program in python to implement Mathematical functions
import math

# Square root of a number


num_sqrt = float(input("\nEnter a number to find its square root: "))
print("Square root of", num_sqrt, "is: ", math.sqrt(num_sqrt))

# Factorial of a number
num_factorial = int(input("\nEnter a number to find its factorial: "))
print("Factorial of", num_factorial, "is: ", math.factorial(num_factorial))

# Absolute value of a number, |Modulus|


num_abs = float(input("\nEnter a floating point number to find its
absolute value: "))
print("Absolute value of", num_abs, "is: ", math.fabs(num_abs))

# Power of a number
base = float(input("\nEnter the base to find exponential: "))
exponent = float(input("Enter the exponent of an exponential: "))
print(base, "raised to the power of", exponent, "is: ", math.pow(base,
exponent))

# Logarithm of a number – log basenum


num_log = float(input("\nEnter a number to find its logarithm: "))
base_log = float(input("Enter the base of the logarithm: "))
print("Logarithm of", num_log, "to the base", base_log, "is: ",
math.log(num_log, base_log))

29 | P a g e
ADHOC NETWORK- Tech Company

# Greatest Common Divisor (GCD) of two numbers


num1_gcd = int(input("\nEnter the first number: "))
num2_gcd = int(input("Enter the second number: "))
print("GCD of", num1_gcd, "and", num2_gcd, "is:", math.gcd(num1_gcd,
num2_gcd))

# Value of pi (π)
print("\nValue of π:", math.pi)

# Value of Euler's number (e)


print("\nValue of Euler's number (e):", math.e)
Output:

30 | P a g e
ADHOC NETWORK- Tech Company
Break:
It is a control flow statement used to exit or terminate a loop
prematurely. It is commonly used within loops such as for and while.
When the break statement is encountered within a loop, it immediately
exits the loop, regardless of whether the loop's condition evaluates to
true or false.
Continue:
It is control flow statement that is used within loops to skip the rest of
the current iteration and proceed to the next iteration of the loop (about
skipping specific iterations based on a condition).
Pass:
The pass statement is a null operation. It does nothing when executed. It
acts as a placeholder where syntax requires a statement but you don't
want any action to be taken (all about maintaining the structure and
syntax of your code without any action).
23. Write a program to implement break, continue and pass statements in
python
my_list = [1, 2, 3, 4, 5]

print("Demonstrating 'break statement':")


for num in my_list:
if num == 4:
break
print(num)
print("Outside loop")

print("\nDemonstrating 'continue statement':")


for num in my_list:
if num % 2 == 0:
continue
print(num)
print("Outside loop")

print("\nDemonstrating 'pass statement':")


for num in my_list:

31 | P a g e
ADHOC NETWORK- Tech Company
if num == 3:
pass #(Placeholder, does nothing)
else:
print(num)
print("Outside loop")
Output:

32 | P a g e
ADHOC NETWORK- Tech Company
String interpolation:
String interpolation is a process used in programming to embed
expressions or variables within a string. It allows you to construct
strings dynamically by inserting the values of variables or the results of
expressions directly into the string.

In Python, string interpolation is typically achieved using formatted string


literals, also known as f-strings. F-strings allow you to embed expressions
inside curly braces {} within a string literal. When the string is evaluated,
the expressions inside the curly braces are replaced with their
corresponding values.
24.Write a program to implement formatted string
name = input("Enter your name: ")
age = int(input("Enter your age: "))

print(f"My name is {name} and I am {age} years old.")


Output:

33 | P a g e
ADHOC NETWORK- Tech Company
enumerate () function is used to iterate over a sequence (such as a list,
tuple, or string) while keeping track of the index of each item. It returns
an enumerate object, which yields pairs containing the index and the
corresponding item from the iterable.

25.Write a program to implement enumerate function in python


list = ['Apples','29.4','Bananas',0.8,'Cherries',8.0,'Dates',11.091999,]

for index, value in enumerate(list):


print (f'Index: {index}, Value: {value}')

Output:

34 | P a g e
ADHOC NETWORK- Tech Company
26. Write a program to achieve Simple To-Do List Manager

todo_list = []

def add_task(task):
todo_list.append(task)
print (f"Task '{task}' added successfully to the to-do list.")

def view_tasks():
if todo_list:
print ("To-Do List:")
for idx, task in enumerate (todo_list, start=1):
print(f"{idx}. {task}")
else:
print ("To-Do List is empty.")

while True:
print ("\n1. Add Task\n2. View Tasks\n3. Quit")
choice = input ("Enter your choice: ")

if choice == "1":
task = input ("Enter the task: ")
add_task(task)
elif choice == "2":
view_tasks()
elif choice == "3":
print ("Exiting...")
break
else:
print ("Invalid choice. Please try again.")
Output:

35 | P a g e
ADHOC NETWORK- Tech Company

36 | P a g e
ADHOC NETWORK- Tech Company
Arrays in python:
An array is a data structure that stores a collection of elements, typically of the
same data type, in contiguous memory locations.
Uses:
 It offers efficient storage and
 It offers retrieval of elements,
 making them suitable for various computational tasks.
In Python, arrays are provided by the “array” module. Here's how you can
create an array in Python:
import array #importing all classes, functions and variables in the module
named array
array.array(‘i’,[]) # signed integers
Note: When you use import array, you are importing the entire ‘array’
module into your current namespace. This means that all objects defined in
the array module, including classes, functions, and variables, which are
accessible by using the array prefix.
(or)
from array import array # only specific classes, functions or variables can be
imported
Note: You are importing only specific objects (functions, classes, variables,
etc.) from a module named ‘array’ into your current namespace

37 | P a g e
ADHOC NETWORK- Tech Company

Fig. Typecode chart

Array syntax:
array(‘typecode’,[n1,n2,n3…..])

Creating an arrays of different types using the array() constructor


int_array = array('i', [1, 2, 3, 4, 5]) # creates an array of integer numbers

float_array = array('f', [3.14, 2.718, 1.618]) # creates an array of floating-point


numbers

char_array = array('u', ['a', 'e', 'i',’o’, ‘u’]) # creates an array of characters

unsign_array = array('I', [10, 20, 30, 40]) # creates an array of unsigned


integers

38 | P a g e
ADHOC NETWORK- Tech Company
Accessing individual elements from an array:
int_array[0] -> 1
float_array[2] -> 1.618
unsign_array[-2] -> 30

Printing all the characters in an array:


from array import array
char_array = array('u', ['a', 'e', 'i',’o’, ‘u’])
for e in char_array:
print(e)
(or)
Printing all the elements in an array:
from array import *
unsign_array = array('I', [10, 20, 30, 40])
for i in range(len(unsign_array)): # len() to get the length of array
print(unsign_array[i])

Exception handling mechanisms in Python:


try block: This is where you place the code that might raise an exception, i.e.,
an error that interrupts the normal flow of the program. By placing code inside
a try block, you're telling Python to attempt to execute that code. If no
exceptions occur, Python continues with the code after the try block.

except block: This is where you handle exceptions that occur within the
corresponding try block. You specify the type of exception you want to catch
after the except keyword. If the exception type specified in the except block

39 | P a g e
ADHOC NETWORK- Tech Company
matches the type of exception raised, the code inside the except block is
executed.

27. Write a program in python to search for an element in an array


from array import array
arr = array('i',[])
num_elements = int(input("Enter the length of an array: "))
for i in range(num_elements):
x = int(input("Enter the value: "))
arr.append(x)

print("\nElements in an array :",arr)

# Seach for the Element


Ele_search = int(input("\nEnter the search element: "))

index = 0
found = False

for e in arr:
if e == Ele_search:
print("Element found at index number: ",index)
found = True
break
index += 1
else:
print("Element not found in the array using the traditional approach.")
40 | P a g e
ADHOC NETWORK- Tech Company

# Using built-in function


try:
index = arr.index(Ele_search)
print("Using built-in function, element found at index:", index)
except ValueError:
print("Element not found using built-in function.")
Output:

41 | P a g e
ADHOC NETWORK- Tech Company
Ternary operator:
It is a conditional expression that allows you to write conditional statements in
a single line. It has the following syntax:
Syntax:
x if condition else y
This expression evaluates to x if the condition is true, and y otherwise.

28. Write a python program to implement ternary operator.


num = int(input("Enter a number: "))
result = "even" if num % 2 == 0 else "odd"
print(f"The number {num} is {result}.")
Output:

42 | P a g e

You might also like