1amongu.com€¦ · Web viewRegulation – 2017 . GE8151 – Problem Solving and Python...
Transcript of 1amongu.com€¦ · Web viewRegulation – 2017 . GE8151 – Problem Solving and Python...
Regulation – 2017 GE8151 – Problem Solving and Python Programming
Notes - Unit II – Data, Expressions and StatementsSyllabus
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 Interpreter and Interactive Mode
About Python:• Python is an open source, object-oriented, interpreted and high level programming
language.• It was developed by Guido van Rossum in 1991. He is computer programmer at CWI
(Centrum Wiskunde and Informatica). CWI – is a National Research Institute of Mathematics and Computer Science in Netherlands. He wanted to develop a language that could be used by anyone.
• It is the most powerful language that has been used by companies in real revenue generating products such as, Google Search Engine, YouTube, Bit Torrent for peer to peer file sharing, Intel for hardware testing, i-Robot for developing commercial Robot and NASA for scientific research.
Why to Learn Python?• Learning Python leads to a basic foundation for programming and also to build other
OOP (Object Oriented Programming) languages like C++, C#, Javascript, Ruby, etc.,• The latest released version is Python 3.6.0.• It is available for download from the following web address: http://www.python.org.
Python Program:• Python programs are composed of modules• Modules contain statements• Statements contain expressions• Expressions create and process objects
1
Features of Python:
Open source: Python is publicly available open source software; anyone can use source code that doesn’t cost anything.
Easy-to-learn: Popular (scripting/extension) language, clear and easy syntax, no type declarations, automatic memory management, high-level data types and operations, design to read (more English like syntax) and write (shorter code compared to C, C++, and Java) fast.
High Level Language: High-level language (closer to human) refers to the higher level of concept from machine language (for example assembly languages). Python is an example of a high-level language like C, C++, Perl, and Java with low-level optimization.
Portable: High level languages are portable, which means they are able to run across all major hardware and software platforms with few or no change in source code. Python is portable and can be used on Linux, Windows, Macintosh, Solaris, FreeBSD, OS/2, Amiga, AROS, AS/400 and many more.
Object-Oriented: Python is a full-featured object-oriented programming language, with features such as classes, inheritance, objects, and overloading.
Python is interactive: Python has an interactive console where you get a Python prompt (command line) and interact with the interpreter directly to write and test your programs. This is useful for mathematical programming.
Interpreted: Python programs are interpreted, takes source code as input, and then compiles (to portable byte-code) each statement and executes it immediately. No need to compiling or linking
Extendable: Python is often referred to as a “glue” language, meaning that it is capable to work in mixed-language environment. The Python interpreter is easily extended and can add a new built-in function or modules written in C/C++/Java code.
Libraries: Databases, web services, networking, numerical packages, and graphical user interfaces, 3D graphics, others.
Supports: Support from online Python community.
Python Interpreter:Interpreter – Computing: an interpreter is a computer program that directly executes, i.e. performs, instructions written in a programming or scripting language, without previously compiling them into a machine language program.
2
History: The name Python was selected from "Monty Python’s Flying Circus" which was a British
sketch comedy series created by the comedy group Monty Python and broadcast by the BBC from 1969 to 1974.
Python was created in the early 1990s by Guido van Rossum at the National Research Institute for Mathematics and Computer Science in Netherlands.
Python was created as a successor of a language called ABC (All Basic Code) and released publicly in1991.
Python is easy to use: Program to print the following message: Welcome to IT department
print (“Welcome to IT deprtment”)
Major uses of Python:
System utilities (system admin tools, command line programs). Web Development.
Graphical User Interfaces (Tkinter, gtk, Qt).
Internet scripting.
Embedded scripting.
Database access and programming.
Game programming.
Rapid prototyping and development.
Distributed programming
Organizations using Python (Sector wise): Web development Games Graphics Financial Science Electronic Design Automation Education Business Software
IDLE:
3
IDLE is an integrated development environment (an application like a word processor which helps developers to write programs) for Python.
IDLE Features: Cross Platform: Works on Unix and Windows. Multi-window text editor with syntax highlighting and smart indent and other.
Python shell window with syntax highlighting.
Integrated debugger.
Coded in Python, using the tkinter GUI toolkit
Python IDLE: Interactive Mode:Let us assume that we've already installed Python (here we installed Python 3.2 on a standard pc with windows 7 OS). Click on start button and find Python 3.2 tab in installed programs.
Now clicking on Python 3.2 tab you can see the Python program development tool named IDLE (Python GUI).
4
To start IDLE click on IDLE (Python GUI) icon, you will see a new window opens up and the cursor is waiting beside '>>>' sign which is called command prompt.
This mode is called interactive mode as you can interact with IDLE directly, you type something (single unit in a programming language) and press enter key Python will execute it, but you cannot execute your entire program here.
At the command prompt type copyright and press enter key Python executes the copyright information.
5
Now Python is ready to read new command. Let's execute the following commands one by one.
Command -1 : print("Hello World")Command -2 : primt("Hello World")
The first command is correct and but the second one has a syntax error, here is the response from Python.
6
Python IDLE: Development Mode or Script Mode
At first, start with a new window.
Clicking on "New window" under file menu a new window will come. Type print "Hello World" in the new window.
7
Let's save (Save command is located under the File menu) the file now. We save the program as helloworld.py under E:/python-programs folder.
To run the program select Run menu.
Now click on Run Module or press F5 as a shortcut key to see the result.
8
Values and Data Types A value is one of the fundamental things, like a letter or a number that a program
manipulates. They are grouped into different data types or classes. Data type is a set of values and allowable operations on those values. Data type allows programming language to organize different kinds of data.
Data typesThe following will be the list of data types in Python: Numbers: Integer, Floating Point and Complex. Integer: Boolean None Sequences: Strings, Tuple and List Sets Mappings: Dictionary
I. Numbers: A numeric literal containing only the digits (0-9), an optional sign character (+ or -) and a
possible decimal point. Number data types are used to store numeric values. Different numerical types includes the following:
o int (signed integers)o long (long integers)o float (float integers)
9
o complex (complex integers)Syntax:
variable_name = initial_valuetype(variable_name) type( ) – this is function which returns the data type
Where, variable_name user defined nameinitial_value value to be initialized
1. Integers It is whole number with no fractional parts and decimal point. They can be either a positive, negative or zero value. It has unlimited size in Python 3 and it supports normal integers as well as octal,
hexadecimal and binary literals. For example:
>>>c=145672 #145672 is initialized to the variable name c >>>type(c) #type( ) is used to check data type of cOutput: <class ‘int’> # it returns the data type as int
Binary Literal (base 2)o It is of the form 0 (zero) followed by either an uppercase B or lowercase b.o For example: >>>c=0b1010 # Lowercase b >>>print(c)Output:10
Octal literal (base 8)o It is a number prefixed with 0 (zero) followed by either uppercase O or
lowercase o.o For example: >>>c=0O24 # Uppercase O >>>print(c)Output:20
Hexadecimal literal (base 16)o It is prefaced by a 0 (zero) followed by an uppercase X or lowercase x.o For example:
10
>>>c=0xa0f # Lowercase x>>>print(c)Output:2575
2. Long Integers (Long) Python displays long integers with an uppercase L. It allows to use a lowercase L with long data type number. For example:
>>>c=76534L #Uppercase L>>>c=c*5669>>>type(c)Output:<class ‘long’>
3. Floating Point Numbers (Floats) Numbers with fractions or decimal points are called floating point numbers. It may be expressed in scientific notation using the letter “e” to indicate the 10th
power. The letter “E” or “E notation” is used to express very large and small results in
scientific notation. For example:
>>>c=67.2>>>type(c)Output:<class ‘float’>
>>>3.5e5Output:350000.0
4. Complex Numbers It consists of an ordered pair of real floating point numbers denoted by (real + img j),
where real and img are the real numbers and the letter j refers to the square root of -1 which is an imaginary number.
A real number is a value that represents a quantity along a line. The real numbers include all the rational and irrational numbers.
An imaginary number is a complex number that can be written as a real number multiplied by the imaginary unit j.
For example:>>>x=4+5j>>>y=2-2j>>>xy=x+y>>>print(xy)
11
Output:(6+3j)
Formatting functions: Python uses C-style string formatting functions to create new, formatted strings. The “%” operator is used to format a set of variables enclosed in a tuple (fixed
size list), together with a format string which contains normal text together with “format specifiers” and special symbols like “%s” and “%d”.
Syntax:print(“%format_specifier”, “%variable_name)where, format_specifier specifies the conversion characters
Format Specifier Conversion%c Character%s String formatting%i Signed decimal integer%d Signed decimal integer%u Unsigned decimal integer%o Octal integer%x Hexadecimal integer (lowercase)%X Hexadecimal integer (UUERCASE)%e Exponential notation (lowercase)%E Exponential notation (UPPERCASE)%f Floating point real number
Example program:Name=”Python Programming”Price= 400Gender=”m”
print(“%s book costs Rs. %d” %(Name,Price))output:Python Programming book costs Rs. 400
5. Boolean It is often called as bools, are either TRUE or FALSE condition. These two values are used when evaluating comparisons, conditional expressions
and in other structures that require values to be represented for True or False conditions.
For example:>>>flag=True>>>type(flag)
12
Output<type ‘bool’>
>>>d=(18>=5)>>print(d)OutputTrue
II. None: This type has a single value. There is a single object with this value. This object is accessed through the built-in name None. It is used to signify the absence of a value in many situations, e.g., it is returned from
functions that don’t explicitly return anything. Its truth value is false.
III. Sequence: A sequence is am ordered collection of items, indexed by positive integers. It is a
combination of mutable and non mutable data types. Three types of sequence data type available in Python are Strings, Lists and Tuples.
1. Strings: Strings are amongst the most popular types in Python. We can create them simply by enclosing characters in quotes. Python treats single quotes the same as double quotes. Strings are immutable character sets. Once a string is generated, you cannot
change any character within the string. Creating strings is as simple as assigning a value to a variable. A string consisting of only a pair of matching quotes is called empty string. For example:
‘A’ a string consisting of a single character.‘@information.co.in’ a string consisting non-letter character“ “ empty string
2. Lists: It is the simplest data structure in Python and is used to store a list of values. It is an ordered sequence of values of any data type. Values in the list are called as elements/items. These are mutable and indexed/ordered. To create a list, define a variable to contain an ordered series of items separated
by a comma. A square bracket is used to enclose the items. Syntax:
13
my_list=[ ] #to create an empty listTo create a list of items:my_list=[item1, item2, item3, item4]For example:num_list=[0, 5, 10, 15, 20]string_ist=[“cat”, “dog”, “lion”]
3. Tuples: It is another sequence data type similar to list. A tuple consists of a number of values separated by commas and enclosed within
parenthesis. Unlike list, the tuple values cannot be updated. They are treated as read-only lists. For example:
tuple1=(‘abcd’, 324, 3.2, ‘python’, 3.14)tuple2=(234, ‘abcd’)
14
How to access sequence:
String: example str=’Hello World!’Code Comment Resultprint str # prints complete string Hello, World!print str[0] #prints first character of the string Hprint str[-1] #prints last character of the string !print str[1:5] #prints character starting from index 1 to 4
#prints str[start_at: end_at-1]ello
print str[2:] #prints starting at index 2 till end of the string llo, World!print str * 2 #asterisk (*) – repetition operator. Prints
string two timesHello, World! Hello, World!
print str + “Hai”
#prints concatenated string Hello, World! Hai
Lists: example list1=[‘abcd’, 234, 3.14, ‘python’]Code Comment Resultprint list1 #prints complete list [‘abcd’, 234, 3.14, ‘python’]print list1[0] #prints first element of the list abcdprint list1[-1] #prints last element of the list pythonprint list1[1:3] #prints elements starting from index 1 to 2
#prints list1[start_at: end_at-1][234,3.14]
Tuple: example tuple1=(‘abcd’, 324, 3.2, ‘python’, 3.14)Code Comment Resultprint tuple1 #prints complete tuple1 (‘abcd’, 324, 3.2, ‘python’,
3.14)print tuple1[0] #prints first element of the tuple1 abcdprint tuple1[-1] #prints last element of the tuple1 3.14
IV. Sets: A set is an unordered collection of unique elements. Basic uses include dealing with set theory (which support mathematical operations like
union, intersection, difference, and symmetric difference) or eliminating duplicate entries.
See the following statements.
15
V. Dictionaries: Python dictionary is a container of the unordered set of objects like lists. The objects are surrounded by curly braces { }. The items in a dictionary are a comma-separated list of key:value pairs where keys and
values are Python data type. Each object or value accessed by key and keys are unique in the dictionary. As keys are used for indexing, they must be the immutable type (string, number, or
tuple). You can create an empty dictionary using empty curly braces.
16
Variables A variable is an identifier that refers to a value or variable is a memory location where a
programmer can store a value. Example : roll_no, amount, name etc. Value is either string, numeric etc. Example : "Sara", 120, 25.36 Variables are created when first assigned. Variables must be assigned before being referenced. The value stored in a variable can be accessed or updated later. No declaration required The type (string, int, float etc.) of the variable is determined by Python The interpreter allocates memory on the basis of the data type of a variable. The assignment statement creates new variables and gives them values. Basic assignment statement in Python is:
Syntax:
<variable_name>=<exp>
Where the equal sign (=) is used to assign value (right side) to a variable name (left side). See the following statements:
For example:
>>> Item_name = "Computer" #A String
>>> Item_qty = 10 #An Integer
17
>>> Item_value = 1000.23 #A floating point
>>> print(Item_name)
Computer
>>> print(Item_qty)
10
>>> print(Item_value)
1000.23
For example: a = 12 is correct, but 12 = a does not make sense to Python, which creates a syntax error.>>> a = 12>>> 12 = aSyntaxError: can't assign to literal
Multiple Assignment:
The basic assignment statement works for a single variable and a single expression. You can also assign a single value to more than one variable simultaneously. Syntax:
var1=var2=var3...varn= = <expr> For example: x=y=z=1
Now check the individual value in Python>>> x = y = z = 1>>> print(x)1>>> print(y)1>>> print(z)1
Here is an another assignment statement where the variables assign many values at the same time.
Syntax:<var>, <var>, ..., <var> = <expr>, <expr>, ..., <expr>
For example: x,y,z=1,2,”abcd” In the above example x, y and z simultaneously get the new values 1, 2 and "abcd".
>>> x,y,z = 1,2,"abcd">>> print(x)1>>> print(y)2
18
>>> print(z)abcd
You can reuse variable names by simply assigning a new value to them :>>> x = 100>>> print(x)100>>> x = "Python">>> print(x)Python>>>
Swap Variables:
Python swap values in a single line and this applies to all objects in python. Syntax:
var1, var2 = var2, var1 For example:
>>> x = 10>>> y = 20>>> print(x)10>>> print(y)20>>> x, y = y, x>>> print(x)20>>> print(y)10>>>
Local and Global Variables in Python:
In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a
local unless explicitly declared as global. For example:
var1 = "Python"def func1():
var1 = "PHP" print("In side func1() var1 = ",var1)
def func2(): print("In side func2() var1 = ",var1)
func1()func2()
19
Output:
In side func1() var1 = PHPIn side func2() var1 = Python
You can use a global variable in other functions by declaring it as global keyword : For example:
def func1(): global var1 var1 = "PHP" print("In side func1() var1 = ",var1)
def func2(): print("In side func2() var1 = ",var1)func1()func2()
Output:
In side func1() var1 = PHPIn side func2() var1 = PHP
Keywords
Keywords are the reserved words in Python. We cannot use keyword as variable name, function name or any other identifier.
They are used to define the syntax and structure of the Python language. In Python, keywords are case sensitive. There are 33 keywords. It may vary with different versions. Every keyword performs a
specific task. Some important keywords are listed here:
False class finally is returnNone continue for lambda tryTrue def from nonlocal whileand del global not withas elif if or yieldassert else import passbreak except in raise
To retrieve the keywords in Python, the following code can be given at the prompt.>>>import keyword
20
>>>print(keyword.kwlist)Output: it shows all keywords.
Note: All keywords except True, False and None are in lowercase.
Identifiers
An identifier is a name which is used to identify a variable, function, class, module or any other object.
It helps in differentiating one entity from another. Rules for naming identifiers:
o It should start with either uppercase or lowercase letter or underscore followed by zero or more alphabetic letters and digits. (0 to 9)
o It should not contain special symbols like !, @, #, $, %, etc.,o By convention, class identifiers should always starts in uppercase, while all other
identifiers can be in lowercase.o Underscores can be used to join multiple-word identifiers.o Pyhton is case sensitive and hence uppercase and lowercase are considered
distinct. Hence, Global and global are distinct identifiers.o Python keywords should not be used as identifiers.o It can be of any length.
For example:Valid identifiers: myVariable, var_1, students1Invalid identifiers: 21var, cart-count, var@-Class identifiers: Student
Comments
A comment is a piece of program text that the interpreter ignores but provides useful documentation to programmers.
A line of text which starts with a hash (#) symbol is known as comment in Python. A comment can be written as a new line or with the statement or expression line. Alternatively, we can use triple single (‘’’) or triple double quotes (“ “ “) at the start and
end of a multi line statement. The author of a program can include his or her name and a brief statement about the
purpose of the program at the beginning of the program file. This type of comment is called as a docstring.
Syntax:# <single line comment statement>‘ ‘ ‘ <Multi line commentStatement 1Statement 2……Statement n> ‘ ‘ ‘Example program:
Program to explain single line comment:sname1=”Aarthy” #Student Name
21
totalmarks=1175 #Total marks obtainedprint(sname1)print(totalmarks)Output:Aarthy1175
Program to explain multi line comments“ “ “ print(“United”)print(“Global”)“ “ “print(“Publishers”) #outside the comment lineOutput:Publishers
Quotations
The Python language permits the use of single quote(‘), double (“), and triple(“ “ “ or ‘ ‘ ‘) quotes to represent a string literal, making sure that the same type of quote begins and ends that string.
Syntax:‘ <statement> ‘ #Single Quotes“ <statement> “ #Double Quotes“ “ “ <statement> “ “ “ or ‘ ‘ ‘ <statement> ‘ ‘ ‘ # triple QuotesExample Program:>>>print(“United”)>>>print(‘Publishers’)>>>print(“ “ “ Python Programming “ “ “ )Ouput:UnitedPublishersPython Programming
Indentation
Most popular high level languages like C, C++, Java uses braces { } to represent blocks of code.
In general, block is a group of statements in a program or a script. Python uses whitespaces at the beginning of each line to structure the program. Generally, four whitespaces are used for indentation and is preferred over tab space. Example program:
pwd = input(“Enter your password: “)if pwd = = ‘global’ :
print(‘Login Successful’) #line indentationelse:
print(‘Incorrect Password!’)Ouput:
22
Enter your password: globalLogin Successful
Expressions and Statements
Expressions:
It is a combination of values, variables and operators. If we type an expression on the command line, the interpreter evaluates it and displays
the result. The evaluation of an expression produces a value, which is why expressions can appear
on the right hand side of assignment statements. A value may be a simple expression. For example:
>>>a15>>>a+1530
When we type an expression at the prompt, the interpreter evaluates it which means that it finds the value of the expression.
In the above example, a has the value 15 and a+15 has the value 30. An arithmetic expression consists of operands and operators combined in a manner that is
similar to algebra. In Python we must indicate the operators explicitly. Binary operators can be used
between their operands (a * b) whereas, unary operators are placed before their operands (-a)
Tuple Assignment:o A programmer can assign multiple variables in one statement by using tuple
assignment. A tuple is the list of expressions separated by a comma.o For example:
x, y, z = 100, -45, 0Here, x, y, z is one tuple and 100, -45, 0 is another tuple. Tuple works as follow: the first variable in the tuple on the left side of the assignment operator is assigned the values of the first expression in the another tuple on the left side effectively. x=100. Like y=-45 and z=0.
Statements:
A statement is a unit of code that the Python interpreter can execute. The following are the two kinds of statements used in Python. They are: print and
assignment. When we type a statement in interactive mode, the interpreter executes it and displays the
result, if there is a single statement. A script usually contains a sequence of statements. If there is more than one statement,
the results appear one at a time as the statement execute.
23
For example:>>>x=3.14>>y=len(“hello”)>>print(y) Output: 5>>print(x) Output:3.14>>x Output:3.14
Note that, when we enter the assignment statement x=3.14, only the prompt is returned. There is no value. This is due to the fact the assignment statements, do not return a value. They are simply executed.
Multi-line statements:
A multi line expression is a single statement that wraps the lines inside braces { }, brackets [ ] and parenthesis ( ).
In Python, end of the statement is always marked by a new line character. A statement may span several lines. But we can make a statement extend over multiple
lines with the line continuation character (\). We could also put multiple statements in a single line using semicolons. Syntax:
variable_name=<{statements} or [statements] or (statements)>Orvariable_name=<”statement1” \
“statement2” \“statement3” >
Or# Multiple statements in single linevar_name=value1;…..var_namen=valuen;Example:>>>weeks=[‘Sunday’, ‘Monday’, ‘Wednesday’, ‘Thursday’, ‘Friday’]>>>alphabets=”A”, “B”,”C”, “D” \
“E”, “F”, “G”, “H” \“I”,”J”, “K”, “L” \“M”, “N”, “O”, “P”
>>>num1=10; num2=20; num3=30
Input / Output and Import Functions
In principle, every computer program has to communicate with the environment or the outside world.
To this purpose nearly every programming language has special I/O functionalities i.e input/output.
Displaying the Output The print( ) function is used for formatting the output data to the standard output
device (screen).
24
Here, we can pass zero or more expressions or statements that are separated by commas. It converts the expressions that are passed into a string and displays the result to standard output.
The print function always ends its output with a new line. In other words, is displays the values of the expressions and then it moves the cursor to the next line on the console.
Syntax:print(“<expression>”)print(“<expression>”, var_name)example:>>>print(“Publishers”)Output: Publishers>>>a=20>>>sum=a+10>>>print(“Sum is: “, sum)Output:Sum is: 30
Reading the Input: Input often comes from the keyboard. It means the data entered by an end-user of
the program. It has two key functions to deal with end user input called raw_input ( ) and
input(). raw_input:
o The raw_input([prompt]) function reads one line from standard input and returns it as a string.
o This prompts the users to enter any string and it would display same entered string on the screen.
o raw_input function is not supported by higher versions of Python for Windows.
o Syntax:var_name=raw_input(“<prompt input statement>”)Example:book_name=raw_input(“Enter your book name: “)price=raw_input(“Enter Price: “)# to display a string use +var_name.print(“Entered book name is: “ +book_name)print(“Price of book is: “, price)Output:Enter your book name: PythonEnter Price: 1450Entered book name is: PythonPrice of book is: 1450
input:
25
o The input([prompt]) function is equivalent to raw_input, except that it assumes the input as a valid Python expression and returns the evaluated result.
o It has an optional parameter, which is the prompt string.o Syntax:
var_name=input(“<prompt expression or statement>”)Example Program:Name=input(“Enter your name”)Rollno=input(“Enter your rollno”)Totalmarks=input(“Enter the total marks”)Collegename=”Anna University”print(“Name: “, Name)print(“Rollno: “, Rollno)print(“Total marks: “, Totalmarks)print(“College Name: “, Collegename)Output:Enter your name: AriEnter your rollno:27Enter the total marks: 1167Name: AriRollno: 27Total Marks: 1167College Name: Anna University
Import Module: Module is a built in file containing python definitions and statements with the .py
extension, which implement a set of function. Modules are imported from other modules using the import command. When a module gets imported, it searches for the module and if found, python
creates a module object. If the named module cannot be found, ModuleNotFoundError will be raised.
Syntax:import modelunameExample:import math>>>math.ceil(30.56)Output:31>>>math.floor(30.56)Output:30
Operators
An operator is a symbol that represents an operation performed on one or more operands. An operand is a quantity on which an operation is performed.
26
Operators that take one operand are called unary operators. A binary operator operates on two operands
Types of Operator:
Python language supports the following types of operators.
Arithmetic Operators Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
Arithmetic Operator: Arithmetic operators are used for performing basic arithmetic operations.
Operator Name Example Result+ Addition x+y Sum of x and y.- Subtraction x-y Difference of x and y.* Multiplication x*y Product of x and y./ Division x/y Quotient of x and y.% Modulus x%y Remainder of x divided by y.** Exponent x**y x**y will give x to the power y
// Floor Division x/ y The division of operands where the result is the quotient in which the digits after the decimal point are removed.
See the following statements in Python Shell.
27
Comparison or Relational Operator: Comparison operators evaluate or compare the values on either side of the expression
and it returns either True or False condition. It describes the relation between the left and right operands. They are also called as
relational operators.
Operator Name Example Result== Equal x==y True if x is exactly equal to y.!= Not equal x!=y True if x is exactly not equal to y.
> Greater than x>y True if x (left-hand argument) is greater than y (right-hand argument).
< Less than x<y True if x (left-hand argument) is less than y (right-hand argument).
>= Greater than or equal to x>=y True if x (left-hand argument) is greater than or equal to y
(left-hand argument).
<= Less than or equal to x<=y True if x (left-hand argument) is less than or equal to y
(right-hand argument).
See the following statements in Python shell.
28
Assignment Operator: This operator assigns the value of an expression to a variable or constant. Basic assignment operator equal (=) assigns the value of right operand to its left
operand.
Operator Shorthand Expression Description+= x+=y x = x + y Adds 2 numbers and assigns the result to left operand.-= x-= y x = x -y Subtracts 2 numbers and assigns the result to left operand.*= x*= y x = x*y Multiplies 2 numbers and assigns the result to left operand./= x/= y x = x/y Divides 2 numbers and assigns the result to left operand.
%= x%= y x = x%y Computes the modulus of 2 numbers and assigns the result to left operand.
**= x**=y x = x**y Performs exponential (power) calculation on operators and assign value to the equivalent to left operand.
//= x//=y x = x//y Performs floor division on operators and assign value to the left operand.
See the following statements in Python shell.
29
Logical Operator: This operator is used to compare and evaluate logical operations.
Operator Example Resultand (x and y) is True if both x and y are true.or (x or y) is True if either x or y is true.not (x not y) If a condition is true then Logical not operator will make false.
See the following statements in Python shell.
30
Bitwise Operator: It is operations that directly manipulate bits. In all computers, numbers are represented
with bits, a series of zeros, and ones. It performs bit by bit operations and returns binary coded output.
Operator Shorthand Expression Description& And x & y Bits that are set in both x and y are set.| Or x | y Bits that are set in either x or y are set.^ Xor x ^ y Bits that are set in x or y but not both are set.~ Not ~x Bits that are set in x are not set, and vice versa.
<< Shift left x <<y Shift the bits of x, y steps to the left>> Shift right x >>y Shift the bits of x, y steps to the right.
For example:
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
31
~a = 1100 0011
Membership Operator: This operator is used to test whether a value (variable) is found in a sequence like string,
list, tuple, set and dictionary.Operator Description Example
inEvaluates to true if it finds a variable in the specified sequence and false otherwise.
x in y, here in results in a 1 if x is a member of sequence y.
not inEvaluates to true if it does not finds a variable in the specified sequence and false otherwise.
x not in y, here not in results in a 1 if x is not a member of sequence y.
For example:X=’Global Publishers’Y={1,’a’,2,’b’}print(‘t’ in X)print(‘Global’ in X)print(1 in Y)print(‘c’ not in Y)Output:FalseTrueTrueTrue
Identity Operator: It is used to compare memory location of two objects.
Operator Description Example
isEvaluates to true if the variables on either side of the operator point to the same object and false otherwise.
x is y, here is results in 1 if id(x) equals id(y).
is notEvaluates to false if the variables on either side of the operator point to the same object and true otherwise.
x is not y, here is not results in 1 if id(x) is not equal to id(y).
It is used to check whether the two values are located on the same part of the memory.
For example:
X, Y, Z = 15, 15, 10print(X is Y) #X=15 and Y=15 Trueprint(X is Z) #X=15 and Z=10 Falseprint(Y is Z) #Y=15 and Z=10 Falseprint(X is not Y) #X=15 and Y=15 Falseprint(X is not Z) #X=15 and Z=10 Trueprint(Y is not Z) #Y=15 and Z=10 True
32
Output:TrueFalseFalseFalseTrueTrue
Operator Precedence
Operator precedence determines which operators need to be evaluated first. To avoid ambiguity in values, precedence operators are necessary.
The following table lists all operators from highest precedence to lowest.
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 operatorsin not in Membership operatorsnot or and Logical operators
Modules
33
Modules are a simple way to organize a program which contains program code, variables etc..
All these definitions and statements are contained in a single Python file. The name of the module is the name of the file name with .py extension. Simply, a module is a file consisting of Python code. A module can define functions, classes and variables. A module can also include runnable code. Syntax: import module_name
Functions
Function is a group of statements that performs a specific task. If a program is large, it is difficult to understand the steps involved in it. Hence, it is subdivided into a number of smaller programs called subprograms or modules.
Each subprogram specifies one or more actions to be performed for the larger programs. Such subprograms are called as functions.
Functions may or may not take arguments and may or may not produce results.
Advantages of Functions:
Decomposing larger programs into smaller functions makes program easy to understand, maintain and debug.
Functions developed for one program can be reused with or without modification when needed.
Reduces program development time and cost. It is easy to locate and isolate faulty function.
Types of Functions:
1. Built-in / Predefined Function2. User Defined Function
1. Built-in / Predefined Function:
Built-in functions are functions already built into Python interpreter and are readily available for use.
Example:o print( ) Print objects o input( ) Reads a line from input, convert it to a string and returns that.o abs( ) Return the absolute value of a number.o len( ) Return length of an object.
Program to find the ASCII value of the given characterc=input(“Enter a character”)print(“ASCII value of “ +c+ “is” +ord(c))Sample Input/Output:Enter a character
34
PASCII value of p is 112
Where, ord(c) function converts a character to an integer (ASCII Value). Type Conversion functions
Python provides built-in function that convert values from one type to another.
Function Converting what to what Exampleint( ) String, floating point integer >>>int(‘2014’)
2014>>>int(3.141592)3
float( ) String, integer floating point number >>>float(‘1.99’)1.99>>>float(5)5.0
str( ) Integer, float, list, tuple, dictionary string >>>str(3.141592)‘3.141592’>>>str([1,2,3,4])‘[1,2,3,4]’
list( ) String, tuple, dictionary list >>>list(‘Mary’)[‘M’, ‘a’, ‘r’, ‘y’]>>>list((1,2,3,4))[1,2,3,4]
tuple( ) String, list tuple >>>tuple(‘Mary’)(‘M’, ‘a’, ‘r’, ‘y’)>>>tuple([1,2,3,4])(1,2,3,4)
>>>age=21>>>sign=’You must be’ + age + ‘Years old’Many Python functions are sensitive to the type of data. For example, we cannot concatenate a string with an integer. If we try, it will result in following error.Traceback (most recent call last):File “<pyshell#71>”, line 1, in <module>Sign = ‘You must be’ + age + ‘Years old’TypeError: cannot concatenate ‘str’ and ‘int’ objects
For the example above, use the str( ) conversion function to convert integer to string data type.>>>age=21>>>sign=’You must be’ + age + ‘Years old’>>>signOutput: You must be 21 Years old
Math functions
35
Math and cmath are mathematical modules available in Python to support familiar mathematical functions.
A module is a file that contains a collection of related functions. Before using built-in math functions, import math module. >>>import math it will create a module object named math which contains
functions and variables defined in the module. The following will be some of the math functions:
Function Description Example Outputabs(n) Return the absolute
value of a number abs(-99) 99
round(n,d) Round a number (n) to a number of decimal points (d)
round(3.1415, 2) 3.14
floor(n) Round down to nearest integer
math.floor(4.7) 4.0
ceil(n) Round up to nearest integer
math.ceil(4.7) 5.0
pow(n,d) Return n raised to the power d
math.pow(10,3) 1000.0
sqrt(n) Returns square root of number (n)
math.sqrt(256) 16.0
factorial(n) Return n factorial math.factorial(5) 120gcd(n,m) Return greatest
common divisor of (n,m)
math.gcd(10,125) 5
trunc(x) Returns the real value x truncated to an integral
math.trunc(1.999) 1
Mathematical constants: math.pi π =3.141592…. math.e e=2.718281…
2. User defined Function:
The function defined by the users according to their requirements is called user defined function.
The users can modify the function according to their requirements. Example: multiply( ), sum( ), display( ) Defining a Function:
o Functions in Python are defined using the block keyword def followed by the function name and parenthesis ( ( ) ). Function definition includes header and body.
o Header begins with a keyword def and ends with a colon.o Body consisting of one or more Python statements.o Syntax:
36
def function_name(parameters):“function docstring”function_suitereturn[expression]
Calling a Function:o A function can be executed by calling it from another function or directly
from the Python prompt by its name.o Syntax:
function_name(parameters)Example program: Function to display Welcome message.
def display( ):print “Welcome!”
>>>display( )Output:Welcome!
o Example: Functions to find the biggest among three numbers.def great(a,b,c):
if(a>b) and (a>c):return a
elif(b>a) and (b>c)return b
else:return c
n1=input(“Enter first number”)n2=input(“Enter second number”)n3=input(“Enter third number”)result=great(n1,n2,n3)print result, “is bigger”
Output:Enter first number10Enter second number5Enter third number2525 is bigger
Function definition and usesdef add(a,b):
return (a+b)def sub(a,b):
return (a-b)def calculate( ):
a=input(“Enter first number”)b=input(“Enter second number”)result=add(a,b)
37
print resultresult=sub(a,b)print resultreturn
o The above program contains three function definitions: add( ), sub( ) and calculate( ). The statements inside the function do not get executed until the function is called and the function definition generates no output.
o Function must be created before execution i.e function definition has to be executed before the first time it is called.
Flow of Executiono It specifies the order in which the statements are executed.o Program execution starts from first statement of the program.o One statement is executed at a time from top to bottom.o It does not alter the flow of execution of the program and the statements
inside the function are not executed until the function is called.o When a function is called, the control flow jumps to the body of the
function, executes the function, and return back to the place in the program where the function call was made.
o When it gets to the end of the program, it terminates. Parameters and Arguments
o Arguments are the values provided to the function during the function call.o Parameters are name used inside the function definition to refer to the
value passed as an argument.o Inside the function, the value of arguments passed during function call is
assigned to parameters.o Example program: Functions to raise a number to given power
import math>>>def raise(no,power):
print math.pow(no,power)>>>a=100>>>b=2>>>raise(a,b)>>>10000 # arguments are a and b parameters are no and power
Functions with no argumentso The empty parenthesis after the function name indicates that this function
does not take any arguments.o Example: Functions to display PI value:
import math>>>def show_pi( ):
print math.pi>>>show_pi( )Output:3.141592653589793
Functions with arguments
38
o Functions may also receive arguments.o Arguments in function call are assigned to function parameters.o Example: Function to calculate area of a circle.
import math>>>def area_circle(r):
a=r*r*math.piprint “Area of Circle:”, a
>>>radius=input(“Enter Radius: “)>>>area_circle(radius)Output:
Enter Radius: 6Area of Circle: 113.04
Functions with return valueo Functions may return a value to the caller, using the keyword – return.o Example: Function to calculate factorial of a number
def factorial(num):fact=1i=1if num = = 0
return 1else:
for i in range(1,num+1):fact=fact*i
return factno=input(“Enter a number:”)print(factorial(no))
Output:Enter a number: 5120
Advantages of Python1. It looks more like a readable, easy to use and learn language. This gives us the ability to
program at a faster rate than a low level language.2. It does not have pointers like other C based language, making it much more reliable.3. It is both free and open source.4. Cross Platform: It runs on all major operating systems like Microsoft Windows, Linux
and Mac OS X.5. Extensible: There are extensive collections of freely available add-on modules, libraries,
frameworks and toolkits.6. Object Oriented Programming allows you to create data structures that can be reused,
which reduces the amount o repetition work.7. It has built-in list and dictionary data structures which can be used to construct fast
runtime data structures.
Disadvantages of Python
39
1. It is executed by an interpreter instead of compilation, which causes it to be slower than if it was compiled and then executed.
2. It is not the best language for memory intensive tasks.3. It is not a great choice for a high-graphic 3d game.4. It has some limitations with database access.
----------------------------------------------------------*********---------------------------------------------
40