BASICS OF PYTHON
PROGRAMMING
DEPARTMENT OF ELECTRONICS & COMMUNICATION
ENGINEERING
Submitted by ARJUN SARRAF
VTU13591
Submitted to Dr Kanimozhi
Assistant
Index
Schedul Complete Mark Pag
Ex.No Experiment Name
ed date d date s e
.
(15) No.
Introduction to Python language
1. and simple programming using
python
a) List of even numbers upto
a given number
b) ASCII distance
between two characters
2. c) Number of vowels in the
input string
d) List of even numbers from a
givenlist of numbers.(use
only comprehensions)
a) Binary form of agivennumber
b) Conversion of Base32 to octal
3. c) Conversion of a given
number into a given base
Finding whether a given number
4. has even number of 1’s in its
binary representation
a) Sorting a given list of strings
in the order
oftheirvowelcounts
b) Removing duplicates in aList
5. c) Finding whether the given
strings are anagrams or
not
d) Finding the top‘n’
most frequently occurring
chars and their respective
counts
a) Implementation of user
defined map() function
b) Generation of infinite
number of even numbers
c) Implementation of left
binary search
6.
d) Conversion of a positive
integer number into its prime
factorization form
e) Converting a given
iterable into a list
File and Exception handling
7.
Experiment No: Date: ……. /…….
INTRODUCTION TO PYTHON LANGUAGE AND SIMPLE
PROGRAMMING
Introduction
Python is a general-purpose programming language that is often applied in scripting
roles. So, Python is programming language as well as scripting language. Python is also
called as Interpreted language
Python is an object-oriented programming language created by Guido Rossum in
1989. It is ideally designed for rapid prototyping of complex applications. It has interfaces to
many OS system calls and libraries and is extensible to C or C++. Many large companies
use the Python programming language include NASA, Google, YouTube, BitTorrent, etc.
Python is widely used in Artificial Intelligence, Natural Language Generation, Neural
Networks and other advanced fields of Computer Science. Python had deep focus on code
readability & this class will teach you python from basics.
Characteristics of Python
It provides rich data types and easier to read syntax than any otherprogramming
languages
It is a platform independent scripted language with full access to operating systemAPI's
Compared to other programming languages, it allows more run-time flexibility
A module in Python may have one or more classes and free functions
For building large applications, Python can be compiled to byte-code
Python supports functional and structured programming as well as OOP
In Python, since there is no compilation step, editing, debugging and testing is fast.
Differences between programming and scripting language:
Pytho Scriptin
n g
Program Scripting a program is
executed (i.e. the source is first A script is interpreted
compiled, and the
result of that compilation is expected)
A "script" is code written in a scripting
A "program" in general, is a language. A scripting language is
sequence of instructions written so nothing but a type of programming
that a computer can perform certain language in which we can write code to
task. control another software application.
How to Install Python on Windows
Step 1: To download and install Python visit the official website of Python
http://www.python.org/downloads/ and choose your version. We have chosen Python
version 3.6.3
Step 2: Once the download is complete, run the exe for install Python. Now click on Install
Now.
Step 3: You can see Python installing at this point.
Step 4: When it finishes, you can see a screen that says the Setup was successful.
Now click on "Close".
Hello World: Create your First Python Program
When Python is installed, a program called IDLE is also installed along with it.
It provides graphical user interface to work with Python.
Open IDLE, Write the following code below and press enter.
o print("Hello, World!")
To create a file in IDLE, go to File > New Window (Shortcut: Ctrl+N). Write
Python code and save (Shortcut: Ctrl+S) with .py file extension like: hello.py or
your-first- program.py
o print("Hello, World!")
Go to Run > Run module (Shortcut: F5) and you can see the output.
Few Important Things to Remember
• To represent a statement in Python, newline (enter) is used.
• Use of semicolon at the end of the statement is optional (unlike languages like C/C++)
• In fact, it's recommended to omit semicolon at the end of the statement inPython
• Instead of curly braces { }, indentations are used to represent a block
Python Keywords
• Keywords are the reserved words(cannot be used as a identifier) in Python
• Are case sensitive
Python Identifiers
• Name given to entities like class, functions, variables etc. in Python
• Rules for writing identifiers
• Can be a combination of letters in lowercase (a to z) or uppercase (A to Z)
or digits (0 to 9) or an underscore (_)
• Cannot start with a digit
• 1variable is invalid, but variable1 is perfectly fine
• Keywords cannot be used as identifiers
• Cannot use special symbols like !, @, #, $, % etc. in ouridentifier.
Python Indentation
• Most of the programming languages like C, C++, Java use braces { } to define ablock
of code
• Python uses indentation
• A code block (body of a function, loop etc.) starts with indentation and ends with
the first un-indented line
Example:
Error due to incorrect indentation
Python Variable
• A variable is a named location used to store data in the memory.
• Alternatively, variables are container that hold data which can be changed later
throughout programming
Declaring Variables
• In Python, variables do not need declaration to reserve memory space.
• The "variable declaration" or "variable initialization" happens automatically when we
assign a value to a variable.
• We use the assignment operator = to assign the value to a variable.
Assigning Values to variables
Constants
• Value that cannot be altered by the program during normal execution.
• In Python, constants are usually declared and assigned on a module
• And then imported to the file
Defining constant Module
Data Types
• In python data types are classes and variables are instance (object) of theseclasses
• Different types of data types in python are:
• Python numbers
• Python lists
• Python tuples
• Python strings
• Python sets
• Python dictionary
Python List
• Ordered sequence of items
• Can contain heterogeneous data
• Syntax:
• Items separated by commas are enclosed within brackets [ ]
• Example: a= [1,2.2,'python']
• Lists are mutable, meaning, value of elements of a list can be altered.
Python Tuple
• Same as list but immutable.
• Used to write-protect the data
• Syntax:
Items separated by commas are enclosed within brackets ( )
• Example:
• t = (5,'program', 1+3j)
Python Strings
• use single quotes or double quotes to represent strings.
• Multi-line strings can be denoted using triple quotes, ''' or """.
• Example
• s = "This is a string"
• Strings are also immutable.
Python Set
• Unordered collection of unique items
• defined by values separated by comma inside braces { }
• Set have unique values. They eliminate duplicates.
• Since, set are unordered collection, indexing has no meaning.
• Hence the slicing operator [] does not work.
Python Dictionary
• An unordered collection of key-value pairs.
• Must know the key to retrieve the value.
• Are defined within braces {} with each item being a pair in the form key: value
• Key and value can be of any type
• Example
• Dict={key1:values1,key2:values2. }
Conversion between data types
• Conversion can be done by using different types of type conversion functions like:
• int(),
• float(),
• str() etc.
Python Input, Output and Import
• Widely used functions for standard input and output operations are:
• print() and
• input()
Input() function
• input() function to take the input from the user.
• The syntax for input() is :
• input([prompt])
• where prompt is the string we wish to display on the screen.
• It is optional
• Example
• In1=int(input(‘enter the number’)
• In2=input(‘enter the string’)
Python Import
• When our program grows bigger, it is a good idea to break it into different modules.
• A module is a file containing Python definitions and statements.
• Python modules have a filename and end with the extension .py
• Example
• from math import
pi Python Operators
• Operators are special symbols in Python that carry out arithmetic or logical computation.
• The value that the operator operates on is called the operand.
• For example:
>>> 2+3
5
• Here, + is the operator that performs addition.
• 2 and 3 are the operands and 5 is the output of the operation.
Types of operators
Arithmetic operator
Comparison operator
Logical operator
Bitwise operator
Assignment
operator Special
operators
• identity operator
• membership operator
Identity operators
• Is and is not are the identity operators in Python.
• They are used to check if two values (or variables) are located on the
same part of the memory.
Membership operators
• in and not in are the membership operators in Python
• They are used to test whether a value or variable is found in a sequence
(string, list, tuple, set and dictionary).
Python Namespace and Scope
• Name (also called identifier) is simply a name given to objects.
• Everything in Python is an object
• Name is a way to access the underlying object.
• For example:
• when we do the assignment a = 2, here 2 is an object stored in memory
and a is the name we associate it with
• We can get the address (in RAM) of some object through the built-in function, id()
Flowchart
Tabulation
Input Output
20 2,4,6,8,10,12,14,16,18
Experiment No: Date: 27. /08.
LIST OF EVEN NUMBERS UPTO A GIVEN
Aim:
To write a python program to get the list of even numbers up to a given number.
Equipment Required:
Python IDLE, PC with windows
Algorithm
Step by Step Algorithm
Step- 1: Start
Step-2: Give the user input
Step-3: Read the input
Step-4: for loop num in range
(2,a+1) Step -5: If num%2 is equal to
zero Step-6:print num
Step-6: End
Pseudo code Algorithm
a. start
b. input a
c. read a
d. for num in range of (2,a+1)
e. if num%2==0
f. print num
g. stop
Program:
a=int(input(‘enter the number’))
for num in range(2,a+1):
if num%2==0
print(‘the even number’,num)
Inference:
From this experiment we learnt to write a program for even
numbers with in a given range by using a for loop
Flowchart
Tabulation
Input Output
Ac 33
Experiment No: Date:
ASCII DISTANCE BETWEEN TWO
Aim:
To write a python program for ASCII DISTANCE BETWEEN TWO CHARACTERS
Equipment Required:
Python IDLE, PC with windows
10. Algorithm
Step1:-start
Step2:-get the input from
user Step3:-get the ord
values
Step4:-subtract the ord values stored
as z Step5:-print z
Step:-end
Pseudo code Algorithm
a. start
b. input a[0],a[1]
c. x=ord(a[0])
d. y=ord(a[1])
e. z=x-y
f. print z
g. stop
Program
at=input(‘enter the letter’)
x=ord(at[0])
y=ord(at[1]
) z=x-y
print(‘the distance is’,z)
Inference
From this experiment i havelearn to write a program for ascii distance between two characters
Flowchart
Tabulation
Input Output
Choshan kumar 4
Experiment No: Date:
NUMBER OF VOWELS IN AN INPUT
Aim:
To write a python program for number of vowels in a input string.
Equipment Required:
Python IDLE, PC with windows
10. Algorithm
Step by Step Algorithm
Step1:-start
Step2:-get the input string from the user
as a Step3:-vowels=0
Step4:-for i in a+1
Step5:- if vowels
=’aeiouAEIOU’ Step6:-count
vowels
Step7:-print vowels
Step8:-end
Pseudo code Algorithm
a. start
b. input a
c. assign vowels =0
d. for I in a range then go to if
e. if vowels =’aeiouAEIOU’
f. vowels= vowels+1
g. print vowels
h. end
Program
a=input(‘enter string’)
vowels=
0 for I in
a+1
if(‘i==a’ or’ i==e’ or’ i==I’ or’ i==o’ or’ i==u’ or’ i==A’ or’ i==E’ or’ i==I’ or’ i==O’ or’ i==U’) :
vowels=
vowels+1 print(vowels)
Inference
From this experiment i have learn to write a program for number of vowels in a input string
1152EC256 BASICS OF PYTHON PROGRAMMING LABORATORY
34
Flowchart
Tabulation
Input Output
11,22,33,44,55,66,77,88,99 22,44,66,88
1152EC256 BASICS OF PYTHON PROGRAMMING LABORATORY
35
Experiment No: Date:
LIST OF EVEN NUMBERS FROM A GIVEN LIST OF
Aim
:
To write a python program for a list of even numbers
from a given list of numbers.
Equipment Required:
Python IDLE, PC with windows
Algorithm
Step-1: start
Step-2: assign list =[11,22,33,44,55,66,77,88,99]
Step-3: for num in list
Step-4:if num%2==0
Step-5:print the num
Pseudo code Algorithm
a. start
b. assign list =[11,22,33,44,55,66,77,88,99]
c. for num in list
d. if num%2==0
e. print(‘num’)
1152EC256 BASICS OF PYTHON PROGRAMMING LABORATORY
36
1152EC256 BASICS OF PYTHON PROGRAMMING
LABORATORY 37
Program
list1 = [11,22,33,44,55,66,77,88,99]
for num in list:
if num%2==0
print(‘the even number’,num)
Inference
From this experiment i have learn to write the program for even numbers from the given list
Flowchart
Tabulation
Input Output
6 0b110
Experiment No:3a Date: 16-09-20
BINARY FORM OF A GIVEN NUMBER
Aim:
To find binary number from a given number
Equipment Required:
Python IDLE, PC with windows 10.
Algorithm
Step by Step Algorithm
Step-1 :- Start.
Step-2:- Give the number in the decimal input.
assign to x
Step-3:- convert the decimal value into binary
by using function bin(x) assign to y
Step-4:- Print the output binary number.
Step-6:- End
Pseudo code Algorithm
1. start
2. input decimal
3. read decimal
4. convert decimal to binary by using bin function
5. assign binary value to y
6. Print binary value y
7. end
Program:
X=int(input(‘enter the decimal numder’)
Y=bin(x)
Print(“the binary value of”,x,”is”,y)
Inference:
From this experiment i have learnt to write a program for converting decimal to
binary.
Flowchart:
Tabulation:
Input Output
1Y2P0IJ32E8E7 0o777777777
77777777777
7
Experiment No:3b Date: 16-09-2020
CONVERSION OF BASE36 TO
Aim:
To write a python program for conversion of base 36 to octal.
Equipment Required:
Python IDLE, PC with windows 10.
Algorithm
Step by Step Algorithm
Step-1: start
Step-2: give the user input as n
Step-3: read n
Step-4: now print oct(n)
Step-5:end
Pseudo code Algorithm:
1. start
2. input n
3. read n
4. print oct(n)
5. stop
Program:
n = int(input("enter the number"), 36)
print(oct(n))
Inference:
From this experiment i have learn to write the conversion of base36 to octal
FLOW CHART:-
TABULATION:-
Input Output
2 the value of 203 in octal 0o313
11001011
2
Experiment No:3c Date:16-09-20
CONVERSION OF NUMBER INTO
Aim:
To write a program for conversion of a given number into a given base
Equipment Required:
Python IDLE, PC with windows 10.
Algorithm
Step by Step Algorithm
Step1:-start
Step2:- enter the base number
Step3:-print the base number
Step4:-enter the number that want convert
Step5:-print the conversion numbers
Step6:-enter the conversion number
Step7:- if(x==1) print the value of b in binary bin(b) are else goto step8
Step8:- if(x==2) print the value of b in octal oct(b) are else goto step9
Step9:- if(x==3) print the value of b in hexagonal hex(b)
Step10:-end
Pseudo code Algorithm
1. start
2. a=enter the base number
3. print (a)
4. enter the number assign to x
5. print the conversion
numbers 6. if(x==1)
print the value of b in binary bin(b) are else goto step8
7. if(x==2)
print the value of b in octal oct(b) are else goto step9
8. if(x==3)
print the value of b in hexagonal hex(b)
9. stop
File £dt Fomat Run Options Window Hep
a- zns (znpuz ( ’enser s.e bAse oonhe r’ ) )
O X
b=ins(input('en:er your n:imLer '),a} fiña Edit Shell Debug Options Window Help
print(’I-binary, -occal,3-hexadecimal’} PytWon 3.B.2 (tags/v3.8.2:7b3ebS9, Feb 25 ?020, 23:03:10) (HfC v.1916 64 bit
x=iot(input(’en:«r che conve-sion nznber")) (AH
pziot (’the value ci ’.b,’ in binary’, bin(b))
›>›
= RESTART: C:\Dmera\LENOVO\AppDaca\Local\Programs\PytbOo\Pytboo88\base cOoveruti
prior (’roe value of ’,b,’ iz hexadecimal ’, hex(b}}
she value of 203 in octal 0o3l3
Program:
a= int(input("enter the base number"))
print(a)
b=int(input('enter your number '),a)
print("1-binary,2-octal,3-hexadecimal")
x=int(input("enter the conversion number"))
if(x==1):
print ("the value of ",b," in binary", bin(b))
if(x==2):
print ("the value of ",b," in octal", oct(b))
if(x==3):
print ("the value of ",b," in hexadecimal ", hex(b))
Inference:
From this experiment i have learnt to write a program for conversion of given
number to the given base.
Flowchart
TABULATION:-
Input Output
Enter the base number 10
enter a number 33
the given number in decimal is 33
the decimal number in binary form
is 0b100001
Even number of ones 2
Odd Number of zeros 4
Experiment Date: 08 /09
Write a program to check whether a given number has even number
of 1’s in its binaryrepresentation
Aim:-
To write a python program for checking whether a given number has even number of 1’s in its binary representation.
Equipment Required :-
Python IDLE, PC with windows 10.
Algorithm :-
Step by Step Algorithm
Step 1: Start
Step 2:Get the base number
Step3:Get the number
Step4:convert the number into binary form by using function bin() assign to z
Step5:print the decimal numder
Step6:check(z.count(‘1’)%2==0) Print the even numbers of one are else print the odd Number of ones
Step7: check(z.count('0')%2==0): print even number of zeros are else print odd Number of zeros
Step8: end
Pseudo code Algorithm :
1. Start
2. Get the base number assign to x
3. Get the number assign to y
4. Print y
5. Assign z=bin(y)
6. Print z
7. If(z.count(1)%2==0)
print("Even number of ones",z.count('1'))
else:
print("Odd Number of ones ",z.count('1'))
8. If(z.count(0)%2==0)
print("Even number of zeros ",z.count('0')-1)
else:
print("Odd Number of zeros ",z.count('0')-1)
9. End
OutPut:-
Program :-
x=int(input("Enter the base number"))
y=int(input("enter a number:"), x)
print("the given number in decimal is",y)
z=bin(y)
print ("the decimal number in binary form is",z)
if(z.count('1')%2 ==0):
print("Even number of ones",z.count('1'))
else:
print("Odd Number of ones ",z.count('1'))
if(z.count('0')%2==0):
print("Even number of zeros ",z.count('0')-1)
else:
print("Odd Number of zeros ",z.count('0')-1)
Inference :-
From this experiment , i learn how to design a python program for checking whether a given
number has even number of 1’s in its binary representation . Hence, i got output for finding program
for check whether a given number has even number of 1’s in its binary representation
Flowchart
TABULATION:-
Input Output
enter the sting choshan is a good boy
['is', 'a', 'boy', 'choshan',
'good']
Experiment No:5a Date:
PYTHON PROGRAM TO SORT A GIVEN LIST OF STRINGS IN THE ORDER OF
THEIR VOWEL COUNTS
Aim:-
To write a python program for Sorting a given list of strings in the order of their vowel counts
.Equipment Required :-
Python IDLE, PC with windows 10.
Algorithm :-
Step by Step Algorithm
Step1:- start
Step2:-Define the function vowel_count_test(string)
Step3:- Assign count=0
Step4:-check for character in a string and check if character is in ['a','e','i','o','u'] go to step5
Step5:-count=count+1 and return the count
Step6:- Get the string from user assign to a
Step7:-Sort the string
Step8:-print a
Step9:-end
Pseudo code Algorithm :
1. Start
2. Define vowel_count_test(string)
3. count=0
4. for z in string:
if z in ['a','e','i','o','u']:
count=count+1
5. return count
6. Get the string
7. Assign string to a
8. Sort a
9. Print a
10. End
OutPut:-
Program :-
def vowel_count_test(string):
count=0
for z in string:
if z in ['a','e','i','o','u']:
count=count+1
return count
a=input("enter the sting").split()
a.sort(key=vowel_count_test)
print(a)
Inference :-
From this experiment I had learn to write the code for sorting a given list of strings in the
order of their vowel counts
Flowchart
TABULATION:-
Input Output
enter the string choshan kumar
chosankumr
Experiment No:5b Date:
PYTHON PROGRAM TO REMOVE DUPLICATES IN A LIST
Aim:-
To write a python program for removing duplicates in a list
.Equipment Required :-
Python IDLE, PC with windows 10.
Algorithm :-
Step by Step Algorithm
Step1:- start
Step2:-Enter the string assign to a
Step3:-copy it to b
Step4:-for c in string a go to step 5are else go to step6
Step5:-If the c in b append with c
Step6:- ' '.join(b)
Step7:-print z
Step8:-end
Pseudo code Algorithm :
1. Start
2. Get the string
3. Assign to a
4. Copy to b
5. for c in a:
if c not in b:
b.append(c)
6. z= ' '.join(b)
7. print z
8. end
OutPut:-
Program :-
a=input("enter the string")
b=[]
for c in a:
if c not in b:
b.append(c)
z= ' '.join(b)
print(z)
Inference :-
From this experiment I had learn to write the code for removing duplicates in a List
Flowchart
TABULATION:-
Input Output
enter a string a listen
enter a string b silent
the string are anagrams
Experiment No:5c Date:
PYTHON PROGRAM TO FINDING WHETHER THE GIVEN STRINGS
ARE ANAGRAMS OR NOT
Aim:-
To write a python program for finding whether the given strings are anagrams or not.
.Equipment Required :-
Python IDLE, PC with windows 10.
Algorithm :-
Step by Step Algorithm
Step1:- start
Step2:-enter the string and assign to a
Step3:-enter the string and assign to b
Step4:-sorte the string a and assign to x
Step5:- sorte the string b and assign to y
Step6:-If x==y go to step7 are else goto step 8
Step7:- print the string are anagrams
Step8:- print the string are not anagrams
Step9:-end
Pseudo code Algorithm :
1. Start
2. Get the string
3. Assign to a
4. Get the string
5. Assign to b
6. X=sorted(a)
7. Y=sorted(b)
8. if x ==y:
print("the string are anagrams")
else:
print("the string are not anagrams")
9. end
OutPut:-
Program :-
a=input("enter a string a")
b=input("enter a string b")
x=sorted(a)
y=sorted(b)
if x ==y:
print("the string are anagrams")
else:
print("the string are not anagrams")
Inference :-
From this experiment I had learn to write the code for finding whether the given strings
are anagrams or not.
Flowchart
TABULATION:-
Input Output
enter a string achoshan kumar
occurs 2 times
a occurs 3 times
c occurs 1 times
h occurs 2 times
k occurs 1 times
m occurs 1 times
n occurs 1 times
o occurs 1 times
r occurs 1 times
s occurs 1 times
u occurs 1 times
Experiment No:5d Date:
FINDING THE TOP ‘N’ MOST FREQUENTLY OCCURING CHARS AND THEIR
RESPECTIVE COUNTS
Aim:-
To write a python program for finding the top ‘n’ most frequently occurring chars and their respective counts.
.Equipment Required :-
Python IDLE, PC with windows 10.
Algorithm :-
Step by Step Algorithm
Step1:- start
Step2:-enter the string and assign to a
Step3:-copy it l
Step4:-for z in a goto step 5 are else goto step6
Step5:-If z is not in l do the l.append(z)
Step6:-for z in sorted(l)
print("{} occurs {} times".format(z,a.count(z)))
step7:end
Pseudo code Algorithm :
1. Start
2. Get the string
3. Assign to a
4. Copy to l
5. for z in a:
if z not in l :
l.append(z)
6. for z in sorted(l):
print("{} occurs {} times".format(z,a.count(z)))
7. end
OutPut:-
Program :-
a=input("enter a string")
l=[]
for z in a:
if z not in l :
l.append(z)
for z in sorted(l):
print("{} occurs {} times".format(z,a.count(z)))
Inference :-
From this experiment I had learn to write the code for finding the top ‘n’ most frequently
occurring chars and their respective counts.