Python Programs AIML
Python Programs AIML
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.
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.
in three subjects. Display the student details, total marks and percentage with
suitable messages.
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")
else:
print("You are a not a senior citizen" ,age)
Output
enter your year of birth1990
Output
How many terms7
Fibonacci Series upto 7 :
0
1
1
2
3
5
8
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
Output
Value of ( 5 , 2 ) is 10.0
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
6
Mean of the numers: 4
Variance of the numbers: 2.5
Standard Deviation of the numbers: 1.5811388300841898
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
import operator
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
('in', 1)
('john', 5)
('the', 3)
('lives', 2)
('world', 2)
('go', 2)
('for', 2)
('have', 2)
('abc', 1)
('xyz', 1)
def sorting(filename):
infile = open(filename)
words = []
Output
Unsorted File (sample.txt)
john abc h g kjl res
Sorted File(result.txt)
abc g h john kjl res
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)
./folder1\new.txt
def DivExp(a,b):
try:
c=a/b
return c
except ZeroDivisionError:
return None
result=DivExp(a,b)
if result!=None:
Output
Enter the numerator5
class Complex:
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)
sum=Complex(0,0)
for i in range(N):
sum=add_complex(sum,Complex(real,imag))
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()
89
78
Name: John
USN: 28
Total: 255
Percentage: 85.0
LIST vs TUPLES
TUPLES
LIST
Lists are slower than tuples. Tuples are faster than list.
• 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.
Ans: An interpreted language is any programming language which is not in machine-level code
before runtime. Therefore, Python is an interpreted language.
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.
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.
Ans: An interpreted language is any programming language which is not in machine-level code
before runtime. Therefore, Python is an interpreted language.
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.
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}
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
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.
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.
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.
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: