0% found this document useful (0 votes)
79 views25 pages

Python Programs AIML

The document talks about Python programming language. It provides a brief history of Python, its uses and applications. It also lists some key reasons for using Python like being platform independent, having simple syntax and allowing rapid prototyping. The document further discusses some common applications of Python like GUI based apps, web development, games, scientific computing etc.

Uploaded by

svam81118
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
79 views25 pages

Python Programs AIML

The document talks about Python programming language. It provides a brief history of Python, its uses and applications. It also lists some key reasons for using Python like being platform independent, having simple syntax and allowing rapid prototyping. The document further discusses some common applications of Python like GUI based apps, web development, games, scientific computing etc.

Uploaded by

svam81118
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 25

East West Institute of Technology

(Affiliated to Visvesvaraya Technological University, Belagavi)


Department of CSE(AI&ML)

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.
• 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.

Dept of AI&ML,EWIT Prof. Madhushree C S


Applications :

1. GUI based desktop applications


2. Graphic design, image processing applications, Games, and Scientific/ computational
Applications
3. Web frameworks and applications
4. Enterprise and Business applications
5. Operating Systems
6. Education
7. Database Access
8. Language Development
9. Prototyping
10. Software Development

Dept of AI&ML,EWIT Prof. Madhushree C S


1a) Develop a program to read the student details like Name, USN and Marks

in three subjects. Display the student details, total marks and percentage with
suitable messages.

name=input("Enter the Student Name")


usn=input("Enter the USN")
sub1=int(input("Enter marks in Subject1:"))
sub2=int(input("Enter marks in Subject2:"))
sub3=int(input("Enter marks in Subject1:"))
total_marks=sub1+sub2+sub3
percentage=(total_marks/300)*100
print("Name:" ,name)

print("USN:",usn)
print("Subject 1:",sub1)
print("Subject 2:",sub2)
print("Subject 3:",sub3)
print("Total Marks:",total_marks)
print("Percentage:",percentage,"%")
if percentage>=90:
print("A+")
elif percentage>=80 and percentage<90:

print("A")

elif percentage>=70 and percentage<80:


print("B")
elif percentage>=60 and percentage<70:
print("C")
elif percentage<60:
print("D")

Dept of AI&ML,EWIT Prof. Madhushree C S


Output

Enter the Student Name us


Enter the USN 45
Enter marks in Subject1:34
Enter marks in Subject2:45
Enter marks in Subject1:45
Name: us
USN: 45
Subject 1: 34
Subject 2: 45
Subject 3: 45
Total Marks: 124
Percentage: 41.333333333333336 %

Dept of AI&ML,EWIT Prof. Madhushree C S


1b) Develop a program to read the name and year of birth of a person. Display
whether the person is a senior citizen or not.

year_of_birth=int(input("enter your year of birth"))


age = 2023 - year_of_birth
if age>=60:
print("You are a senior citizen", age)

else:
print("You are a not a senior citizen" ,age)

Output
enter your year of birth1990

You are a not a senior citizen 33

enter your year of birth1950


You are a senior citizen 73

Dept of AI&ML,EWIT Prof. Madhushree C S


2a) Develop a program to generate Fibinacci sequence of length(N).Read N
from the console.

N=int(input("How many terms"))


n1,n2=0,1
count=0
if N<=0:
print("Enter a positive number")
elif N==1:
print("Fibonacci Series upto", N,":")
print(n1)
else:
print("Fibonacci Series upto", N,":")
while count<N:
print(n1)
fib=n1+n2
n1=n2
n2=fib
count+=1

Output
How many terms7
Fibonacci Series upto 7 :
0
1

1
2
3
5
8

Dept of AI&ML,EWIT Prof. Madhushree C S


How many terms3
Fibonacci Series upto 3 :
0
1

2b) Write a function to calcualte factorial of a number.Develop a program to compute


binomial coefficient(Given N and R)

def factorial(n):
res=1
for i in range(2,n+1):

res=res*i
return res
def coefficent(n,r):
return factorial(n)/(factorial(r)*factorial(n-r))
n=5
r=2

print("Value of (",n,",",r,") is", co-efficent(n,r))

Output

Value of ( 5 , 2 ) is 10.0

Dept of AI&ML,EWIT Prof. Madhushree C S


3) Read N numbers from the console and create a list.Develop a program to print
mean,variance and standard deviation with suitable messages.

import statistics
numbers=[]
print("Enter the numbers:")
for i in range(0,5):
x=int(input())
numbers.append(x)
mean=statistics.mean(numbers)
variance=statistics.variance(numbers)
std_dev=statistics.stdev(numbers)
print("Mean of the numers:",mean)
print("Variance of the numbers:",variance)
print("Standard Deviation of the numbers:",std_dev)

Output

Enter the numbers:


2

6
Mean of the numers: 4
Variance of the numbers: 2.5
Standard Deviation of the numbers: 1.5811388300841898

Dept of AI&ML,EWIT Prof. Madhushree C S


4. Read a multi-digit number(as chars) from the console.Develop a program to print the
frequency of each digit with suitable message.

num=input("Enter a multi digit number")


freq={}
for i in num:
if i.isdigit():

if i in freq:
freq[i]+=1
else:
freq[i]=1
print("Frequency of each digit:")
for key,value in freq.items():
print("{}-{}".format(key,value))

Output
Enter a multi digit number45435
Frequency of each digit:
4-2

5-2
3-1

Dept of AI&ML,EWIT Prof. Madhushree C S


5. Develop a program to print 10 most frequently appearing words in a text file.(hint:Use
dictionary with distinct words and their frequency of occurences.Sort the dictionary in the
reverse order of frequency and display dictionary slice of first 10 items]

import operator

filename=input("Enter the name of the file:")


with open(filename,'r') as f:
words=f.read().split()
wordfreq={}
for w in words:
if w in wordfreq:
wordfreq[w]+=1
else:

wordfreq[w]=1
sorted_d=sorted(wordfreq.items(),key=operator.itemgetter(1),reverse=True)
print("The 10 most frequent words in the text file are:")
for i in range(10):
print(sorted_d[i-1])

Text File
john lives abc john xyz america world
john go for the world lives
john in the for go have the have john

Dept of AI&ML,EWIT Prof. Madhushree C S


Output

Enter the name of the file:sample.txt


The 10 most frequent words in the text file are:

('in', 1)

('john', 5)
('the', 3)
('lives', 2)
('world', 2)
('go', 2)

('for', 2)
('have', 2)
('abc', 1)
('xyz', 1)

Dept of AI&ML,EWIT Prof. Madhushree C S


6. Develop a program to sort the contents of a text file and write the sorted contents into a
separate text file [Hint: USe string methods strip(),len(),list methods sort(),append() and file
methods open(),readlines() and write()]

def sorting(filename):
infile = open(filename)
words = []

for line in infile:


temp = line.split()
for i in temp:
words.append(i)
infile.close()
words.sort()

outfile = open("result.txt", "w")


for i in words:
outfile.writelines(i)
outfile.writelines(" ")
outfile.close()
sorting("sample.txt")

Output
Unsorted File (sample.txt)
john abc h g kjl res
Sorted File(result.txt)
abc g h john kjl res

Dept of AI&ML,EWIT Prof. Madhushree C S


7) Develop a program to backing Up a given Folder(Folder in a current working directory)
into a ZIP file by using relevant modules and suitable methods.

from zipfile import ZipFile


import os
def get_all_file_paths(directory):
file_paths = []

for root, directories, files in os.walk(directory):


for filename in files:
filepath = os.path.join(root, filename)
file_paths.append(filepath)
return file_paths

def main():
directory = './folder1'
file_paths = get_all_file_paths(directory)
print('Following files will be zipped:')
for file_name in file_paths:
print(file_name)

with ZipFile('folder1.zip','w') as zip:


for file in file_paths:
zip.write(file)
print('All files zipped successfully!')
if name == " main ":
main()

Dept of AI&ML,EWIT Prof. Madhushree C S


Output

Following files will be zipped:

./folder1\New Text Document.txt

./folder1\new.txt

All files zipped successfully!

Dept of AI&ML,EWIT Prof. Madhushree C S


8. Write a function named DivExp which takes TWO parameters a,b and returns a value
c(c=a/b).Write suitable assertion for a>0 in function DivExp and raise an exception for when
b=0.Develop a suitable program which reads two values from the console and calls a function
DivExp.

def DivExp(a,b):

try:

c=a/b

return c

except ZeroDivisionError:

print("Cannot divide by zero")

return None

a=int(input("Enter the numerator"))

b=int(input("Enter the denominator"))

result=DivExp(a,b)

if result!=None:

print("The result is:",result)

Output
Enter the numerator5

Enter the denominator0


Cannot divide by zero

Dept of AI&ML,EWIT Prof. Madhushree C S


9. Define a function which takes TWO objects representing complex numbers and returns
new complex number with a addition of two complex numbers,Define a suitable class
‘Complex’ to represent the complex number.Develop a program to read N(N>=2) complex
numbers to compute the addition of N complex numbers.

class Complex:

def init (self,real,imag):

self.real=real

self.imag=imag

def add_complex(x,y):

real=x.real+y.real

imag=x.imag+y.imag

return Complex(real,imag)

N=int(input("Enter the number of complex numbers to add"))

sum=Complex(0,0)

for i in range(N):

real=int(input("Enter the real part of the complex number:"))

imag=int(input("Enter the imagionary part of the complex numbers"))

sum=add_complex(sum,Complex(real,imag))

print("The sum of complex numbers is:",sum.real,"+",sum.imag,"i")

Dept of AI&ML,EWIT Prof. Madhushree C S


Output

Enter the number of complex numbers to add 2


Enter the real part of the complex number:10

Enter the imagionary part of the complex numbers 2


Enter the real part of the complex number:5

Enter the imagionary part of the complex numbers2


The sum of complex numbers is: 15 + 4 i

Dept of AI&ML,EWIT Prof. Madhushree C S


10. Develop a program that uses class Student which prompts the user to enter marks in three
subjects and calculates total marks,percentage and displays the score card details.

class Student:
def init (self,name,usn):
self.name=name
self.usn=usn
self.marklist=[]
self.total_marks=0
def getMarks(self):
print("Enter marks in 3 subjects:")
for i in range(3):
m=int(input())
self.marklist.append(m)
self.total_marks+=m
def display(self):
print("Name:",self.name)
print("USN:",self.usn)
print("Total:",self.total_marks)
print("Percentage:",self.total_marks/3)
name=input("Enter your name:")
usn=input("Enter your USN:")
s1=Student(name,usn)
s1.getMarks()
s1.display()

Dept of AI&ML,EWIT Prof. Madhushree C S


Output

Enter your name:John


Enter your USN:28
Enter marks in 3 subjects:
88

89
78
Name: John
USN: 28
Total: 255
Percentage: 85.0

Dept of AI&ML,EWIT Prof. Madhushree C S


VIVA QUESTIONS

1. What is the difference between list and tuples in Python?

LIST vs TUPLES
TUPLES
LIST

Tuples are immutable (tuples are lists which can’t be


Lists are mutable i.e they can be edited.
edited).

Lists are slower than tuples. Tuples are faster than list.

Syntax: l1 = [10, ‘abc’, 20] Syntax: a1 = (10, ‘abc’ , 20)

2. What are the key features of Python?

• Python is an interpreted language. That means that, unlike languages like C and its variants,
Python does not need to be compiled before it is run. Other interpreted languages
include PHP and Ruby.
• Python is dynamically typed, this means that you don’t need to state the types of variables
when you declare them or anything like that. You can do things like x=111 and then x="I'm
a string" without error
• Python is well suited to object orientated programming in that it allows the definition of
classes along with composition and inheritance. Python does not have access specifiers (like
C++’s public, private).
• In Python, functions are first-class objects. This means that they can be assigned to
variables, returned from other functions and passed into functions. Classes are also first
class objects
• Writing Python code is quick but running it is often slower than compiled languages.
Fortunately,Python allows the inclusion of C-based extensions so bottlenecks can be
optimized away and often are. The numpy package is a good example of this, it’s really
quite quick because a lot of the number-crunching it does isn’t actually done by Python
• Python finds use in many spheres – web applications, automation, scientific modeling, big
data applications and many more. It’s also often used as “glue” code to get other languages
and components to play nice. Learn more about Big Data and its applications from the Data
Engineering Training Course.

Dept of AI&ML,EWIT Prof. Madhushree C S


3. What type of language is python? Programming or scripting?

Python is capable of scripting, but in general sense, it is considered as a general-purpose


programming language. To know more about Scripting, you can refer to the Python Scripting
Tutorial.

4. Python an interpreted language. Explain.

Ans: An interpreted language is any programming language which is not in machine-level code
before runtime. Therefore, Python is an interpreted language.

5. What are the benefits of using Python?

The benefits of using python are-

1. Easy to use– Python is a high-level programming language that is easy to use, read,
write and learn.
2. Interpreted language– Since python is interpreted language, it executes the code line
by line and stops if an error occurs in any line.
3. Dynamically typed– the developer does not assign data types to variables at the time
of coding. It automatically gets assigned during execution.
4. Free and open-source– Python is free to use and distribute. It is open source.
5. Extensive support for libraries– Python has vast libraries that contain almost any
function needed. It also further provides the facility to import other packages using
Python Package Manager(pip).
6. Portable– Python programs can run on any platform without requiring any change.
7. The data structures used in python are user friendly.
8. It provides more functionality with less coding.

6. What are the common built-in data types in Python?

The common built-in data types in python are-

Numbers– They include integers, floating-point numbers, and complex numbers. eg. 1, 7.9,3+4i

List– An ordered sequence of items is called a list. The elements of a list may belong to different data
types. Eg. [5,’market’,2.4]

Tuple– It is also an ordered sequence of elements. Unlike lists , tuples are immutable, which means
they can’t be changed. Eg. (3,’tool’,1)

String– A sequence of characters is called a string. They are declared within single or double-quotes.
Eg. “Sana”, ‘She is going to the market’, etc.

Set– Sets are a collection of unique items that are not in order. Eg. {7,6,8}
Dept of AI&ML,EWIT Prof. Madhushree C S
Python is capable of scripting, but in general sense, it is considered as a general-purpose
programming language. To know more about Scripting, you can refer to the Python Scripting
Tutorial.

6. Python an interpreted language. Explain.

Ans: An interpreted language is any programming language which is not in machine-level code
before runtime. Therefore, Python is an interpreted language.

7. What are the benefits of using Python?

The benefits of using python are-

9. Easy to use– Python is a high-level programming language that is easy to use, read,
write and learn.
10. Interpreted language– Since python is interpreted language, it executes the code line
by line and stops if an error occurs in any line.
11. Dynamically typed– the developer does not assign data types to variables at the time
of coding. It automatically gets assigned during execution.
12. Free and open-source– Python is free to use and distribute. It is open source.
13. Extensive support for libraries– Python has vast libraries that contain almost any
function needed. It also further provides the facility to import other packages using
Python Package Manager(pip).
14. Portable– Python programs can run on any platform without requiring any change.
15. The data structures used in python are user friendly.
16. It provides more functionality with less coding.

7. What are the common built-in data types in Python?

The common built-in data types in python are-

Numbers– They include integers, floating-point numbers, and complex numbers. eg. 1, 7.9,3+4i

List– An ordered sequence of items is called a list. The elements of a list may belong to different data
types. Eg. [5,’market’,2.4]

Tuple– It is also an ordered sequence of elements. Unlike lists , tuples are immutable, which means
they can’t be changed. Eg. (3,’tool’,1)

String– A sequence of characters is called a string. They are declared within single or double-quotes.
Eg. “Sana”, ‘She is going to the market’, etc.

Set– Sets are a collection of unique items that are not in order. Eg. {7,6,8}

Dept of AI&ML,EWIT Prof. Madhushree C S


Dictionary– A dictionary stores values in key and value pairs where each value can be accessed
through its key. The order of items is not important. Eg. {1:’apple’,2:’mango}

Boolean– There are 2 boolean values- True and False.

7.What are Keywords in Python?

Keywords in python are reserved words that have special meaning. They are generally used to
define type of variables. Keywords cannot be used for variable or function names. There are following
33 keywords in python.Eg.And,Or,Not,If

8. What are python modules?

Python modules are files containing Python code. This code can either be functions classes or
variables. A Python module is a .py file containing executable code.

9.What are local variables and global variables in Python?

Global Variables:

Variables declared outside a function or in global space are called global variables. These variables
can be accessed by any function in the program.

Local Variables:

Any variable declared inside a function is known as a local variable. This variable is present in the
local space and not in the global space.

Example:

1 a=2

2 def add():

3 b=3

4 c=a+b

5 print(c)

6a=add()Output: 5

Output: 5

When you try to access the local variable outside the function add(), it will throw an error.

10.What are functions in Python?

Dept of AI&ML,EWIT Prof. Madhushree C S


A function is a block of code which is executed only when it is called. To define a Python
function, the def keyword is used.

11. What is init ?

init is a method or constructor in Python. This method is automatically called to


allocate memory when a new object/ instance of a class is created. All classes have the __init
method.

12. What is a dictionary in Python?

The built-in datatypes in Python is called dictionary. It defines one-to-one relationship


between keys and values. Dictionaries contain pair of keys and their corresponding values.
Dictionaries are indexed by keys.

13. Why do we need break and continue in Python?

Both break and continue are statements that control flow in Python loops. break stops the
current loop from executing further and transfers the control to the next block. continue jumps to the
next iteration of the loop without exhausting it.

14. Explain about relational operators in Python.

Dept of AI&ML,EWIT Prof. Madhushree C S


15. What are assignment operators in

Python?

16. How do you take input in Python?

For taking input from the user, we have the function input(). The input() function takes, as an
argument, the text to be displayed for the task:

Dept of AI&ML,EWIT Prof. Madhushree C S

You might also like