Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Introduction to Python: Data, Expressions, Statements, and Applications, Study notes of Computer Applications

An introduction to Python programming language, including its interpreter and interactive mode, values and types, variables, expressions, statements, modules, and functions. It also covers the features of Python, its applications, and the modes of execution. the sequence data types available in Python, including strings, lists, and tuples, and the operations that can be performed on them. It also provides examples of how to create, access, slice, concatenate, repeat, update, insert, and delete elements in lists.

Typology: Study notes

2022/2023

Available from 02/10/2024

karthik-a-nair
karthik-a-nair 🇮🇳

5 documents

1 / 31

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
31
UNIT II
DATA, EXPRESSIONS, STATEMENTS
Python interpreter and interactive mode; values and types: int, float, boolean, string, and list; variables,
expressions, statements, tuple assignment, precedence of operators, comments; Modules and functions,
function definition and use, flow of execution, parameters and arguments; Illustrative programs: exchange
the values of two variables, circulate the values of n variables, distance between two points.
1.
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.
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++,JavaScript
, 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.
Applications:
Bit Torrent file sharing
Google search engine, YouTube
Intel, Cisco, HP,IBM
iRobot
NASA
Face book, Drop box
INTRODUCTION TO PYTHON:
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f

Partial preview of the text

Download Introduction to Python: Data, Expressions, Statements, and Applications and more Study notes Computer Applications in PDF only on Docsity!

UNIT II

DATA, EXPRESSIONS, STATEMENTS

Python interpreter and interactive mode; values and types: int, float, boolean, string, and list; variables,

expressions, statements, tuple assignment, precedence of operators, comments; Modules and functions,

function definition and use, flow of execution, parameters and arguments; Illustrative programs: exchange

the values of two variables, circulate the values of n variables, distance between two points.

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.

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++,JavaScript

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

Applications:

Bit Torrent file sharing

Google search engine, YouTube

Intel, Cisco, HP,IBM

i–Robot

NASA

Face book, Drop box

INTRODUCTION TO PYTHON:

Python interpreter:

Interpreter: To execute a program in a high-level language by translating it one line ata 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

Compiler Takes Entire program as input

Interpreter Takes Single instruction as input

Intermediate Object Code is Generated

No Intermediate is

Generated

Object Code

Conditional Control Statements are

Executes faster

Conditional Control

Executes slower

Statements are

Memory Requirement is More (Since Object

Code is Generated)

Memory Requirement is Less

Program need not be compiled every time

Every time higher level program is

converted into lower level program

Errors are displayed after entire program is checked Errors are displayed for every instruction

interpreted (if any)

Example : C Compiler Example : PYTHON

Modes of python interpreter :

Python Interprete r 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:

The chevron, >>>, is the prompt the interpreter uses to indicate that it is ready for you to enter code. If you

type 1 + 1, the interpreter replies 2.

print ('Hello, World!')

Hello, World!

Auto completion with smart indentation.

Python shell to display output with syntax highlighting.

2 .VALUES AND DATATYPES

Value:

Value can be any letter, number or string.

Eg, Values are 2, 42.0, and 'Hello, World!'. (These values belong to different datatypes.)

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 integers, floating point numbers and complex numbers. They are defined as,

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)

datatypes.

 There are three types of sequence data type available in Python, they are

**1. Strings

  1. Lists
  2. Tuples**

Strings:

 A String in Python consists of a series or sequence of characters - letters, numbers, and special

characters.

 Strings are marked by quotes:

• Single quotes(' ') E.g., 'This a string in single quotes'

• double quotes(" ") E.g., "'This a string in double quotes'"

• triple quotes(""" """)E.g., """This is a paragraph. It is made up of multiple

lines and sentences."""

 Individual character in a string is accessed using a subscript(index).

 Characters can be accessed using indexing and slicing operations .Strings are

Immutable i.e the contents of the string cannot be changed after it is created.

Indexing:

• Positive indexing helps in accessing the string from the beginning

• Negative subscript helps in accessing the string from the end.

• Subscript 0 or – ven(where n is length of the string) displays the first element.

Example: A[0] or A[-5] will display “H”

• Subscript 1 or – ve (n-1) displays the second element.

Example: A[1] or A[-4] will display “E”

Operations on string:

i. Indexing

ii. Slicing

iii. Concatenation

iv. Repetitions

v. Membership

Creating a string >>> s="good morning" Creating the list with elements of different

data types.

Indexing >>> print(s[2])

o

print(s[6])

O

 Accessing

position 0

 Accessing

position

the

the

item

item

in

in

the

the

Slicing( ending

position - 1)

print(s[2:])

od morning

  • Displaying items from 2

nd till

last.

6.78, 9]

Repetition

list2*

['god', 6.78, 9, 'god', 6.78, 9, 'god',

6.78, 9]

Creates new strings, concatenating

multiple

copies of the same string

Updating the list >>> list1[2]=

print( list1)

[‘python’, 7.79, 45, ‘hello’]

Updating the list using index value

Inserting an element

list1.insert(2,"program")

print(list1)

['python', 7.79, 'program', 45,

'hello']

Inserting an element in 2

nd position

Removing an element

list1.remove(45)

print(list1)

['python', 7.79, 'program', 'hello']

Removing an element by

giving the element directly

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.

Basic Operations:

Creating a tuple >>> t=("python", 7.79, 101,

"hello”)

Creating the tuple with elements

of different data types.

Indexing

print(t[0]) python

t[2]

 Accessing the item in the

position

 Accessing the item in the

position

Slicing( ending

position - 1)

print(t[1:3])

 Displaying items from1st

till2nd.

Concatenation >>> t+("ram", 67)

('python', 7.79, 101, 'hello', 'ram',

 Adding tuple elements at

the end of another tuple elements

Repetition >>> print(t2)*

('python', 7.79, 101, 'hello',

'python', 7.79, 101, 'hello')

 Creates new strings,

concatenating multiple copies of the

same string

Altering the tuple data type leads to error. Following error occurs when user tries to do.

Mapping

  • This data type is unordered and mutable.
  • Dictionaries fall under Mappings.

Dictionaries:

 Lists are ordered sets of objects, whereas dictionaries are unorderedsets.

 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 (also known as hashes). 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 unordered key-value-

pairs( The association of a key and a value is called a key- value pair)

Dictionaries don't support the sequence operation of the sequence data types like strings, tuples and lists.

Creating a

dictionary

>>> food = {"ham":"yes", "egg" :

"yes", "rate":450 }

print(food)

{'rate': 450, 'egg': 'yes', 'ham':

'yes'}

Creating

elements

types.

the

of

dictionary

different

with

data

Indexing >>>> print(food["rate"])

Accessing the item with keys.

Slicing( ending

position - 1)

print(t[1:3])

Displaying items from 1st till 2nd.

If you try to access a key which doesn't exist, you will get an error message:

words = {"house" : "Haus", "cat":"Katze"}

words["car"]

Traceback (most recent call last): File

"", line 1, in KeyError: 'car'

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”))

>>>t[0]="a"

Trace back (most recent call last):

File "", line 1, in

Type Error: 'tuple' object does not support item assignment

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

Example:

Names like myClass, var_1, and this_is_a_long_variabl e

Valid declarations Invalid declarations

Num Number 1

Num num

Num1 addition of program

_NUM 1Num

NUM_temp2 Num.no

IF if

Else else

STATEMENTS AND EXPRESSIONS:

Statements :

  • Instructions that a Python interpreter can executes are called statements.
  • A statement is a unit of code like creating a variable or displaying avalue.

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.

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:

a=

a+3+2 7

z=("hi"+"friend")

print(z) hifriend

INPUT AND OUTPUT

INPUT: Input is data entered by user (end user) in the program. In python, input

() function is available for input.

Syntax for input() is:

variable = input (“data”)

Example:

#python accepts string as default data type. Conversion is required for type.

OUTPUT: Output can be displayed to the user using Print statement.

Example:

COMMENTS:

A hash sign (#) is the beginning of a comment.

Anything written after # in a line is ignored by interpreter.

Eg: percentage = (minute * 100)/60 # calculating percentage of an hour

Python does not have multiple-line commenting feature. You have to comment each line

individually as follows:

Example :

This is a comment.

This is a comment, too.

I said that already.

DOCSTRING:

Docstring is short for documentation string.

It is a string that occurs as the first statement in a module, function, class, or method definition. We

must write what a function/class does in the docstring.

Triple quotes are used while writing docstrings.

Syntax:

functionname__doc.__ Example:

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.

def double(num):

"""Function to double thevalue"""

return2*num

>>>print (double.doc)

Function to double the value

>>> print ("Hello")

Hello

Syntax:

print (expression/constant/variable)

>>>y=int(input("enter the number"))

enter the number 3

>>> x=input("enter the name:")

enter the name: george

  • Tuple assignment solves this problem neatly:
  • One way to think of tuple assignment is as tuple packing/unpacking.

In tuple packing, the values on the left are ‘packed’ together in a tuple:

  • In tuple unpacking, the values in a tuple on the right are ‘unpacked ‘into the variables/names on the

right:

  • The right side can be any kind of sequence (string, list,tuple)

Example:

  • To split an email address in to user name and a domain

mailid='god@abc.org'

name,domain=mailid.split('@')

print name god

print (domain) abc.org

4.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 operator

Types of Operators:

  • Python language supports the following types of operators

• Arithmetic Operators

• Comparison (Relational)Operators

• Assignment Operators

• Logical Operators

• Bitwise Operators

• Membership Operators

• Identity Operators

(a, b) = (b, a)

>>> b = ("George",25,"20000") # tuplepacking

>>> (name, age, salary)=b # tupleunpacking

>>> name

'George'

>>> age

>>> salary

>>> b = ("George", 25, "20000") # tuple packing

Arithmetic operators:

They are used to perform mathematical operations like addition, subtraction, multiplication etc.

Assume, a=10 and b=

Operator Description Example

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

operand.

right hand operand from left hand a – b = - 10

  • Multiplication Multiplies values on either side of the operator a * b = 200

/ Division Divides left hand operand by right hand operand b / a = 2

% Modulus Divides left hand operand by right hand operand and returns

remainder

b % a = 0

** Exponent Performs

operators

exponential (power) calculation on a**b =10 to the

power 20

// Floor Division - The division of operands where the result is the

quotient in which the digits after the decimal point are removed

Examples

a=

b=

print("a+b=",a+b)

print("a-b=",a-b)

print("ab=",ab)

print("a/b=",a/b)

print("a%b=",a%b)

print("a//b=",a//b)

print("ab=",ab)

Output:

a+b=

a-b= 5

a*b= 50

a/b= 2.

a%b=

a//b=

a**b= 100000

Comparison (Relational)Operators:

• Comparison operators are used to compare values.

• It either returns True or False according to the condition. Assume, a=10 and b=

Operator Description Example

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

AND

Multiply It multiplies right operand with the left operand and assign the

result to left operand

c *= a is

equivalent to c

= c *a

AND

Divide It divides left operand with the right operand and assign the result

to left operand

c /= a is

equivalent to c

= c /ac

/= a is

equivalent to c

= c /a

AND

Modulus It takes modulus using two operands and assign the result to left

operand

c %= a is

equivalent to c

= c % a

**= Exponent

AND

Performs exponential (power) calculation on

operators and assign value to the left operand

c **= a is

equivalent to c

= c ** a

//= Floor

Division

It performs floor division on operators and assign value to the left

operand

c //= a is

equivalent to c

= c // a

Example

a =

b =

c = 0

c = a + b

print("Line 1 - Value of c is ",c)

c += a

print("Line 2 - Value of c is ", c)

c *= a

print("Line 3 - Value of c is ",c)

c /= a

print("Line 4 - Value of c is ", c)

c = 2

c %=a

print("Line 5 - Value of c is ",c)

c **= a

print("Line 6 - Value of c is ",c)

c //= a

print ("Line 7 - Value of c is ", c)

Output

Line 1 - Value of c is 31

Line 2 - Value of c is 52

Line 3 - Value of c is 1092

Line 4 - Value of c is 52.

Line 5 - Value of c is

Line 6 - Value of c is 2097152

Line 7 - Value of c is

Logical Operators:

  • Logical operators are the and, or, not operators.

Example

a = True

b = False

print('a and b is', a and b)

print('a or b is' ,a or b)

print('not a is', not a)

Output

x and y is False

x or y is True

not x is False

Bitwise Operators :

• A bitwise operation operates on one or more bit patterns at the level of individual bits

Example: Let x = 10 (0000 1010 in binary)and

y = 4 (0000 0100 in binary)

Example

a = 60

Output

Line 1 - Value of c is 12

b = 13

c = 0

c = a & b;

Line 2 - Value of c is 61

Line 3 - Value of c is 49

Line 4 - Value of c is- 61

print "Line 1 - Value of c is ", c

c = a|b; # 61 = 0011 1101

print "Line 2 - Value of c is ", c

c = a^b; # 49 = 0011 0001

print "Line 3 - Value of c is ", c

c =~a; # - 61 = 1100 0011

Line 5 - Value of c is 240

Line 6 - Value of c is 15

5.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 regularOR'

<= <>>= Comparison operators

<> == != Equality operators

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

is is not Identity operators

in not in Membership operators

not or and Logical operators

  • For mathematical operators, Python follows mathematical convention.
  • The acronym PEMDAS (Parentheses, Exponentiation, Multiplication, Division, Addition, Subtraction ) is a

useful way to remember the rules:

  • Parentheses have the highest precedence and can be used to force an expression to evaluate in the

order you want. Since expressions in parentheses are evaluated first, 2 * (3-1)is 4, and (1+1)**(5-2)

is8.

  • You can also use parentheses to make an expression easier to read,asin(minute
    1. / 60, even if it doesn’t change the result.
  • Exponentiation has the next highest precedence, so 1 + 2**3 is 9, not 27, and

3*2 is 18, not 36.

  • Multiplication and Division have higher precedence than Addition and Subtraction. So 2*3-1 is 5,

not 4, and 6+4/2 is 8, not5.

  • Operators with the same precedence are evaluated from left to right (except exponentiation).

Examples:

a=9-12/3+3*2- 1

a=?

a=9-4+3*2- 1

a=9-4+6- 1

a=5+6-1 a=11-

1 a=

A=2*3+4%5-3/2+

A=6+4%5-3/2+

A=6+4-3/2+6 A=6+4-

A=10-1+

A=9+6 A=

find m=?

m=-43||8&&0||- 2 m=-

43||0||-2 m=1||- 2

m=

  1. Functions, Function Definition And Use, Function call, Flow Of Execution, Function Prototypes,

Parameters And Arguments, Return statement, Arguments types, Modules

FUNCTIONS:

 Function is a sub program which consists of set of instructions used to perform a specific task.

A large program is divided into basic building blocks called function.

Need For Function:

  • When the program is too complex and large they are divided into parts. Each part is separately

coded and combined into single program. Each subprogram is called as function.

  • Debugging, Testing and maintenance becomes easy when the program is divided into

subprograms.

  • Functions are used to avoid rewriting same code again and again in a program.
  • Function provides code re-usability
  • The length of the program is reduced.

Types of function:

Functions can be classified into two categories:

i) user defined function

ii) Built in function

i) Built in functions

  • Built in functions are the functions that are already created and stored inpython.
    • These built in functions are always available for usage and accessed by a programmer. It cannot be

modified.