Basic Python

Download as pdf or txt
Download as pdf or txt
You are on page 1of 111

Disclaimer

Every effort has been made to make this book as accurate


as possible. However, there may be inadvertent
typographical or content errors. The author and publisher
shall have no liability or responsibility to any person or
entity regarding any loss or damage incurred, or alleged to
have incurred, directly or indirectly, by the information
contained in this book. You hereby agree to be bound by
this disclaimer or you may return this book within 30 days’
time period for a refund.

Any error, mistake or discrepancy may be brought to our


notice which shall be taken care of in the forthcoming
edition.

The text of this Publication, or any part thereof, may not


be reproduced or transmitted in any form by any means,
electronic or mechanical, including photocopying,
recording, storage in an information retrieval, or
otherwise, without the prior written permission of the
Author and Publisher.

Preface

This book covers theoretical as well as practical


knowledge. As an author we tried to cover all the concepts
in Python. Also I would like to thank “Sarjil Satware”
(M.SC in Information Technology – Data Science)
with his immense knowledge in the field of Data Science
and Python helped me in compiling the entire textbook.

Basics of Python

Dr. Abbas Lalani

(PHD, MCA, MBA, MCOM, B.ED)

1
SR. PAGE
No:
INDEX OF CONTENT
NO:-

1 What is Python?
15

2 What can Python do?


15

3 Why Python. 16

4 Basic Python function. 16-17

5 Python Comments, Creating a Comment.


17

6 What is a Variable? 18

7 Built-in Data Types.


18

8 Python numbers:- int,float,complex. 18

2
9 Sequence Data Type:- Strings 19-22
,Slicing, Modifying Strings, String
Concatenation.

List, Tuple,Set, Dictionary

10 Python Operators:- 22
· Arithmetic operators
23
· Assignment operators
· Comparison operators
24
· Logical operators
· Identity operators
· Membership operators
· Bitwise operators

11 Python If ... Else, Nested If. 24-25

12 Python For Loops.


25

13 Python While Loops.


26

14
Python Functions: Arguments, 26

3
15 Python Lambda.
27

16 Python Classes/Objects. 26-27

17 Module. 27

18 Math Functions.
27

4
PYTHON REAL LIFE
PROBLEMS SOLVING:

SR. PAGE
INDEX OF PYTHON REAL LIFE NO:
NO:
PROGRAMS
1 Write a program for Add Two Numbers In 28
Python Using Sum.

2 Write a program for Adding Two Numbers In 29


Python Using (User input function

3 Write a program for Hello world print by using 30


print function.

4 Calculate the Square root of by Using Input 30


function.

5 Calculate The Area of Triangle Using formula 31

6 Write a program for Simple Calculator Using 31


function

5
7 Convert Kilometers to Miles using the formula 35
of miles.

8 Write a program for Swap two variables Using 35


swapping.

9 Write a program to check Number is Positive, 37


Negative Or zero Using (IF ELIF).

10 Write a program to check num is even or odd 38


using (if else)

11 Write a program to check if a given year is a 38


leap year or not.

12 Write a program to check if a given number is 39


prime or not

13 Write a program to generate random numbers. 41

14 Write a program to Compare two values by 41


using if elif else statements

15 Write a program to Remove duplicates from list 42


by using from keys method.

16 Write a program to remove duplicates from a list 43


by using a function.

6
17 Write a program to Remove the last item in the 44
set by using pop () method

18 Write a program to Remove the last item in 44


dictionary by using pop () method

19 Write a program to find the user input Number 45


is even or odd by using if else

20 Write a program by marks we can find grade 46


using if… elif… else.

21 Write a Program for choosing any language. 47

22 Write a program for checking eligibility of 48


voting.

23 Write a program to Find vowels from any string 49


and count by using for loop.

24 Write a program to convert celsius to 49


fahrenheit.

25 Write a program to display the multiplication 50


table using a for loop.

26 Write a program for user input name age and 51


marksUsing formatting of string and string
interpolation (f string)

7
27 Write a program to print the user input number 52
of a fibonacci sequence using a for loop.

28 Write a program to print all prime numbers in 53


intervals by using a for loop.

29 Write a program to print the even numbers from 54


a given list by using a function.

30 Write a program to calculate the factorial of a 54


number the function accepts the number as an
argument.

31 write a program to reverse a string using a 55


while loop and function.

32 Write a program to change the list element to 56


uppercase using lambda with map function.

33 Write a program to compute maximum elements 57


from a list by using lambda function with
reduce function.

34 Write a program for square using lambda 57


function.

35 Write a program to greet all the people given in 58


tuples using a function.

8
36 Write a program making a dictionary from two 59
lists by using the zip function.

37 Write a program function that accepts a string 60


and calculates the number of uppercase letters
and lowercase letters.

38 Write a program to find the most repeated 61


number from a list

39 Write a program to find the most repeated 62


number from a user inputted numbers by using
functions and modules.

40 Write a python program to display fibonacci 63


sequences using recursion.

41 Write a program to display a calendar in python 64


programming.

42 Write a python program to display fibonacci 65


sequences using recursion.

43 Write a python program to add two matrices. 66

44 Write a python program, How to Transpose a 67


matrix.

45 Write a program for hello world by using the 68


decorator function.

9
46 Write a program to check whether a number is 69
in a given range.

47 Write a program to find the most repeated 69


number from a list.

48 Write a program to find the most repeated 70


number from a list without using any functions
and modules

49 Write a program to find numbers divisible by 71


another number.

50 Write a python program to catch multiple 72


handling in python

51 Write a python program How to print out 73


without a newline.

52 Write a Python program to count the number of 73


vowels in a string (by using function)

53 Write a Python program to generate Fibonacci 74


series up to n terms. (by using function)

54 Write a Python program to check if a number is 75


prime or not.

55 Write a python program for Reverse a String. 76

10
56 Write a python program to find all duck 77
numbers within a range

57 Write a python program to calculate the power 79


of a number.

58 Write a python program to Find the square root 80


of a number.

59 Write a python program to find the cube root of 81


a number.

60 Write a python program to check if a string is a 82


valid email address.

61 Write a python program to sort a dictionary by 83


value.

62 Write a program for inverted full pyramid 84


pattern by using Nested for loop.

63 Write a program for the Right half pyramid 85


pattern by using Nested for loop.

64 Write a program for the left half pyramid pattern 85


by using Nested for loop.

65 Write a program for Full Pyramid pattern by 86


using Nested for loop.

11
66 Write a program for Diamond pattern by using 87
Nested for loop.

67 Write a program for square and cube values by 88


using the decorator function.

68 Write a program to compute maximum elements 89


from a list by using lambda function with
reduce function.

69 Write a program to find factorial using 90


recursion.

70 Write a program to slice operations using 91


arrays.

71 Write a program to retrieve and display 92


elements of a numpy array using while loop
indexing.

72 Write a program to find the transpose of a 93


matrix by using an array

73 Write a program to retrieve and display 94


elements of a numpy array using while loop
indexing.

74 Write a program to calculate the sine of an array 95


of angles (in radius) Using Numpy.

12
75 Write a program to calculate the cosine 96
similarity of 2 vectors (as numpy arrays).

76 Write a program for converting any string lower 97


to uppercase and upper to lowercase by using
for loop and nested if else.

77 Write a program for counting the substring from 99


string using a for loop.

78 Write a program to print the user input number 99


of a fibonacci sequence using a for
loop(example-2).

79 Write a program to display power of 2 using an 101


anonymous function.

80 Write a python program to convert decimal to 102


binary octal and hexadecimal.

81 Write a python program to find the ASCII value 103


of a character.

82 Write a python program to convert Decimal to 104


Binary using Recursion.

83 write a python program How to merge two 105


dictionaries.

13
84 Write a python program to access the index of a 105
list using a for loop in python.

85 Write a python program on how to slice a list in 106


python.

86 Write a program to iterate over dictionaries 107


using a for loop.

87 Write a python programHow to check if a list is 107


empty in python

88 Write a python program List Manipulation. 108

89 Write a python program to Calculate Simple


Interest. 109

90 Write a python program to find the average of 110


numbers in a list.

14
What is Python?
“Python is a popular programming
language. It was created by Guido van
Rossum, and released in 1991.”

It is used for:

● web development (server-side),


● software development,
● mathematics,
● system scripting.

What can Python do?


● Python can be used on a server to
create web applications.
● Python can be used alongside
software to create workflows.
● Python can connect to database
systems. It can also read and
modify files.
● Python can be used to handle big
data and perform complex
mathematics.

15
● Python can be used for rapid
prototyping,or for production-ready
software development.

Why Python?
● Python works on different platforms
(Windows, Mac, Linux, Raspberry Pi,
etc).
● Python has a simple syntax similar
to the English language.
● Python has syntax that allows
developers to write programs with
fewer lines than some other
programming languages.
● Python runs on an interpreter
system, meaning that code can be
executed as soon as it is written.
This means that prototyping can be
very quick.
● Python can be treated in a
procedural way, an object-oriented
way or a functional way.

Basic python function:

Input:

16
Allows you to ask a user to type some
sort of information into the program and
to save that information into a variable
that the program can process.

Print:(used in every program)

Used to print the object.

Type:

The function returns data type.

Id:

Gives the memory location of the


object.

Python Comments:(used in every


program)
Comments can be used to explain Python
code.Comments can be used to make the
code more readable.

Comments can be used to prevent


execution when testing code.

17
Creating a Comment:(used in every
programs)

Comments starts with a #, and Python


will ignore them.

What is Variables(used in every


program)

Variables are containers for storing data


values.

Built-in Data Types:

In programming, data type is an


important concept.Variables can store
data of different types, and different
types can do different things.

Python has the following data types


built-in by default, in these categories:

Python Numbers:
There are three numeric types
in Python.

● int

18
● Float
● complex

Sequence Data Type:-

Strings:

Strings in python are surrounded by


either single quotation marks, or double
quotation marks.

'hello’ is the same as "hello".

Slicing:

You can return a range of characters by


using the slice syntax.

Specify the start index and the end


index, separated by a colon, to return a
part of the string.

Modify Strings:
Python has a set of built-in methods that
you can use on strings.

19
● Upper Case
● Lower Case
● Remove Whitespace
● Replace String
● Split String

String Concatenation:

To concatenate, or combine, two strings


you can use the + operator.

Looping Through a String:


Since strings are arrays, we can loop
through the characters in a string, with a
for loop.

String Format:
As we learned in the Python Variables
chapter, we cannot combine strings and
numbers like this.

But we can combine strings and numbers


by using the format() method!

The format() method takes the passed


arguments, formats them, and places

20
them in the string where the
placeholders {} are.

List:
Lists are used to store multiple items in a
single variable.

Lists are created using square brackets.

Tuple:

Tuples are used to store multiple items in


a single variable.

Tuple is one of 4 built-in data types in


Python used to store collections of data,
the other 3 are List, Set, and Dictionary,
all with different qualities and usage.

A tuple is a collection which is ordered


and unchangeable.

Tuples are written with round brackets.

Set:

Sets are used to store multiple items in a


single variable.

21
Set is one of 4 built-in data types in
Python used to store collections of data,
the other 3 are list,tuple and Dictionary
all with different qualities and usage.

Dictionary:

Dictionaries are used to store data values


in key:value pairs.

A dictionary is a collection which is


ordered*, changeable and do not allow
duplicates.

Modify Strings:
Python has a set of built-in methods that
you can use on strings.
● Upper Case
● Lower Case
● Remove Whitespace
● Replace String
● Split String

Python Operators:

Operators are used to perform operations


on variables and values.

22
In the example below, we use the +
operator to add together two values:

Python divides the operators in


the following groups:

● Arithmetic operators
● Assignment operators
● Comparison operators
● Logical operators
● Identity operators
● Membership operators
● Bitwise operators

Python Arithmetic Operators:

Arithmetic operators are used with numeric


values to perform common mathematical
operations.

Python Assignment Operators:

Assignment operators are used to assign


values to variables.

Python Comparison Operators:

Comparison operators are used to


compare two values.

23
Python Logical Operators:

Logical operators are used to combine


conditional statements.

Python Identity Operators:

Identity operators are used to compare


the objects, not if they are equal, but if
they are actually the same object, with
the same memory location.

Python Membership Operators:

Membership operators are used to test if a


sequence is presented in an object.

Python Bitwise Operators:


Bitwise operators are used to compare
(binary) numbers.

Python If ... Else:

Python supports the usual logical


conditions from mathematics:

● Equals: a == b

24
● Not Equals: a != b
● Less than: a < b
● Less than or equal to: a <= b
● Greater than: a > b
● Greater than or equal to: a >= b

These conditions can be used in several


ways, most commonly in "if statements"
and loops.

An "if statement" is written by using the


if keyword.

Nested If:
You can have if statements inside if
statements, this is called nested if
statements.

Python For Loops:


A for loop is used for iterating over a
sequence (that is either a list, a tuple, a
dictionary, a set, or a string).

This is less like the for keyword in other


programming languages, and works
more like an iterator method as found in

25
other object-oriented programming
languages.

With the for loop we can execute a set


of statements, once for each item in a
list, tuple, set etc.

Python While Loops:

With the while loop we can execute a set


of statements as long as a condition is
true.

Python Functions:

A function is a block of code which only


runs when it is called.

You can pass data, known as


parameters, into a function.A function
can return data as a result.

Arguments:

Information can be passed into functions


as arguments.

Arguments are specified after the


function name, inside the parentheses.

26
You can add as many arguments as you
want, just separate them with a comma.

Python Lambda:

A lambda function is a small anonymous


function.

A lambda function can take any number


of arguments, but can only have one
expression.

Python Classes/Objects:

Python is an object oriented


programming language.

Almost everything in Python is an object,


with its properties and methods.

A Class is like an object constructor, or a


"blueprint" for creating objects.

Module:

Consider a module to be the same as a


code library.

27
A file containing a set of functions you
want to include in your application.

Math Functions:
The min() and max() functions can be
used to find the lowest or highest value
in an iterable.

BASICS OF PYTHON PROGRAM:-

1. Write a program for Add Two


Numbers In Python Using Sum.

Coding part:-
#User can create two variable num1 and
#num2

num1=10
num2=20

#user can create sum variable for adding two


#numbers

sum=num1+num2

#print statement return the values which is use


#in the print statement

28
print(“the sum of two number is:”,sum)

We can use any latest version of python


3.12.1. otherwise we can use pycharm,thony
and online compiler

2. Write a program for Adding Two


Numbers In Python Using (User
input function)

#the user can create two variables num1 and


#num2 and use the input function for the user
#input.
#we have to use float if the user input decimal
#number.
num1=float(input("Enter any number:"))
num2=float(input("Enter any another
number:"))
#user can create sum variable for adding two
#numbers
sum=num1+num2
#print statement return the values the sum of
#provided two number is
print(“the sum of provided two number
is:”,sum)

29
3. Write a program for Hello world
print by using print function
#User can directly use print function
#use single quotes or double quotes in print
function
print("Hello world!")

4.Calculate the Square root of by


Using Input function.
#create variables num and take the user to
#input using the input function.
num=int(input("enter any number:"))
#create a variable of sqr root for a given
#number using exponentiation.
Sqr_root=num**(1/2)

30
#The square root of a given number using sqr
#root variable values
print("the square root of given number is
",Sqr_root)

5.Calculate The Area of Triangle


Using formula
#create height variable for taking user input of
#height
height=float(input("enter height of the
triangle:"))
#create base variable for taking user input of
#base
base=float(input("enter base of the triangle:"))
#create a variable area and apply the formula
#of area of triangle.
area=(1/2)*base*height
#print area of triangle using area variable
print("the area of triangle is",area)

31
6. Write a program for Simple
Calculator Using function

#define addition function and using argument


#num1 and num2
def add(num1,num2):
return num1+num2
#define subtraction function and using
#argument num1 and num2
def sub(num1,num2):
return num1-num2
#define multiplication function and using
#argument num1 and num2
def mul(num1,num2):
return num1*num2
#define division function and using argument
#num1 and num2
def div(num1,num2):
return num1/num2
#define modulus(reminder) function and using
#argument num1 and num2
def mod(num1,num2):
return num1%num2
#define floor division function and using
#argument num1 and num2
def flo(num1,num2):
return num1//num2

32
#define square function and using print
#statement
def sqr(num1,num2):
print(f'{num1}**2={num1**2}')
print(f'{num2}**2={num2**2}')
#using while loop for continue
while(True):
#taking input from users for num1 variable
num1=int(input("enter any number:"))
#taking input from users for num2 variable
num2=int(input("enter another number:"))
#using print statement to show task
print("""this is your taks
1.add
2.sub
3.mul
4.div
5.mod
6.flo
7.sqr """)

#taking input from users which task to perform


ip=int(input("enter your choice:"))
#using conditional statements
if(ip==1):

print(f'{num1}+{num2}=={add(num1,num2)}')

elif(ip==2):

33
print(f'{num1}-{num2}=={sub(num1,num2)}')
elif(ip==3):

print(f'{num1}*{num2}=={mul(num1,num2)}')

elif(ip==4):
print(f'{num1}/{num2}=={div(num1,num2)}')

elif(ip==5):

print(f'{num1}%{num2}=={mod(num1,num2)}')
elif(ip==6):

print(f'{num1}//{num2}=={flo(num1,num2)}')

elif(ip==7):
sqr(num1,num2)

else:
break #for quite

34
7.Convert Kilometers to Miles using
formula of miles.

#using km variable for taking input from the


#user by using float input function.
km=float(input("enter your values in kms:"))
#using miles variable for formula
miles=(0.621371)*km
#fixed for multiplication 0.621371

#print function used for printing the statement.

35
print(km,"kms in miles will be",mile,"miles")

8.Write a program for Swap two


variable Using swapping

#creating two variable x and y


x=20
y=30

#creating the temp variable


temp=x #for swapping x value

#using print statements for print value of temp


print("the value of temp variable is",temp)

x=y #assign the values of x

#using print statements for print value of x


print("the value of x is",x)

y=temp #assign the values of y

36
#using print statements for print value of y
print("the value of y is",y)

9. Write a program to check Number


is Positive, Negative Or Zero Using
(IF ELIF)

#creating variable and assign the value


a =0

#using if conditional statement for positive


#integer
if a>0:
print("number is positive")

#statement for if execution

#using elif conditional statement for zero


#integer

37
elif a==0:
print("number is zero ")
#statement for elif block execution

#using else conditional statement for negative


#integer
else:
print("number is negative")
#statement for else block execution

10.Write a program to check num is


even or odd using (if else)
#creating variable for assigning value
a=13
#using if conditional statement for even
#number
if a%2==0: # if reminder gives 0 so number is
even
print("Number is even")
#using else statement for odd number
else:
#if reminder gives 1 so number is odd
print("number is odd")

38
11. Write a program to check if a
given year is a leap year or not.

#creating variable year and take input from


#user by using input function
year =int(input("enter a year:"))

#using if conditional statements


if(year % 400==0) and (year % 100 ==
0):
print(year,"is a leap year") #print
#function

#using elif conditional statements

elif(year % 4==0) and (year % 100 !=0):


print(year,"is a leap year")

#using else
else:
print(year,"is not leap year")

39
12. Write a program to check given
number is prime or not
#creating num variable for taking input from
#user
num=int(input("enter any number:"))

#using if conditional statement


if num==1:
#print function
print("it is not a prime number")

#using if conditional statement


if num>1:
#using for loop
for i in range(2,num):
if num % i==0: #using if
#conditions
print("it is not a prime number")
break # break

#using else statement


else:
print("it is a prime number")
#print statement

40
13.Write a program to GENERATE A
RANDOM NUMBER

#import random module


import random
#create variable and use function randint and
#give initial and terminal
num=random.randint(0,10)
#print statement
print(num)

14.Write a program to Compare two


values by using if elif else statements
#User can create two variable a and b to
#compare it self by values
a = 200 ,b = 33
# user can use if condition
if b > a: # b is greater than a
print("b is greater than a")
#user can use elif if conditions is more
elif a == b: # a and b is equal

41
print("a and b are equal")
#is above both conditions is false then else
#block will execute
else: #no need condition
print("a is greater than b")
#User can create two variable a and b to
#compare it self by values
a = 200
b = 33
# user can use if condition
if b > a: # b is greater than a
print("b is greater than a")
#user can use elif if conditions is more
elif a == b: # a and b is equal
print("a and b are equal")
#is above both conditions is false then else
#block will execute
else: #no need condition
print("a is greater than b")

15.Write a program to Remove


duplicates from list by using from
keys method.
#First we have a List that contains
#duplicates

42
#user can make list
my = ["a", "b", "a", "c", "c"]
#use fromkeys method for remove
#duplicates
my = list(dict.fromkeys(my))
print(my) #print my list

16. Write a program to remove


duplicates from a list by using a
function.
#user can define any name of function with
#parameters
def my_function(x):
#using fromkey method for removing
#duplicates by return function
return list(dict.fromkeys(x))
#pass arguments(values) in function
my = my_function(["a", "b", "a", "c", "c"])
#print function call
print(my)

43
17. Write a program to Remove the
last item in set by using pop() method

#User can create a set


thisset = {"apple", "banana", "cherry"}
#Using the pop() method for removing last
#element
x = thisset.pop()

print(x) #removed item


print(thisset) #the set after removal

[Note:every time output will change


due to set not support indexing ]

18. Write a program to Remove the


last item in dictionary by using pop()
method
#User can create a dictionary
dict = {
"brand": "Ford",
"model": "Mustang",

44
"year": 1964
}
#Using the pop() method for removing last
#element
dict.pop("model")
print(dict) #the dictionary after removal

19. Write a program to find the user


input Number is even or odd by using
if else
#user can create any variable and using input
#function for user input
num=int(input("enter any number:"))
#using if condition ,checking remainder is 0 or
#1
if(num%2==0): #if remainder 0
print("Number is even ")
else: #if remainder 1
print("Number is odd")

45
20.Write a program by marks we can
find grade using if… elif… else.

#user can create any variable and take input


#from user by using input function
marks=int(input("enter your marks:"))
#using if condition for D grade
if(marks>35 and marks<45):
print("you have passed with D grade ")
#using elif condition for C grade
elif(marks>=45 and marks<55):
print(" you have passed with C grade")
#using elif condition for B grade
elif(marks>=55 and marks<65):
print(" you have passed with B grade")
#using elif condition for A grade
elif(marks>=65 and marks<75):
print(" you have passed with A grade")
#using elif condition for O grade
elif(marks>=75):
print(" you have passed with distinction O
grade")
#else function if above all condition are not met

else:
print("you have failed in examination with F
grade ") #print for else statement

46
21. Write a Program for choosing any
language.
#user can create any variable and take input
#from user by using input function
choice=int(input("""please select your favorite
language
1.python language
2.java language
3.R language
4.Rust language
please select :"""))
if(choice==1): # if for python language
print("your selected language is: python
language ")
elif(choice==2): #elif for java language
print("your selected language is:java
language ")
elif(choice==3): #elif for R language
print("your selected language is:R language
")
elif(choice==4): #elif for Rust language
print("your selected language is:Rust
language ")
else: #else if above condition is not met
print ("you are not from this world! ")

47
22.Write a program for checking
eligibility of voting.

#user can create any variable and take input


#from user by using input function
age=int(input("enter your age:"))
#using if condition for checking age if eligible
#for for then ask about voter card
if(age>=18):
card=int(input("you have voter card: press 1
for yes,press 2 for no:"))
if(card==1):
#if have voter card the user is eligible for vote
print("you can vote")

#if not have a voter card the user is not


eligible.and message to user please apply for
voter card.
else:
print("you are not eligible for vote ,please
apply for voting card")
# age is less than 18 then user is not eligible
else:
print("you are under 18 so you are not
eligible for vote")

48
23. Write a program to Find vowels
from any string and count by using
for loop

#user can create variable count for indexing


count=0
#user can create variable for taking input from
#user
s=str(input("enter any string:"))
# string is sequence of unicode characters
# user can create variable for compare vowels
vowel="a,e,i,o,u,A,E,I,O,U"
#using for loop for indexing

for i in s:
if(i in vowel):
count +=1 #indexing increment
print(count) #print the count values

24.Write a program to convert celsius


to fahrenheit.
#user can create variable celsius and take
#input from user by using input function
celsius=int(input("enter any number:"))

49
#this is the formula
fahrenheit=(celsius*(9/5))+32
#Users can use(1.8) instead of (9/5)
#print statement using display the
#converted value.
print("the converted value
is",fahrenheit,"fahrenheit")

25.Write a program to display the


multiplication table using for loop
#users can create variable and take input from
#user by using input function
n=int(input("enter any number:"))
#using for loop with range
for i in range(1,11):
#print function for display the table
print(n,"X",i,"=",n*i)

50
26.Write a program for user input
name,age and marks.Using
formatting of string and string
interpolation(f.string)

#string formatting
#user can use input function for taking input
#name
name=input("enter your name:")
#user can use input function for taking input
#age
age=input("enter your age:")
#user can use input function for taking input
#marks
marks=input("enter your marks:")
#just for shows user input values
print(name,age,marks )
#string formatting
print("my name is " +name+ "my age is
"+age+" my marks is"+marks)
#string interpolation (f.string )
print(f"my name is {name},my age is {age},my
marks is {marks}")

51
27.Write a program to print the user
input number of a fibonacci
sequence using a for loop.
#using variable a and b and assigning values
a=0
b=1
#taking input from user any number
num=int(input("enter any number to obtain
fibonacci sequence:"))
#if condition
if num==1:
print(a) #print a values
else: #else
print(a) #print a values
print(b) #print b values
#using for loop and range
for i in range(1,num+1):
c=a+b #creating variable c and assigning
#value a+b
a=b #assign
b=c #assign
print(c) #print c values

52
28.Write a program to print all prime
numbers in intervals by using a for
loop.

# Users can create variables and take input


#from users for lower and upper limits.
lower=int(input("enter lower limit here(>1):"))
upper=int(input("enter upper limit here:"))
#using for loop and apply range lower and
#upper limits
for i in range (lower,upper+1):
if i >1: #using if condition for i is greater
#than 1
for num in range(2,i): #using for loop
if i%num==0: #using if condition for
#modulus
break #using break
else: #using else
print(i) #using print for i

53
29.Write a program to print the even
numbers from a given list by using a
function.
#python program to print the even numbers
#from a given list using a function.
#using function
def is_even_number(num):
enum=[] #creating object for empty list
for n in num: #using for loop
if n %2==0: #using if for conditions for
#even number
enum.append(n) #using append
#method
return enum #using return
#using print statement
print(is_even_number([11,12,13,14,15,16,17,1
8,19]))

30.Write a program to calculate the


factorial of a number the function n
accept the number as an argument.
#using function for factorial
def factorial(n):
if n==0: #using if condition

54
return 1 #returning 1
else: #using else
#returning the values multiply by factorial of
#value-1
return n * factorial (n-1)
#users can create variable and take input from
#user
n=int(input("enter any number to compute the
factorial:"))
print(factorial(n)) #print the factorial value

31.write a program to reverse a string


using a while loop and function.
#using function for reverse
def string_reverse(s):
rs= " " #creating variable and assign the
#empty string
index=len(s) #creating index and assign the
#length
while index>0: #using while loop for index is
greater than 0
rs += s[ index-1] #assigning negative
#indexing

55
index = index -1 #assigning the index
#value for reverse
return rs #return the rs
print(string_reverse("sarjilsatware")) #print the
#string_reverse

32.Write a program to change the list


element to uppercase using lambda
with map function .
#python program using lambda() function with
#map()
#here we intend to change all name to upper
#case and return the
names=["sufiyan","sarjil","uvais","salman","zaid
”]
#creating variables and using lambda function
#and converting uppercase methods .
uppered_names=list(map(lambda
names:str.upper(names),names))
#print uppered_names variable
print(uppered_names)

56
33.Write a program to compute
maximum elements from a list by
using lambda function with reduce
function.
#python program using a lambda function with
#reduce function
#to compute maximum element from list
import functools #importing functools
#creating list
A=[11,34,54,65,90,23]
#using print statement
print("the maximum element of the list
is:",end="")
#using lambda and reduce function
print(functools.reduce(lambda a,b:a if a>b else
b,A))

34.Write a program for square using


lambda function.
#python program for lambda function,
#that takes a number and returns the square of
it.
square=lambda a:a*a

57
#call lambda function
#create variable and take input from user
num=int(input("enter the number\n"))
#create variable for square
result= square(num) #print statement
print("square of number is:",result)

35.Write a program to greet all the


people given in tuples using a
function.
#program to greet all the people given in tuple
def greet(*names):
#name is a tuple with argument
for name in names: #using for loop
#for iterate
print("Good morning",name) #using print
#function
#calling function
greet("samad","sufiyan","sarjil","uvais","madiha
","farzana")

58
36.Write a program making a
dictionary from two lists by using the
zip function.
#create two list
l1=[1,2,3,4,5]
l2=["sarjil","sufiyan","uvais","madiha","umar"]
#create variable and apply zip function
zip_obj=zip(l1,l2)
print(zip_obj) #print created variable zip_obj
l1=list(zip_obj) #convert into list
d1=dict(l1) #convert into dictionary
print(d1) #print dictionary

59
37.Write a program function that
accepts a string and calculates the
number of uppercase letters and
lowercase letters.
#using function
def string_test(s):
d={"upper_case":0,"lower_case":0}
#creating a dictionary and assigning the value
#lowercase and uppercase 0.
for c in s: #using for loop
if c.isupper(): #using if condition for
#upper case
d["upper_case"]+=1
elif c.islower(): #using elif condition for
#lower case
d["lower_case"]+=1
else: #using else for pass
pass
print("original string:",s) #print for original
#string
#using print function for uppercase
print("no. of uppercase
characters:",d["upper_case"])
#using print function for lowercase
print("no.of lower case
characters:",d["lower_case"])
#calling for function
string_test("I Love My India")

60
38.Write a program to find the most
repeated number from a list.
#find the most repeated number from list
max_count = 0
numbers=[1,2,3,3,3,4,5,6,73]
# Iterate through the list
for num in numbers:
# Count occurrences of the current number in
#the list
current_count = numbers.count(num)

# Update if the current number has more


#occurrences than the current maximum
if current_count > max_count:
most_repeated_number = num
max_count = current_count

# Print the most repeated number


print(f"The most repeated number is:
{most_repeated_number}")

61
39.Write a program to find the most
repeated number from a user
inputted numbers by using functions
and modules.

from collections import Counter


def find_most_repeated_number(numbers):
# Use Counter to count the occurrences of
each number in the list
counts = Counter(numbers)

# Find the most common number and its


count
most_common_number, count =
counts.most_common(1)[0]

return most_common_number, count

def main():
# Input: List of numbers
numbers = [int(x) for x in input("Enter
numbers separated by space: ").split()]

# Call the function to find the most repeated


number
most_repeated_number, count =
find_most_repeated_number(numbers)

62
# Output the result
print(f"The most repeated number is
{most_repeated_number} with a count of
{count}.")

if __name__ == "__main__":
main()

40.Write a python program to display


fibonacci sequence using recursion.

#user can create function


def fibonacci(n):
if n <= 1: #using if condition
return n
else: #using else
return fibonacci(n-1) + fibonacci(n-2)
#the user can create another function.
def display_fibonacci_sequence(num_terms):
if num_terms <= 0: #using condition
print("Please enter a positive integer.")
else: #using else statement
print("Fibonacci sequence:")
#using for loop with range

63
for i in range(num_terms):
print(fibonacci(i), end=" ") #print
#statement

# Taking input from the user


num_terms = int(input("Enter the number of
terms for Fibonacci sequence: "))

# Displaying Fibonacci sequence


display_fibonacci_sequence(num_terms)

41.Write a program to display a


calendar in python programming.
#import calendar module
import calendar
#user can create year variable and take input
#from user
year = int(input("Enter year: "))
#user can create month variable and take input
#from user

64
month = int(input("Enter month: "))
#using print statements for calendar.month
print(calendar.method with user inputted year
and month month(year, month))

42.Write a python program to display


fibonacci sequence using recursion.

#user can create function


def fibonacci(n):
if n <= 1: #using if condition
return n
else: #using else
return fibonacci(n-1) + fibonacci(n-2)
#the user can create another function.
def display_fibonacci_sequence(num_terms):
if num_terms <= 0: #using condition

65
print("Please enter a positive integer.")
else: #using else statement
print("Fibonacci sequence:")
#using for loop with range
for i in range(num_terms):
print(fibonacci(i), end=" ") #print
#statement

# Taking input from the user


num_terms = int(input("Enter the number of
terms for Fibonacci sequence: "))

# Displaying Fibonacci sequence


display_fibonacci_sequence(num_terms)

43.Write a python program to add two


matrices.

#user can create variable A and assign


#matrices
A= [[1,5,8],
[4,6,7],
[7,2,3]]

66
#user can create variable B and assign
#matrices
B= [[4,5,6],
[8,9,1],
[3,5,6]]

#user can create variable result and assign


#empty matrices
result=[[0,0,0],
[0,0,0],
[0,0,0]]

#using for loop for with rows


for i in range(len(A)):

#using for loop for with column


for j in range(len(A[0])):

result[i][j]=A[i][j]+B[i][j]
print(result) #print statement for print result

44.Write a python program, How to


Transpose a matrix.
#user can create A variable and apply matrix
A= [[1,2,3],
[4,5,6]]

67
#user can create T variable and apply empty
#matrix
T= [[0,0],
[0,0],
[0,0]]
#using for loop for row with range
for i in range(len(A)):
#using for loop for column with range
for j in range(len(A[0])):
T[j][i]=A[i][j] #assigning the transpose
#using print statement for T matrix
print(T)

45.Write a program for hello world by


using the decorator function.
#user can use function with greet def greet():
print("hello world ") #using print

#user can use receiver function with decor


def decor(func1):
print("*"*20) #print 20 times *
func1() #calling
print("*"*20) #print 20 times *

decor(greet) #decorator added function

68
46.Write a program to check whether
a number is in a given range.
#using function
def test_range():
#taking input from user in variable of n
n=int(input("enter any number"))
#using if condition with range
if n in range(3,10):
#using print statement(if Block )
print(" %s is in the range"%str(n))
else: #using else
#using print statement (else block )
print("the number is outside the given
range.")
test_range() #testing the range

47.Write a program to find the most


repeated number from a list.

#find the most repeated number from list

69
max_count = 0
numbers=[1,2,3,3,3,4,5,6,73]
# Iterate through the list
for num in numbers:
# Count occurrences of the current number in
#the list
current_count = numbers.count(num)

# Update if the current number has more


#occurrences than the current maximum
if current_count > max_count:
most_repeated_number = num
max_count = current_count

# Print the most repeated number


print(f"The most repeated number is:
{most_repeated_number}")

48.Write a program to find the most


repeated number from a list without
using any functions and modules.
#user can create any list
list = [10, 5, 10, 15, 10, 15, 20, 10, 15,15,15]
dict = {} #creating empty dictionary
#using for loop for iterating values of list
for i in list:

70
if i in dict: #using conditional statement
dict[i] += 1 #assigning the value
else: #using else statements
dict[i] = 1 #assigning the value

#creating the variable and assign the value


most_com = max(dict, key=dict.get)
count = dict[most_com] #creating count
#variable and assign
print(f"The most repeated number:
{most_com}")
print(f"It appears {count} times.")

49.Write a program to find numbers


divisible by another number.
# using print statement
print("the number divisible by 13 are:")
#using for loop for iterating number which
#divisible by 13 under 100
for i in range(1,100):
#using if condition
if i%13==0:
print(i) # using print statement

71
50.Write a python program to catch
multiple handling in python.
#User can create string variable and take input
from user
string = input("Enter something here: ")
#using try function
try:
#User can create num variable and take
input from user
num = int(input("Enter a number here: "))
print(string + str(num)) # Convert num to
string before #concatenation
#using exception method and allies a
except(ValueError, TypeError) as a:
#using print statement
print(a)

72
51.Write a python program How to
print out without a newline.

#the user can print a statement with some text


and use the "end" element.
print("hello my all students", end= " ")
#the user can use a print statement with some
text.
print("how are you")

52.Write a Python program to count the


number of vowels in a string.(by using
function)
#the user can create a function with the name
count_vowels with parameters.
def count_vowels(s):
#creating variables and assigning vowel
alphabets in lower and upper case.
vowels = 'aeiouAEIOU'
#using return for sum

73
return sum(1 for char in s if char in vowels)
#the user can create a variable string and take
input from the user.
string = input("Enter a string: ")
#using print statements
print("Number of vowels:",
count_vowels(string))

53.Write a Python program to generate


Fibonacci series up to n terms.(by using
function)
#User can create an function with name
fibonacci with n argument
def fibonacci(n):
#user can create fib_series variable and
assign value 0,1 in list.
fib_series = [0, 1]
#using while loop with length and compare
with parameter
while len(fib_series) < n:
#using append method
fib_series.append(fib_series[-1] +
fib_series[-2])

74
#using the return function for less number of
#n.
return fib_series[:n]
#user can create n variable and take user input
from user
n = int(input("Enter the number of terms:"))
#using print statement
print("Fibonacci series:", fibonacci(n))

54.Write a Python program to check if a


number is prime or not.

#user can create a function name is_prime


#with parameter num.
def is_prime(num):
#using if the condition number is less than
#or equal to 1.
if num <= 1:
#using return false.
return False
#using for loop with range for iterating value
for i in range(2, int(num**0.5) + 1):
#using if statement for reminder is 0.
if num % i == 0:
return False

75
#using return
return True
#user can create num variable and take input
#from user
num = int(input("Enter a number: "))
#using if statements
if is_prime(num):
#using print statement
print(num, "is prime")
else: #using else
print(num, "is not prime")
#using a print statement.

55.Write a python program for


Reverse a String.
#the user can create a variable string and
#assign the string value.
string = "Sarjil Abdul Samad Satware"
#user can create a variable reversed_string and
#apply the reverse string slicing .
reversed_string = string[::-1]

76
#using print statements for reversed_string
#variables.
print("Reversed String:", reversed_string)

56.Write a python program to Find all


Duck numbers within a range

#user can create an function


#is_duck_number
#with parameter
def is_duck_number(num):
#creating num_str variable and assign the str
#of num
num_str = str(num)
#using the return o is in num_str and index
#0 is not equal to zero.
return '0' in num_str and num_str.index('0') !=
0
#the user can create a function
#find_duck_numbers with parameters start and
#end.
def find_duck_numbers(start, end):

77
#user can create variable #duck_numbers
#and assign empty list
duck_numbers = []
#using for loop with range
for num in range(start, end + 1):
#using if condition
if is_duck_number(num):
#using append method
duck_numbers.append(num)
#using the return function.
return duck_numbers
# Test the function
#user can create an variable start_range and
#take input from user
start_range = int(input("Enter the start of the
range: "))
#user can create an variable end_range and
#take input from the user.
end_range = int(input("Enter the end of the
range: "))
#using a print statement.
print("Duck numbers within the range",
start_range, "to", end_range, "are:")
#using print statements.
print(find_duck_numbers(start_range,
end_range))

78
57.Write a python program to Calculate
the power of a number.

#the user can create a function power with


#parameters base and exponent.
def power(base, exponent):
#using return base ** exponent for power of
#number
return base ** exponent
# Test the function
#user can create an variable base and take
#input from user
base = float(input("Enter the base: "))
#the user can create a variable exponent and
#take input from the user.
exponent = int(input("Enter the exponent: "))
#create variable results and assign the power
#of parameters.
result = power(base, exponent)
#using print statements.

79
print(f"{base} raised to the power of {exponent}
is {result}")

58.Write a python program to Find the


square root of a number.
#using the import math module.
import math
#user can create an function
#calculate_square_root with parameters
def calculate_square_root(num):
#using return with math function for sqrt of
#parameter.
return math.sqrt(num)
# Test the function.
#create a variable num and take input from the
#user.
num = float(input("Enter a number: "))
#user can create variable square_root and
#assign the function with parameters
square_root = calculate_square_root(num)
#using a print statement for square root.

80
print("Square root of", num, "is", square_root)

59.Write a python program to find the


cube root of a number.
#the user can create a function
#calculate_cube_root with parameters.
def calculate_cube_root(num):
#using return for parameter**(1/3)
return num ** (1/3)
# Test the function
#user can create a variable num and take input
#from a user.
num = float(input("Enter a number: "))
#creating cube_root variable and assign the
#function with parameter
cube_root = calculate_cube_root(num)
#using a print statement for cube root .
print("Cube root of", num, "is", cube_root)

81
60.Write a python program to Check if a
string is a valid email address.

#import re module
import re
#the user can create a function is_valid_email
with parameter email.
def is_valid_email(email):
#the user can create a variable pattern and
assign the value below.
pattern =
r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}
$'
# using return with regular expressions.
return re.match(pattern, email) is not None

# Test the function


#the user can create a variable email and take
#input from the user.

email = input("Enter an email address: ")


#using if condition with function
if is_valid_email(email):
#using print statement
print(email, "is a valid email address")

82
else: #using else with a print statement.
print(email, "is not a valid email address")

61.Write a python program to sort a


dictionary by value.
#User can create variable marks and apply
dictionary
marks={"sosun":23,"tehreen":20,"zayna":17,"fat
ima":20}
#using print statement for marks
print(marks)
#using empty print statement for space
print()
#User can create variable sv and apply sorted
method with items()
sv=sorted(marks.items(),key= lambda x:x[1])
#using print statement for sv
print(sv)

83
62. Write a program for inverted full
pyramid pattern by using Nested for
loop
#User can create a variable and take input
#from user for rows using input function

n=int(input("enter any number for:"))


#Using for loop with range of 0 and input
#number

for i in range(0,n):
#for loop for spaces
for j in range(0,i):
print(" ",end="") # print for spaces

#for loop for stars


for j1 in range(0,n-i):

print("*",end=" ") #print for stars


print() #empty print for new line

84
63. Write a program for Right half
pyramid pattern by using Nested for
loop
#User can create a variable and take input
#from user for rows using input function
n=int(input("enter any number for:"))
#using for loop with range of 0 and input
#number

for i in range(0,n):

#for loop for stars

for j in range(0,i+1):
print("*",end=" ") #print for stars
print() #empty print for new line

64. Write a program for left half


pyramid pattern by using Nested for
loop
#User can create a variable and take input
#from user for rows using input function

85
n=int(input("enter any number for:"))
#using for loop with range of 0 and input
#number
for i in range(0,n):
# this loop for spaces decrease
for j in range(0,n-(i+1)):
print(" ",end=" ") #print for spaces

#for loop for stars


for j1 in range(0,i+1):
print("*",end=" ") #print for stars
print() #empty print for new line

65. Write a program for Full Pyramid


pattern by using Nested for loop
#User can create a variable and take input
#from user for rows using input function
n=int(input("enter any number for:"))
#using for loop with range of 0 and input
#number

for i in range(0,n):

86
# this loop for spaces decrease
for j in range(0,n-(i+1)):

print(" ",end="") #print for spaces

#for loop for stars

for j1 in range(0,i+1):
print("*",end=" ") #print for stars
print() #empty print for new line

66.Write a program for Diamond


pattern by using Nested for loop

# user can create variable and take input for


#Reading number of row
row = int(input('Enter number of row: '))
# Upper part of diamond
for i in range(1, row+1):

87
for j in range(1,row-i+1): #for spaces
print(" ", end="")
for j in range(1, 2*i): # for stars
print("*", end="")
print()
# Lower part of diamond
for i in range(row-1,0, -1):
for j in range(1,row-i+1): #for spaces
print(" ", end="")

for j in range(1, 2*i): #for stars


print("*", end="")
print()

67.Write a program for square and


cube values by using the decorator
function.
#user can use function for square
def square(num):
return num**2 #return for square

#user can use function for cube

88
def cube(num):
return num**3 #return for cube

#user can use receiver function with decor


def decor(func,num):
print("*"*20) #print 20 times *
print(func(num)) #print return values
print("*"*20) #print 20 times *

decor(square,5) #decorator added


#function for square
# just for design
print("<<<<<<<<<<<<<(O_O)>>>>>>>>>>>>>
>>>>>>>>>>>>>>>>>>")
decor(cube,5) #decorator added
#function for cube

68.Write a program to compute


maximum elements from a list by
using lambda function with reduce
function.

89
#python program using a lambda function with
#reduce function

#to compute maximum element from list

import functools
#importing functools
#creating list

A=[11,34,54,65,90,23]
#using print statement

print("the maximum element of the list


is:",end="")

#using lambda and reduce function

print(functools.reduce(lambda a,b:a if a>b else


b,A))

69.Write a program to find factorial


using recursion.

#factorial of a number using recursion


#using function for factorial
def recur_factorial(n):

90
if n==1: #using if statement
return n #return the vales
else: #using else
return n*recur_factorial(n-1) #return the
#value of multiply by recur_function n-1
#create variable and take input from user
num=int(input("enter any number:"))
#check if the number is negative
if num<0: #using if num is less than 0
print("sorry,factorial is does not exist for
negative numbers")
elif num==0: #Using elif num==0
print("the factorial of 0 is 1") #Print
#statement
else: #Using else
#print statement for factorial
print("the factorial
of",num,"is",recur_factorial(num)

70.Write a program to slice


operations using arrays.

#import numpy libraries


from numpy import *

91
a=arange(20,26) #creating variables and
#assigning range values
print(a) #print a
b=a[1:6:1] #slicing,initially:ending:step 1
print(b) #print b

b=a[1:6:2] #slicing,initially:ending:step 2
print(b) #print b

b=a[-2:2:-1] #slicing,initially -2 :ending


2:step -1
print(b) #print b
b=a[:-2:] #removing last -2 element
print(b) #print b

71.Write a program to retrieve and


display elements of a numpy array
using while loop indexing.
#import numpy libraries
from numpy import *
a=arange(20,26) #creating variables and
#assigning range values

92
print(a) #print a

b=a[1:6:1] #slicing,initially:ending:step 1
print(b) #print b

b=a[-2:2:-1] #slicing,initially -2 :ending


#2:step -1
print(b) #print b

#creating variable i and assign the #value 0


i=0
while(i<len(a)): #using while loop for continue
print(a[i]) #print a[i]
i+=1 #assigning the value 1

72.Write a program to find the


transpose of a matrix by using an
array.

#import numpy libraries

93
import numpy as np

#creating array
x=np.array([[1,2,3],
[4,5,6],
[7,8,9]])

print("array is:\n",x) #print original array


x_transpose=x.T #creating variable and apply

#transpose
#print the X_transpose variable
print("transpose array:\n",x_transpose)

73.Write a program to retrieve and


display elements of a numpy array
using while loop indexing.
#import numpy libraries
import numpy as np
#creating array

94
x=np.array([[1,2,3],[4,5,6],[7,8,9]])
print("array is:\n",x) #print array
print(" ") #for spacing

rows=np.array([[0,0],[2,2]]) #accessing rows


cols=np.array([[0,1],[0,1]]) #accessing cols
y=x[rows,cols] #creating variable and assign

#the rows and cols values


print("the corner elements of this array
are:\n",y) #print y

74.Write a program to calculate the


sine of an array of angles(in radius)
Using Numpy.
#import numpy libraries
import numpy as np

95
#creating array
angles=np.array([3.14,3.14/2,6.28])
print("array is:\n",angles) #print original array

sine_of_angles=np.sin(angles) #creating
#variable and assign the sin(angles)

#print statements
print("sine of the given array of
angles=",sine_of_angles)

75.Write a program to calculate the


cosine similarity of 2 vectors(as
numpy arrays).

#import numpy libraries


import numpy as np
#creating array

angles=np.array([3.14,3.14/2,6.28])
print("array is:\n",angles) #print original array

96
cosine_of_angles=np.cos(angles) #creating
#variable and assign the scos(angles)
#print statements

print("cosine of the given array of


angles=",cosine_of_angles)

76.Write a program for converting


any string lower to uppercase and
upper to lowercase by using for loop
and nested if else.
#users can create variable and taking input in
#form of string
str1=input("enter any string:")
final_str=" " #creating empty final str

for i in str1: #using for loop


cur_car_val=ord(i) #creating variable for

97
#checking order of i

#using if conditions for lower case


if(cur_car_val >= 65 and cur_car_val <= 90):
cur_car_val +=32 #counting difference
#increment
lower_car=chr(cur_car_val) #assigning
#value
final_str +=lower_car #assigning value in

#final string and using increment operator

#using elif condition for upper case


elif(cur_car_val >= 97 and cur_car_val <=
122):
cur_car_val -=32 #counting difference
#decrement
upper_car=chr(cur_car_val) #assigning
#value

final_str +=upper_car #assigning value


#in final string and using decrement operator

else: #using else statement


final_str +=i #using for non alphabets
print(final_str) #print statement

98
77.Write a program for counting the
substring from string,using a for
loop.
#user can create any string like this
str="helloooooo"
#user can create substring
sub_str="ooo"
#create count variable for counting
count=0
#using for loop
for i in range(0,len(str)-2):
#using if for condition
if(str[i]=="o" and str[i:i+3]==sub_str):
count +=1 #assigning the count value
#with 1
#print the count values
print(count)

78.Write a program to print the user


input number of a fibonacci sequence
using a for loop.(example-2).

99
#user can create any variable and take input

terms=int(input("enter any number of terms


fibonacci series:"))

#creating variable f_term and assigning the


value 0
f_term=0

s_term=1 #creating variable s_term and


assigning the value 1.

temp=0 #creating variable temp and assigning


the value 0.

#using for loop with range of input


number(terms)
for i in range(terms):
if(i==0): #using if conditions
print(f_term) # print f_terms

elif(i==1): #using elif for another


#condition

print(s_term) #print the s_term

else: #using else

100
temp=f_term+s_term #assigning value for
temp
f_term=s_term #assigning value for
f_term
s_term=temp #assigning value for
s_term
print(s_term) #print s_term

79.Write a program to display power


of 2 using anonymous function.
#User can create variable terms and take input
#from user

terms=int(input("enter number of terms:"))


#the user can create a result variable and
#apply lambda with map function in list.

result=list(map(lambda x:2**x,range(terms+1)))
#using print statement for print the result
print(result)

101
#using for loop for iterating values
for i in range(terms+1):
#using print statement
print("the value of 2 raised to the
power",i,"is",result[i])

80.Write a python program to convert


decimal to binary ,octal and
hexadecimal.
#user can create a decimal variable and take

#input from user


decimal=int(input("enter a number here:"))

#using print statement


print("the conversion of decimal number is :")

#using print statement for binary conversion


print(bin(decimal),"in binary ")

#using print statement for octal conversion

102
print(oct(decimal),"in octal ")

#using print statement hexadecimal


conversion
print(hex(decimal),"in hexadecimal ")

81.Write a python program to find the


ASCII value of a character.

#user can create char variable and take input


#from a user.

char=input("enter any character here:")

#user can use the print statement for ascii


#value for given input number.

print("the ASCII value of",char,"is",ord(char))

103
82.Write a python program to convert
Decimal to Binary using Recursion.

#user can create a convertBinary function.


def convertBinary(n):

#user can apply conditional statements


if n>1:
convertBinary(n//2) #convert into floor
division

#using print statement for reminder


print(n%2,end= " ")
#user can create n variable and take input from
#user

n=int(input("enter any number:"))

#using print statements to print the binary of


the given number.

print("The binary of the given number is :")

convertBinary(n) #calling function

104
83.write a python program, How to
merge two dictionaries.
# User can create variable dict1 and make
dictionary 1
dict1 = {"abbas": 45, "rukhsar": 34, "hasan": 10}
# User can create another variable dict2 and
make dictionary 2
dict2 = {"sarjil": 22, "sufiyan": 25, "uvais": 20}
# Merge dictionaries using update() method
dict1.update(dict2)
# Print the merged dictionary
print(dict1)

84.Write a python program to access


the index of a list using a for loop in
python.
#create variable l and apply list
l=[34,5,61,54,89]
#using for loop with value in enumerate
for index,value in enumerate(l):
#using print statements for index and value.
print(index,value)

105
85.Write a python program how to
slice a list in python.
#user can create variable a and apply list with
some name
a=["sarjil","sufiyan","asad","khalid","uvais","sal
man"]

#using print statement for accessing first


element
print(a[0])

#using print statement for accessing all


element
print(a[0:6])

#using print statement accessing element with


steps 2
print(a[0:6:2])

106
86.Write a program to iterate over
Dictionaries using a for loop.

#the user can create a friend variable and


#apply a dictionary.
friends=
{"sarjil":"Raigad","umar":"thana","sarwar":"mum
bai"}

#using print statement for friends


print(friends)

#using for loop with key and values and


applying item() method
for key,value in friends.items():

#using print statements


print(key,value)

87.Write a python program ,How to


check if a list is empty in python.
#user can my_list variable and apply empty list
my_list=[]

107
#using if condition and checklist
if not my_list:
#using print statement
print("the list is empty")

88.Write a python program List


Manipulation.

#users can create a variable my_list and apply


#a list.
my_list = [1, 2, 3, 4, 5]

#using print statements


print("Original list:", my_list)

#using append method for add 6 element


my_list.append(6)

#using print statement


print("After appending 6:", my_list)

#using remove method for removing 3


elements
my_list.remove(3)

108
#using print statement
print("After removing 3:", my_list)

#using print statements for checking length by


#using len.
print("Length of list:", len(my_list))

89.Write a python program to Calculate


Simple Interest.
#user can create a variable principal and
assign the value by int.
principal = 10000
#user can create a variable rate and assign the
value by int.
rate = 5
#user can create a variable time and assign the
value by int.
time = 2
#the user can create a variable simple_intrest
and assign the formula.
simple_interest = (principal * rate * time) / 100

109
#using a print statement.
print("Simple interest:", simple_interest)

90.Write a python program to find the


average of numbers in a list.
#the user can create a function
#calculate_average with parameter numbers.
def calculate_average(numbers):
#the user can create a variable total and
#assign the sum method.
total = sum(numbers)
#the user can create a variable count and
#assign the len method.
count = len(numbers)
#using if condition count equal to 0.
if count == 0:
return 0 # To avoid division by zero if the
#list is empty
return total / count

# Test the function


#the user can create variable numbers and
#take input from the user.
numbers = [int(x) for x in input("Enter numbers
separated by space: ").split()]

110
#the user can create an variable average and
#assign the function.
average = calculate_average(numbers)
#using print statement for average
print("Average:", average)

111

You might also like