0% found this document useful (0 votes)
13 views

Unit 1 - Python Programming - Notes

For biher Chennai
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Unit 1 - Python Programming - Notes

For biher Chennai
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 34

UNIT I

DATA, EXPRESSIONS, STATEMENTS


UNIT I DATA, EXPRESSIONS, STATEMENTS 6 hours
Python interpreter and interactive mode; values and types: int, float, Boolean; variables,
expressions, statements, tuple assignment, operators and precedence, comments;

1. Introduction to python:
Python is a general-purpose interpreted, interactive, object-oriented, and
high-level programming language. It was created by Guido van Rossum
during 1985- 1990.
Python got its name from “Monty Python’s flying circus”. Python was
released in the year 2000.
 Python is interpreted: Python is processed at runtime by the
interpreter. You do not need to compile your program before
executing it.
 Python is Interactive: You can actually sit at a Python prompt and
interact with the interpreter directly to write your programs.
 Python is Object-Oriented: Python supports Object-Oriented style or
technique of programming that encapsulates code within objects.
 Python is a Beginner's Language: Python is a great language for the
beginner- level programmers and supports the development of a
wide range of applications.
1.1. Python Features:
 Easy-to-learn: Python is clearly defined and easily readable. The
structure of the program is very simple. It uses few keywords.
 Easy-to-maintain: Python's source code is fairly easy-to-maintain.
 Portable: Python can run on a wide variety of hardware platforms
and has the same interface on all platforms.
 Interpreted: Python is processed at runtime by the interpreter. So,
there is no need to compile a program before executing it. You can
simply run the program.
 Extensible: Programmers can embed python within their C,C++,Java
script
,ActiveX, etc.
 Free and Open Source: Anyone can freely distribute it, read the source
code, and edit it.
 High Level Language: When writing programs, programmers
concentrate on solutions of the current problem, no need to worry
about the low level details.
 Scalable: Python provides a better structure and support for large
programs than shell scripting.
1.2. Applications:
 Bit Torrent file sharing
 Google search engine, youtube
 Intel, Cisco, HP, IBM
 i–Robot
 NASA
 Facebook, Drop box
1.3. Python interpreter:
Interpreter: To execute a program in a high-level language by translating
it one line at a time.
Compiler: To translate a program written in a high-level language into a
low-level language all at once, in preparation for later execution.

Compiler Interpreter
Interpreter Takes Single
Compiler Takes Entire program as
instruction as
input
input
No Object Cod
Intermediate Object Code is Generated Intermediate is
e
Generated
Conditional Control Statements Conditional Statemen are
are Executes faster ts
Control Executes
slower
Memory Requirement is More(Since
Memory Requirement is Less
Object Code is Generated)
Every time higher level
Program need not be compiled every
program is
time
converted into lower level
program
Errors are displayed after Errors are displayed for every
entire instruction interpreted (if any)
program is checked
Example : C Compiler Example : PYTHON

1.4 Modes of python interpreter:


Python Interpreter is a program that reads and executes Python code. It
uses 2 modes of Execution.
1. Interactive mode
2. Script mode
Interactive mode:
 Interactive Mode, as the name suggests, allows us to interact with OS.
 When we type Python statement, interpreter displays the result(s)
immediately.

Advantages:
 Python, in interactive mode, is good enough to learn, experiment or
explore.
 Working in interactive mode is convenient for beginners and for
testing small pieces of code
Drawback:
 We cannot save the statements and have to retype all the
statements once again to re-run them.
 In interactive mode, you type Python programs and the interpreter
displays the result:
Script mode:
 In script mode, we type python program in a file and then use
interpreter to execute the content of the file.
 Scripts can be saved to disk for future use. Python scripts have the
extension .py, meaning that the filename ends with .py
 Save the code with filename.py and run the interpreter in script
mode to execute the script.
Interactive mode Script mode
A way of using the Python A way of using the Python
interpreter by typing commands interpreter to read and execute
and expressions at the statements in a script.
prompt.
Cant save and edit the code Can save and edit the code
If we want to experiment with the If we are very clear about the code,
code, we can use interactive mode. we can use script mode.
we cannot save the statements for we can save the statements for
further use and we have to retype further use and we no need to
all the statements to re-run them. retype
all the statements to re-run them.
We can see the results immediately. We cant see the code immediately.

Integrated Development Learning Environment (IDLE):


 Is a graphical user interface which is completely written in Python.
 It is bundled with the default implementation of the python
language and also comes with optional part of the Python
packaging.

Features of IDLE:
 Multi-window text editor with syntax highlighting.
 Auto completion with smart indentation.
 Python shell to display output with syntax highlighting.

2. VALUES AND DATA TYPES

Values:
Value can be any letter, number or string.
Eg, Values are 2, 42.0, and 'Hello, World!'. (These values belong to different
data types.)

Data type:
Every value in Python has a data type.
It is a set of values, and the allowable operations on those
values. Python has four standard data types:
Numbers:
 Number data type stores Numerical Values.
 This data type is immutable [i.e. values/items cannot be changed].
 Python supports following number types
1. integers
2. floating point numbers
3. Complex numbers.
2.1 integer:
Integers are the whole numbers consisting of +ve or –ve sign.

Example:
a=10
a=eval(input(“enter a
value”))
a=int(input(“enter a
value”))

2.2 Float:
it has decimal part and fractional part.

Example:
a=3.15
a=eval(input(“enter a
value”))
a=float(input(“enter a
value”))

2.3. Complex:
It is a combination of real and imaginary part.
Example:
2+5j
a+bi

Sequence:
 A sequence is an ordered collection of items, indexed by positive
integers.
 It is a combination of mutable (value can be changed) and immutable
(values cannot be changed) data types.
 There are three types of sequence data type available in Python, they
are
1. Strings
2. Lists
3. Tuples
2.4. Strings:
 String is defined as a continues set of characters represented in
quotation marks (either single quotes ( ‘ ) or double quotes ( “ ).
 An individual character in a string is accessed using a subscript
(index).
 The subscript should always be an integer (positive or negative).
 A subscript starts from 0 to n-1.
 Strings are immutable i.e. the contents of the string cannot be
changed after it is created.
 Python will get the input at run time by default as a string.
 Python does not support character data type. A string of size 1 can
be treated as characters.
1. single quotes (' ')
2. double quotes (" ")
3. triple quotes(“”” “”””)

Operations on string:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Member ship

>>>a=”HELLO”  Positive indexing helps in


indexing >>>print(a[0]) accessing the string from the
>>>H beginning
>>>print(a[-1])  Negative subscript helps in
>>>O accessing the string from the
end.
Print[0:4] – HELL The Slice[n : m] operator
Slicing: Print[ :3] – HEL extracts sub string from the
Print[0: ]- HELLO strings.
A segment of a string is called a
slice.
a=”save The + operator joins the text on
Concatenation ” both sides of the operator.
b=”eart
h”
print(a+
b)
saveeart
h
a=”panimalar ” The * operator repeats the string
Repetitions: print(3*a) on the left hand side times the
panimalarpanima value on right hand side.
lar panimalar

Membership: >>> s="good Using membership operators to


morning" check a particular character is in
>>>"m" string or not. Returns true if
in s True present
>>> "a" not in s
True
2.5 Lists
 List is an ordered sequence of items. Values in the list are called
elements / items.
 It can be written as a list of comma-separated items (values)
between square brackets[ ].
 Items in the lists can be of different data types.

Operations on list:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
create a list >>> a=[2,3,4,5,6,7,8,9,10] in this way we can
>>> print(a) create a list at compile
[2, 3, 4, 5, 6, 7, 8, 9, 10] time
Indexing >>> Accessing the item in
print(a[0]) 2 the position 0
>>> Accessing the item in
print(a[8]) 10 the position 8
>>> print(a[-1]) Accessing a last
10 element
using negative indexing.
Slicing >>> print(a[0:3])
[2, 3, 4]
>>> print(a[0:]) printing a part of the
[2, 3, 4, 5, 6, 7, 8, 9, 10] string.
>>>
print(a[:8]) [2,
3, 4, 5, 6, 7, 8,
9]
>>>b=[20,30] Adding and printing
Concatenation >>> print(a+b) the items of two
[2, 3, 4, 5, 6, 7, 8, 9, 10, 20, lists.
30]
>>> print(b*3) Create a multiple
Repetition [20, 30, 20, 30, 20, 30] copies of the same
string
>>>
print(a[2]) 4 Updating the list
Updating the list >>> a[2]=100 using index
>>> print(a) value
[2, 3, 100, 5, 6, 7, 8, 9, 10]
Inserting an >>> a. insert(0,"apple") Inserting an element in
element >>> print(a) 0th position
a=[“apple”,2,3,4,5,6,7,8,9,10]
Removing an >>> a. remove(“apple”) Removing an
element >>> print(a) element
a=[2,3,4,5,6,7,8,9,10] by giving the
element directly
2.6. Tuple:
 A tuple is same as list, except that the set of elements is enclosed in
parentheses
instead of square brackets.
 A tuple is an immutable list. i.e. once a tuple has been created, you
can't add elements to a tuple or remove elements from the tuple.
Benefit of Tuple:
 Tuples are faster than lists.
 If the user wants to protect the data from accidental changes, tuple
can be used.
 Tuples can be used as keys in dictionaries, while lists can't.
Operations on Tuples:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
Creating the tuple
Creating a tuple >>>a=(20,40,60,”apple”,”bal with elements
l”) of different data
types.
>>>print(a[0]) Accessing the item in
Indexing 20 the position 0
>>> a[2] Accessing the item in
60 the
position 2
Slicing >>>print(a[1: Displaying items from
3]) (40,60) 1st till 2nd.
Concatenation >>> b=(2,4) Adding tuple elements
>>>print(a+b) at the end of another
>>>(20,40,60,”apple”,”ball”, tuple elements
2,4)
Repetition >>>print(b*2) repeating the tuple in n
>>>(2,4,2,4) no of times
updating a tuple >>>a[2]=100 Altering the tuple data
Type Error: 'tuple' object type leads to error.
does not support item
assignment
2.7. Boolean:
 Boolean data type have two values either it can take 0 or 1.
 0 means False
 1 means True
 True and False is a keyword.

Example:
>>> 3==5
False
>>>
True+True 2
>>>
False+True 1
>>>
False*True 0
2.8. Dictionaries:
 Lists are ordered sets of objects, whereas dictionaries are unordered
sets.
 Dictionary is created by using curly brackets. i,e. { }
 Dictionaries are accessed via keys and not via their position.
 A dictionary is an associative array. Any key of the dictionary is
associated (or mapped) to a value.
 The values of a dictionary can be any Python data type. So
dictionaries are key- value-pairs
 Dictionaries don't support the sequence operation of the sequence
data types like strings, tuples and lists.

Creating a a={'name':"abi",'age':18,'mark':10 Creating the dictionary


dictionary 0} print(a) with elements of
{'name': 'abi', 'age': 18, 'mark': different data types.
100}
Indexing print(a['name']) Accessing the item with
abi keys.

2.9. Sets:
 Set is an unordered collection of values of any data type with no
duplicate entry.
 In set every element is unique.
 Elements are separated by”,” enclosed with { }

Example:
a={1,2,3,4,5,6,7,6,7}
print(a)
a={1,2,3,4,5,6
,7}

3. VARIABLES:
 A variable allows us to store a value by assigning it to a name,
which can be used later.
 Named memory locations to store values.
 Programmers generally choose names for their variables that are
meaningful.
 It can be of any length. No space is allowed.
 We don't need to declare a variable before using it. In Python, we
simply assign a value to a variable and it will exist.

Assigning values to variables:


= sign used to assign values to a variables.

Example:
a=5 // single assignment
a,b,c=2,3,4 // multiple
assignment
a=b=c=2 //assigning one value to multiple variables
4. KEYWORDS:
 Keywords are the reserved words in Python.
 We cannot use a keyword as variable name, function name
or any other identifier.
 They are used to define the syntax and structure of the Python
language.
 Keywords are case sensitive.

5. IDENTIFIERS:
 Identifier is the name given to entities like class, functions,
variables etc. in Python.
 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 (_).
 all are valid example.
 An identifier cannot start with a digit.
 Keywords cannot be used as identifiers.
 Cannot use special symbols like !, @, #, $, % etc. in our identifier.
 Identifier can be of any length.

Valid identifiers Invalid identifiers


Num Number 1
Num num 1
Num1 addition of program
_NUM 1Num
NUM_temp2 Num.no
IF if
Else else

6. STATEMENTS
 Instructions that a Python interpreter can executes are called
statements.
 A statement is a unit of code like creating a variable or displaying a
value.
>>> n = 17
>>> print(n)
 Here, The first line is an assignment statement that gives a value to n.
 The second line is a print statement that displays the value of n.
There are two types of statements available
1. single line statements
2. multi line statements
Single line statements:
single line statements are end with newline
Examples:
a=1
b=2
c=a+
b

Multiline statements:
python allows the user to write multi line statement using line
continuation character (\) to denote that the line should continue.

Example:
total=mark1+\
mark2
+\
mark3
7. INPUT AND
OUTPUT INPUT:
 Input is a data entered by user in the program.
 In python, input () function is available for input.

Syntax:
variable = input (“data”)

Example:
a=input("enter the name:")

How to get different data type from user:


Data type Compile time Run time
int a=10 a=int(input(“enter a”))
float a=10.5 a=float(input(“enter a”))
string a=”panimalar” a=input(“enter a string”)
list a=[20,30,40,50] a=list(input(“enter a list”))
tuple a=(20,30,40,50) a=tuple(input(“enter a tuple”))

OUTPUT:
 Output can be displayed to the user using Print statement.
Syntax:
print (expression/constant/variable)

Example:
print ("Hello") //
Hello print(5) //5
print(3+5) //8
Print(c)
8. COMMENTS:
 Comments are used to provide more details about the program like
name of the program, author of the program, date and time, etc.
Types of comments:
1. single line comments
2. multi line comments

Single line comments


 A hash sign (#) is the beginning of a comment.
 Anything written after # in a line is ignored by interpreter.
Example:
Percentage = (minute * 100) / 60 # calculating percentage of an hour

Multi line comments:


 Multiple line comments can be written using triple quotes “”” ”””

Example:
“”” This program is created by
Robert in Dell lab on
12/12/12
based on newtons method”””

9. LINES AND INDENTATION:


 Most of the programming languages like C, C++, Java use braces {
} to define a block of code. But, python uses indentation.
 Blocks of code are denoted by line indentation.
 It is a space given to the block of codes for class and function
definitions or flow control.

Example:
a=
3
b=
1
if a>b:
print("a is
greater") else:
print("b is greater")

10. TUPLE ASSIGNMENT


 An assignment to all of the elements in a tuple using a single
assignment statement.
 Python has a very powerful tuple assignment feature that allows a
tuple of variables on the left of an assignment to be assigned values
from a tuple on the right of the assignment
 The left side is a tuple of variables; the right side is a tuple of
values. Each value is assigned to its respective variable. All the
expressions on the right side are evaluated before any of the
assignments.
(a,b,c)=(3,4,5)
(a, b, c, d) = (1, 2, 3)
ValueError: need more than 3 values to
unpack Swapping two numbers using
tuple
(a, b) = (b, a)

11. OPERATORS:
 Operators are the constructs which can manipulate the value of
operands.
 Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands
and + is called

Types of Operators:
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators

Arithmetic operators:
They are used to perform mathematical operations like addition, subtraction,
multiplication etc.
Operator Description Example
a=10,b=20

+ Addition Adds values on either side of the operator. a + b = 30

- Subtraction Subtrac right hand operan from left hand a – b = -10


ts d
operan
d.
* Multiplies values on either side of the a * b = 200
Multiplicatio operator
n
/ Division Divides left hand operand by right hand b/a=2
operand
% Modulus Divides left hand operand by right hand b%a=0
operand and returns remainder

** Exponent Perform exponenti (power calculation on a**b =10 to


s al ) the power 20
operator
s
// Floor Division - The division of operands 5//2=2
where the result is the quotient in which
the digits after the decimal point are
removed
Comparison (Relational) Operators:
Comparison operators are used to compare values.
It either returns True or False according to the condition.
Operato Description Example
r a=10,b=20

== If the values of two operands are equal, then the (a == b)


condition becomes true. is not
true.
!= If values of two operands are not equal, then
(a!=b) is
condition becomes true.
true
> If the value of left operand is greater than the (a > b) is
value of right operand, then condition becomes not true.
true.
< If the value of left operand is less than the value of (a < b) is
right operand, then condition becomes true. true.

>= If the value of left operand is greater than or equal (a >= b)


to the value of right operand, then condition is not
becomes true. true.
<= If the value of left operand is less than or equal to (a <= b)
the value of right operand, then condition becomes is true.
true.

Assignment Operators:
Assignment operators are used in Python to assign values to variables.
Operator Description Example

= Assigns values from right side operands c = a + b


to left side operand assigns
value of a +
b into c
+= Add AND It adds right operand to the left operand c += a
and assign the result to left operand is
equivalent
to c
=c+a
-= Subtract It subtracts right operand from the left c -= a
AND operand and assign the result to left is
operand equivalent
to c
=c-a
*= Multiply It multiplies right operand with the left c *= a
AND operand and assign the result to left is
operand equivalent
to c
=c*a
/= Divide AND It divides left operand with the right c /= a
operand and assign the result to left is
operand equivalent
to c
= c / ac /= a
is equivalent
to c
=c/a
%= Modulus It takes modulus using two operands c %= a
AND and assign the result to left operand is
equivalent
to c
=c%a
**= Performs exponential (power) c **= a
calculation on operators and assign is
Exponent AND value to the left operand equivalent
to c
= c ** a
//= Floor It performs floor division on operators c //= a
Division and assign value to the left operand is
equivalent
to c
= c // a

Logical Operators:
Logical operators are and, or, not operators.

Bitwise Operators:
Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)

Membership Operators:
Evaluates to find a value or a variable is in the specified sequence of
string, list, tuple, dictionary or not.

Let, x=[5,3,6,4,1]. To check particular item in list or not, in and not in


operators are used.
Example:
x=[5,3,6,4,1]
>>> 5
in x
True
>>> 5 not
in x False

Identity Operators:
They are used to check if two values (or variables) are located on the same
part of the memory.

Example
x=5
y=5
a=
'Hello' b
=
'Hello'
print(x is not y) //
False print(a is
b)//True

Operator Precedence:
When an expression contains more than one operator, the order of evaluation
depends on the order of operations.
Operator Description

** Exponentiation (raise to the power)

~+- Complement, unary plus and


minus (method names for the
last two are +@ and -@)
* / % // Multiply, divide, modulo and floor division

+- Addition and subtraction

>> << Right and left bitwise shift


& Bitwise 'AND'
^| Bitwise exclusive `OR' and regular `OR'

<= < > >= Comparison operators

<> == != Equality operators

= %= /= //= -= += *= Assignment operators


**=
is is not Identity operators

in not in Membership operators

not or and Logical operators

12. Expressions:

 An expression is a combination of values, variables, and operators.


 A value all by itself is considered an expression, and also a variable.
 So the following are all legal expressions:

>>> 42
42
>>> a=2
>>>
a+3+2 7
>>> z=("hi"+"friend")
>>>
print(z)
hifriend

a=9-12/3+3*2-1 A=2*3+4%5-
a=? 3/2+6 find m=?
A=6+4%5-
3/2+6
a=9-4+3*2-1 A=6+4-3/2+6 m=-43||8&&0||-2
a=9-4+6-1 A=6+4-1+6 m=-43||0||-2
a=5+6-1 A=10-1+6 m=1||-2
a=11-1 A=9+ m=1
a=10 6
A=15
a=2,b=12,c=1 a=2*3+4%5-3//2+6
d=a<b>c a=2,b=12,c=1 a=6+4-1+6
d=2<12>1 d=a<b>c-1 a=10-1+6
d=1>1 d=2<12>1-1 a=15
d=0 d=2<12>0
d=1>0
d=1
PART A
1. What is interpreter?
2. What are the two modes of python?
3. List the features of python.
4. List the applications of python
5. List the difference between interactive and script mode
6. What is value in python?
7. What is identifier? and list the rules to name identifier.
8. What is keyword?
9. How to get data types in compile time and runtime?
10.What is indexing and types of indexing?
11.List out the operations on strings.
12.Explain slicing?
13.Explain below operations with the
example (i)Concatenation
(ii)Repetition
14.Give the difference between list and tuple
15.Differentiate Membership and Identity operators.
16.Compose the importance of indentation in python.
17.Evaluate the expression and find
the result (a+b)*c/d
a+b*c/d
18.Write a python program to print ‘n’ numbers.
19.Give the various data types in Python
20.Assess a program to assign and access variables.
21.Select and assign how an input operation was done in python.
22.Discover the difference between logical and bitwise operator.
23.Give the reserved words in Python.
24.Give the operator precedence in python.
25.Point out the uses of default arguments in python
25. Give the syntax for variable length arguments.
Part B
1. Explain in detail various data types in Python with an example.
2. Explain the different types of operators in python with an example.
3. Discuss the need and importance of function in python.
4. Explain in detail function prototypes in python.
5. Discuss the various type of arguments in python.
6. Explain the flow of execution in a user-defined function with an example.
7.Illustrate a program to display different data types using variables
and literal constants.
8. Explain in detail the various operators in python with suitable
examples.
9. Discuss the difference between tuples and list
10.Discuss the various operation that can be performed on a
tuple and Lists (minimum 5) with an example program
11.What are membership and identity operators?
12.Write a program to perform addition, subtraction,
multiplication, integer division, floor division and modulo
division on two integers and float.
13.Write a program to convert degrees Fahrenheit to Celsius
14.Discuss the need and importance of function in python.
15.Illustrate a program to exchange the value of two variables
with temporary variables
16.Analyze the difference between local and global variables.
17.Explain with an example program to circulate the values of n
variables
18.Analyze with a program to find out the distance between two points
using python.
19.Do the Case study and perform the following operation in tuples i)
Maxima minima iii) sum of two tuples iv) duplicate a tuple v) slicing
operator vi) obtaining a list from a tuple vii) Compare two tuples
viii) Printing two tuples of different data types

25 Unit 2: Data ,expressions, Statements by J.RANGANAYAKI/AP/ CSE

You might also like