UNIT 2 – DATA, EXPRESSIONS,
STATEMENTS
PYTHON INTERPRETER AND INTERACTIVE
MODE
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.
Applications
• Bit Torrent file sharing
• Google search engine, Youtube
• Intel, Cisco, HP, IBM
• i–Robot
• NASA
• Facebook, Drop box
Integrated Development Learning Environment (IDLE)
• 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.2.2 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:
a) Indexing
b) Slicing
c) Concatenation
d) Repetitions
e) Updation, Insertion, Deletion
2.2.3 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, we can't add elements to a tuple or remove elements
from the tuple.
• Altering the tuple data type leads to error. Following error occurs when user tries to do.
>>> t[0]="a"
Trace back (most recent call last):
File "<stdin>", line 1, in <module>
Type Error: 'tuple' object does not support item assignment
Benefits 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.
2.3 Mapping
• This data type is unordered and mutable.
• Dictionaries fall under Mappings.
2.3.1 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.
• If we try to access a key which doesn't exist, we 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'
Python program to illustrate built-in method bool()
TOPIC : 3 VARIABLES,
EXPRESSIONS,STATEMENTS,TUPLE ASSIGNMENT
3.1 Variables
• Variable is a name that refers to the value
• Variables are containers for storing data values.
• When we create a variable we reserve some space in memory
• Programmers generally choose names for their variables that are meaningful.
• 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.
Rules for Python variables:
• A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive (age, Age and AGE are three different variables)
• Keywords cannot be a variable. Eg: print, input, case, if ,else
• It can be of any length.
• No space is allowed.
3.3 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
3.4 Statements and Expressions
3.4.1 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.
Example :
>>> 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.
• When we type a statement, the interpreter executes it, which means that it does whatever the statement
says.
3.4.2 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:
• When we type an expression, the interpreter evaluates it, which means that it finds the value of the
expression
Expressions Vs Statements
• Expression
o Expressions always returns a value
o Functions are also expressions
o Can print the result value
• Statement
o A statement never returns a value
o Cannot print any result
o Python statement is made up of one or more Python expressions
o Examples Of Python Statements:
Assignment statements,
conditional branching,
loops, classes, import,
def, try, except, pass, del etc
3.6 Comments
• Comments are non-executable statements in Python.
• It means neither the python compiler nor the PVM will execute them.
• Comments are intended for human understanding, not for the compiler or PVM.
• Therefore they are called non-executable statements.
• There are two types of commenting features available in Python:
• These are single-line comments and multi-line comments.
Single Line Comment
• A single-line comment begins with a hash (#) symbol and is useful in mentioning that the whole line should be considered as a comment
until the end of the line.
• Example 1: o # This is a comment.
o # This is a comment, too.
o # I said that already.
• Example 2 :
#Defining a variable to store number.
n = 50 #Store 50 as value into variable n.
• In the above example program, the first line starts with the hash symbol, so the entire line is considered as a comment.
• In the second line of code, "N = 50" is a statement and after the statement, the comment begins with the # symbol. From the # symbol to the end of
this line, the line will be treated as a comment.
Multi- line comment
• Multi-line comment is useful when we need to comment on many lines.
• We can also use single-line comment, but using multi-line instead of single-line comment is easy to comment on multiple
lines.
• In Python Triple double quote (""") and triple single quote (''') are used for Multi-line commenting.
• It is used at the beginning and end of the block to comment on the entire block.
• Hence it is also called block comments.
Example 1:
""" Author: Kings College
Description: Writes the words Hello World on the screen """
Example 2:
‘ ‘ ‘ Author: Kings College
Description: Writes the words Hello World on the screen ‘ ‘ ‘
Docstring in Python
• 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. For example:
def double(num):
"""Function to double the value"""
return 2*num
3.7 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.
3.8 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."""
3.9 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. 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.
>>> (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.
OPERATORS
• Operators are used to perform operations on variables and values.
• 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