[go: up one dir, main page]

0% found this document useful (0 votes)
82 views20 pages

Foss Lab Record (Expr 2,3)

The document discusses the introduction to Python programming language. It describes the features of Python like being an interpreted, object-oriented and high-level programming language. It also discusses how to install Python and different modes of executing Python code.

Uploaded by

Ratnakar1035
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
82 views20 pages

Foss Lab Record (Expr 2,3)

The document discusses the introduction to Python programming language. It describes the features of Python like being an interpreted, object-oriented and high-level programming language. It also discusses how to install Python and different modes of executing Python code.

Uploaded by

Ratnakar1035
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 20

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Experiment 2

AIM : Introduction to PYTHON


DESCRIPTION: Python is a simple, easy to learn, powerful, high level and object-oriented
programming language.

Python is an interpreted scripting language also. Guido Van Rossum is known as the founder of
python programming.

Python is an object-oriented, high level language, interpreted, dynamic and multipurpose


programming language.

Python is easy to learn yet powerful and versatile scripting language which makes it attractive for
Application Development.

Python's syntax and dynamic typing with its interpreted nature, make it an ideal language for
scripting and rapid application development in many areas.

Python supports multiple programming pattern, including object oriented programming, imperative
and functional programming or procedural styles.

Python is not intended to work on special area such as web programming. That is why it is known
as multipurpose because it can be used with web, enterprise, 3D CAD etc.

We don't need to use data types to declare variable because it is dynamically typed so we can write
a=10 to declare an integer value in a variable.

Python makes the development and debugging fast because there is no compilation step included in
python development and edit-test-debug cycle is very fast.

PYTHON Features:

1. Easy to use
2. Expressive Language
3. Interpreted Language
4. Cross platform Language
5. Free and open source
6. Object oriented Language
7. GUI Programming
8. Integrated

Installation of PYTHON :
1. To install Python, firstly download the Python distribution from www.python.org/download.

P.V.P SIDDHARTHA INSTITUTE OF TECHNOLOGY


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

2. Having downloaded the Python distribution now execute it. Double click on the
downloaded software. Follow the steps for installation:
3.

P.V.P SIDDHARTHA INSTITUTE OF TECHNOLOGY


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Click the Finish button and Python will be installed on your system.

P.V.P SIDDHARTHA INSTITUTE OF TECHNOLOGY


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Python Example
Python code is simple and easy to run. Here is a simple Python code that will print "Welcome to
Python".

A simple python example is given below.

>>> a="Welcome To Python"


>>> print a
Welcome To Python

How to execute python :


There are three different ways of working in Python:

1) Interactive Mode:
You can enter python in the command prompt and start working with Python.

Press Enter key and the Command Prompt will appear like:

P.V.P SIDDHARTHA INSTITUTE OF TECHNOLOGY


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Now you can execute your Python commands.

Eg:

2) Script Mode:

Using Script Mode , you can write your Python code in a separate file using any editor of your
Operating System.

P.V.P SIDDHARTHA INSTITUTE OF TECHNOLOGY


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Save it by .py extension.

Now open Command prompt and execute it by :

P.V.P SIDDHARTHA INSTITUTE OF TECHNOLOGY


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

NOTE: Path in the command prompt should be where you have saved your file. In the above case file
should be saved at desktop.

3) Using IDE: (Integrated Development Environment)

You can execute your Python code using a Graphical User Interface (GUI).

All you need to do is:

Click on Start button -> All Programs -> Python -> IDLE(Python GUI)

You can use both Interactive as well as Script mode in IDE.


1) Using Interactive mode:
Execute your Python code on the Python prompt and it will display result simultaneously.

P.V.P SIDDHARTHA INSTITUTE OF TECHNOLOGY


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

2) Using Script Mode:

i) Click on Start button -> All Programs -> Python -> IDLE(Python GUI)
ii) Python Shell will be opened. Now click on File -> New Window.
A new Editor will be opened . Write your Python code here.

Click on file -> save as

P.V.P SIDDHARTHA INSTITUTE OF TECHNOLOGY


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Run then code by clicking on Run in the Menu bar.

Run -> Run Module

Result will be displayed on a new Python shell as:

P.V.P SIDDHARTHA INSTITUTE OF TECHNOLOGY


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

1. comments :
# print('Hello, world!')

2. printing statment :
# This program prints Hello, world!
print('Hello, world!')

3. Python Output Using print() function :

print('This sentence is output to the screen')


# Output: This sentence is output to the screen
a=5

print('The value of a is', a)


# Output: The value of a is 5
In the second print() statement, we can notice that a space was added between the string and
the value of variable a.This is by default, but we can change it.

The actual syntax of the print() function is

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

Here, objects is the value(s) to be printed.

The 'sep' separator is used between the values. It defaults into a space character.
After all values are printed, end is printed. It defaults into a new line.
The file is the object where the values are printed and its default value is sys.stdout (screen). Here
are an example to illustrate this.
program :

print(1,2,3,4)
# Output: 1 2 3 4
print(1,2,3,4,sep='*')
# Output: 1*2*3*4
print(1,2,3,4,sep='#',end='&')
# Output: 1#2#3#4&

4. Output formatting :
Sometimes we would like to format our output to make it look attractive. This can be done by using
the str.format() method. This method is visible to any string object.

P.V.P SIDDHARTHA INSTITUTE OF TECHNOLOGY


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

>>> x = 5; y = 10
>>> print('The value of x is {} and y is {}'.format(x,y))
The value of x is 5 and y is 10

Here the curly braces {} are used as placeholders. We can specify the order in which it is printed by
using numbers (tuple index).
program :
print('I love {0} and {1}'.format('bread','butter'))
# Output: I love bread and butter

print('I love {1} and {0}'.format('bread','butter'))


# Output: I love butter and bread

5. Python Input :
input([prompt])
where prompt is the string we wish to display on the screen. It is optional.
>>> num = input('Enter a number: ')
Enter a number: 10
>>> num
'10'

2. Data types in Python : very value in Python has a datatype. Since everything is an object in
Python programming, data types are actually classes and variables are instance (object) of these
classes.

There are various data types in Python. Some of the important types are listed below.

a) Python Numbers :

Integers, floating point numbers and complex numbers falls under Python numbers
category. They are defined as int, float and complex class in Python.

We can use the type() function to know which class a variable or a value belongs to and the
isinstance() function to check if an object belongs to a particular class.

Integers can be of any length, it is only limited by the memory available.

A floating point number is accurate up to 15 decimal places. Integer and floating points are
separated by decimal points. 1 is integer, 1.0 is floating point number.

Complex numbers are written in the form, x + yj, where x is the real part and y is the imaginary
part.

Program :

P.V.P SIDDHARTHA INSTITUTE OF TECHNOLOGY


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

a=5

print(a, "is of type", type(a))


a = 2.0
print(a, is of type", type(a))
a = 1+2j
print(a, "is complex number?", isinstance(1+2j,complex))
output :
5 is of type <class 'int'>
2.0 is of type <class 'float'>
(1+2j) is complex number? True

b) Python List :
List is an ordered sequence of items. It is one of the most used datatype in Python and is very
flexible. All the items in a list do not need to be of the same type.
Declaring a list is pretty straight forward. Items separated by commas are enclosed
within brackets [ ].
We can use the slicing operator [ ] to extract an item or a range of items from a list. Index starts
form 0 in Python.
Program :
a = [5,10,15,20,25,30,35,40]
# a[2] = 15
print("a[2] = ", a[2])
# a[0:3] = [5, 10, 15]
print("a[0:3] = ", a[0:3])
# a[5:] = [30, 35, 40]
print("a[5:] = ", a[5:])
Lists are mutable, meaning, value of elements of a list can be altered.
a = [5,10,15,20,25,30,35,40]
a[2]=”hai”
# a[2] = 15

P.V.P SIDDHARTHA INSTITUTE OF TECHNOLOGY


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

print("a[2] = ", a[2])


# a[0:3] = [5, 10, 15]
print("a[0:3] = ", a[0:3])

# a[5:] = [30, 35, 40]


print("a[5:] = ", a[5:])

c) Python Strings :
String is sequence of Unicode characters. We can use single quotes or double quotes to represent
strings. Multi-line strings can be denoted using triple quotes, ''' or """.
>>> s = "This is a string"
>>> s = '''a multiline
Like list and tuple, slicing operator [ ] can be used with string. Strings are immutable.
Program:
s = 'Hello world!'
# s[4] = 'o'
print("s[4] = ", s[4])
# s[6:11] = 'world'
print("s[6:11] = ", s[6:11])
# Generates error
# Strings are immutable in Python
s[5] ='d'

e) Python Set :
Set is an unordered collection of unique items. Set is defined by values separated by
comma inside braces { }. Items in a set are not ordered. Every element is unique (no duplicates) and
must be immutable (which cannot be changed).
However, the set itself is mutable. We can add or remove items from it.
Sets can be used to perform mathematical set operations like union, intersection, symmetric
difference etc.
Program :
a = {5,2,3,1,4}

P.V.P SIDDHARTHA INSTITUTE OF TECHNOLOGY


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

# printing set variable


print("a = ", a)
# data type of variable a
print(type(a))
a) add elements from the set :
program :
# initialize my_set
my_set = {1,3}
print(my_set)
# if you uncomment line 9,
# you will get an error
# TypeError: 'set' object does not support indexing
#my_set[0]
# add an element
# Output: {1, 2, 3}
my_set.add(2)
print(my_set)
# add multiple elements
# Output: {1, 2, 3, 4}
my_set.update([2,3,4])
print(my_set)
# add list and set
# Output: {1, 2, 3, 4, 5, 6, 8}
my_set.update([4,5], {1,6,8})
print(my_set)

output :
When you run the program, the output will be:
{1, 3}
{1, 2, 3}

P.V.P SIDDHARTHA INSTITUTE OF TECHNOLOGY


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

{1, 2, 3, 4}
{1, 2, 3, 4, 5, 6, 8}
b) discard elements from the set :
A particular item can be removed from set using methods, discard() and remove().
The only difference between the two is that, while using discard() if the item does not exist in the
set, it remains unchanged. But remove() will raise an error in such condition.
Program :
# initialize my_set
my_set = {1, 3, 4, 5, 6}
print(my_set)
# discard an element
# Output: {1, 3, 5, 6}
my_set.discard(4)
print(my_set)
# remove an element
# Output: {1, 3, 5}
my_set.remove(6)
print(my_set)
# discard an element
# not present in my_set
# Output: {1, 3, 5}
my_set.discard(2)
print(my_set)
# remove an element
# not present in my_set
# If you uncomment line 27,
# you will get an error.
# Output: KeyError: 2
#my_set.remove(2)
Similarly, we can remove and return an item using the pop() method.

P.V.P SIDDHARTHA INSTITUTE OF TECHNOLOGY


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Set being unordered, there is no way of determining which item will be popped. It is completely
arbitrary.
We can also remove all items from a set using clear().
Program :
# initialize my_set
# Output: set of unique elements
my_set = set("HelloWorld")
print(my_set)
# pop an element
# Output: random element
print(my_set.pop())
# pop another element
# Output: random element
my_set.pop()
print(my_set)
# clear my_set
#Output: set()
my_set.clear()
print(my_set)

SAMPLE PROGRAMS

AIM : WAP to find the Factorial of a number


PROGRAM :

P.V.P SIDDHARTHA INSTITUTE OF TECHNOLOGY


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

# take input from user


num=int(input(“ Enter a Number :”))
factorial=1
#check if the number is –ve,+ve or 0
if num<0:
print(“ Sorry, Factorial doesn’t exist for –ve no’s”);
elif num==0:
print(“The factorial of 0 is 1 “);
else :
for i in range(1,num+1):
factorial=factorial*i;
print(“The factorial of “,num,”is” factorial)

OUTPUT :
Enter a No : 5
(‘The Factorial of”, 5, “is”,120)

AIM : WAP to check whether the given number is prime or not


PROGRAM :

num=int(raw_input("Enter a number "))


# prime numbers are greater than 1
if num > 1:
# check for factors
for i in range(2,num):
if (num % i) == 0:
print num,"is not a prime number"
print i,"is a factor of ",num
break
else:
print num,"is a prime number"

# if input number is less than


# or equal to 1, it is not prime
else:
print num,"is not a prime number"

OUTPUT :
Enter a Number : 25
25 is not a prime number
5 is a factor of 25.

P.V.P SIDDHARTHA INSTITUTE OF TECHNOLOGY


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Experiment 3
AIM : WAP to check to select off numbers from the list
PROGRAM :

a=[11,12,13,14,15,16,17,18,19,20,21,31,44,45,10];
print(“List is :”,a);

P.V.P SIDDHARTHA INSTITUTE OF TECHNOLOGY


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

n=len(a);
print(“length:”,n);
i=0;
print(“odd number”);
for i in range (len(a));
if(a[i]%2==1):
print(a[i]);

OUTPUT :
(‘List is :’,[11,12,13,14,15,16,17,18,19,20,21,31,44,45,10])
(‘length:’,15)
odd number
11 13 15 17 19 21 31 45

AIM : WAP to display the Celsius value


PROGRAM:
a= input(“enter the Celsius value :”)
f=(a*1.8)
b=t+32;
print b

OUTPUT :
Enter the Celsius value : 2
35.6

AIM : WAP to display the Fibonacci Series values


PROGRAM:
a,b=0,1
while b<200;
print b
a,b=b,a+b

OUTPUT :1 2 3 5 13 21 34 55 89 144
AIM : WAP to display the even or odd
PROGRAM:
a=int(raw_input(“please enter an integer :”));
if(a%2==1):
print ‘a ‘ + ‘is odd.’
else:
print ‘a’ + ‘is even.’

P.V.P SIDDHARTHA INSTITUTE OF TECHNOLOGY


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

OUTPUT :
Please enter an integer : 6
a is even

AIM : WAP to display the Calendar


PROGRAM:
#import module
import calendar
yy=int(input(“Enter Year:”))
mm=int(input(“Enter Month:”))
print(calendar month (yy,mm))

OUTPUT :
Enter Year : 2014
Enter month : 11
November 2014
Mon Tues wed thu fri sat sun
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30

AIM : WAP to find the ASCII value of a character


PROGRAM:
c=input(“Enter a Character:”);
print(“Ascii value of ‘”+c”’ is “, ard©)

OUTPUT :
Enter a Character : P
ASCII value of ‘p’ is 112

P.V.P SIDDHARTHA INSTITUTE OF TECHNOLOGY

You might also like