Unit 2
Unit 2
Python interpreter and interactive mode, debugging; values and types: int, float, boolean, string, and list;
variables, expressions, statements, tuple assignment, precedence of operators, comments;
Illustrative programs: exchange the values of two variables, circulate the values of n variables, distance
between two points.
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 verysimple. 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 allplatforms.
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
1
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING
2
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING
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 theextension .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.
Features of IDLE
Multi-window text editor with syntax highlighting.
Auto completion with smart indentation.
Python shell to display output with syntax highlighting.
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING
Data type
Every value in Python has a data type.
It is a set of values, and the allowable operations on those values.
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,
2.5 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
Strings
Lists
Tuples
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING
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 multiplelines and sentences."""
Individual character in a string is accessed using a subscript(index).
Characters can be accessed using indexing and slicing operations .
Strings areimmutable i.e the contents of the string cannot be changed after it is created.
Indexing
Operations on string
Indexing
Slicing
Concatenation
Repetitions
Membership
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING
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 datatypes.
Operations on list
Indexing
Slicing
Concatenation
Repetitions
Updation, Insertion, Deletion
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING
Tuples
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.
Altering the tuple data type leads to error. Following error occurs when user tries to do.
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING
>>>t[0]="a"
Trace back (most recent call last):
File "<stdin>", line 1, in <module>
Type Error: 'tuple' object does not support item assignment
Mapping
This data type is unordered and mutable.
Dictionaries fall under Mappings.
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 (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.
Basic Operations
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 "<stdin>", line 1, in
<module>KeyError: 'car'
2.6 Variables,Keywords Expressions, Statements, Comments, Docstring ,Lines And Indentation, Quotation In
Python, Tuple Assignment
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.
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING
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.
Keywords
Keywords are the reserved words in Python.
We cannot use a keyword as name, function name or any other identifier.
They are used to define the syntax and structure of the Python language.
Keywords are case sensitive.
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 (_).
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_variable
Statements
>>> n = 17
>>>print (n)
>>> 17
Here, The first line is an assignment statement that gives a value to n.
The second line isa 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:
>>> 42
42
>>> a=2
>>>a+3+2
7
>>> z=("hi"+"friend")
>>>print(z)
hi friend
Example
>>> x=input("enter the name:")
enter the name: george
>>> y=int(input("enter the number"))
enter the number 3
OUTPUT: Output can be displayed to the user using Print statement .
Syntax
print (expression/constant/variable)
Example:
>>> print(“ Hello ”)
Hello
Comments
A hash sign (#) is the beginning of a comment.
Anything written after # in a line is ignored by interpreter.
Python does not have multiple-line commenting feature. You have to comment each lineindividually as follows:
Eg: percentage = (minute * 100)/60 # calculating percentage of an hour
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.
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING
Example:
functionname doc.
def double(num):
"""Function to double thevalue"""
return2*num
>>>print (double. doc )
Example:
a=3
b=1
if(a>b):
print("a is greater")
else:
print("b is greater")
Quotation in python
Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals.
Anything that is represented using quotations are considered as string.
Single quotes(' ') Eg, 'This a string in single quotes'
Double quotes(" ") Eg, " This a string in double quotes"
Triple quotes(""" """)
Eg: """ This is a paragraph. It is made up of multiple lines and sentences """
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 anassignment
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. This feature makes tuple
assignment quite versatile.
Naturally, the number of variables on the left and the number of values on the right have to be the same.
Example
>>>>>(a, b, c, d) = (1, 2, 3)
ValueError: need more than 3 values to unpack
Example:
It is useful to swap the values of two variables.
With conventional assignment statements, we have to use a temporary variable.
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING
(a, b) = (b, a)
In tuple unpacking, the values in a tuple on the right are ‘unpacked ‘into the variables/names on the right.
>>>b = ("George", 25, "20000") # tuple packing
>>>(name, age, salary)=b # tuple unpacking
>>>name
'George'
>>>age
25
>>>salary
20000
2.7 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
Arithmetic operators
They are used to perform mathematical operations like addition, subtraction, multiplication etc.
Assume, a=10 and b=5
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING
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=5
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING
Assignment Operators
Assignment operators are used in Python to assign values to variables.
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING
Logical Operators
Logical operators are the and, or, not operators.
Bitwise Operators
A bitwise operation operates on one or more bit patterns at the level of individual bits
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING
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.
Identity Operators
They are used to check if two values (or variables) are located on the same part of thememory
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING
Operator precedence
When an expression contains more than one operator, the order of evaluation depends on the order of
operations.