Unit 2
Unit 2
By:
Ramraj Dangi
Chapter 2: Python Data, Expressions and Statements
Python is simpler to use, available on Windows, Mac OS X, and Unix operating systems,
and will help you get the job done more quickly.
Python Features
1) Easy to Learn and Use
Python is easy to learn- compared to other PL. Its syntax is straightforward - same as the English language. No use of the
semicolon or curly-bracket, the indentation defines the code block.
2) Expressive Language
Python can perform complex tasks using a few lines of code. A simple example, the hello world program you simply type
print("Hello World"). It will take only one line to execute, while Java or C takes multiple lines.
3) Interpreted Language
Python is an interpreted language; it means the Python program is executed one line at a time. The advantage of being
interpreted language, it makes debugging easy and portable.
4) Cross-platform Language
Python can run equally on different platforms such as Windows, Linux, UNIX, and Macintosh, etc. So, we can say that
Python is a portable language. It enables programmers to develop the software for several competing platforms by writing
a program only once.
Python Features Cont.
5) Free and Open Source
Python is freely available for everyone. It is freely available on its official website www.python.org. The open-source means,
"Anyone can download its source code without paying any penny."
6) Object-Oriented Language
Python supports object-oriented language and concepts of classes and objects come into existence. The object-oriented
procedure helps to programmer to write reusable code and develop applications in less code.
10) Integrated
It can be easily integrated with languages like C, C++, and JAVA, etc. Python runs code line by line like C,C++, Java. It
makes easy to debug the code.
11) Embeddable
The code of the other programming language can use in the Python source code. We can use Python source code in another
programming language as well. It can embed other language into our code.
Usage of Python
The various areas of Python use are given below. Some Research Areas
● Beginner level — IDLE (or Online Python Editors) is perfect choice for the first steps in python
language. PyCharm is also good but takes the help of some experienced person while using this.
● Intermediate level— PyCharm, Sublime, Atom, Vs Code.
● Advanced level— PyCharm, Vim, Emacs, Sublime, Atom, Vs Code.
● A value is one of the fundamental things — like a letter or a number — that a program
manipulates.
● These values can belong to different data types.
● Python variable do not need explicit declaration to reserve memory space. The declaration
happens automatically when you assign value to a variable.
● The assignment operator (=) is used to assign values to the variables.
Ex. a = 10, here ‘a’ is variable name and ‘10’ is value assigned to the variable ‘a’.
Type Checking in Python
name = ‘Saksham’
type(name)
String type
Chapter 2: Python Data, Expressions and Statements
● Fixed values such as numbers, letters, and strings are called “constants”
- because their value does not change
● Numeric constants are as you expect
● String constants use single-quotes (') or double-quotes (")
Example:
● >>> print 123
123
● >>> print 98.6
98.6
● >>> print 'Hello world'
Hello world
Variable
Variable is a name that is used to refer to memory location. Python variable is also known as an
identifier and used to hold value.
In Python, we don't need to specify the type of variable because Python is a infer language and
smart enough to get variable type.
Variable names can be a group of both the letters and digits, but they have to begin with a letter
or an underscore.
It is recommended to use lowercase letters for the variable name. Rahul and rahul both are two
different variables.
Variable or Identifier Naming
● Variables are the example of identifiers. An Identifier is used to identify the literals used in
the program. The rules to name an identifier are given below.
● The first character of the variable must be an alphabet or underscore ( _ ).
● All the characters except the first character may be an alphabet of lower-case(a-z), upper-
case (A-Z), underscore, or digit (0-9).
● Identifier name must not contain any white-space, or special character (!, @, #, %, ^, &,
*).
● Identifier name must not be similar to any keyword defined in the language.
● Identifier names are case sensitive; for example, my name, and MyName is not the same.
● Examples of valid identifiers: a123, _n, n_9, etc.
● Examples of invalid identifiers: 1a, n%4, n 9, etc.
Declaring Variable and Assigning Values
In Python, variables are a symbolic name that is a reference or pointer to an object. The variables are
used to denote objects by that name.
Let's understand the following example
a = 50
In the image, the variable a refers to an integer object.
Suppose we assign the integer value 50 to a new variable b.
b=a
The variable b refers to the same object that a points to because Python does not create another object.
Declaring Variable and Assigning Values
Let's assign the new value to b. Now both variables will refer to the different objects.
a = 50
b =100
Python manages memory efficiently if we assign the same variable to two different values.
Variable Names
We have already discussed how to declare the valid variable. Variable names can be any length can have
uppercase, lowercase (A to Z, a to z), the digit (0-9), and underscore character(_). Consider the following
example of valid variables names.
name = "Devansh"
age = 20
marks = 80.50
print(name)
print(age)
print(marks)
Output:
Devansh
20
80.5
Multiple Assignment
Python allows us to assign a value to multiple variables in a single statement, which is also known as
multiple assignments.
We can apply multiple assignments in two ways, either by assigning a single value to multiple variables or
assigning multiple values to multiple variables. Consider the following example.
1. Assigning single value to multiple variables
Eg:
x=y=z=50
print(x)
print(y)
print(z)
Output:
50
50
50
Multiple Assignment
2. Assigning multiple values to multiple variables:
Eg:
a,b,c=5,10,15
print a
print b
print c
Output:
5
10
15
The values will be assigned in the order in which variables appear.
Python Variable Types
There are two types of variables in Python - Local variable and Global variable. Let's understand the following variables.
Local Variable
Local variables are the variables that declared inside the function and have scope within the function. Let's understand the
following example.
Example -
# Declaring a function
def add():
# Defining local variables. They has scope only within a function
a = 20
b = 30
c=a+b Output:
print("The sum is:", c)
# Calling a function The sum is: 50
add()
Local Variable
Explanation:
In the above code, we declared a function named add() and assigned a few variables within the
function. These variables will be referred to as the local variables which have scope only inside the
function. If we try to use them outside the function, we get a following error.
add()
# Accessing local variable outside the function
print(a)
Output:
The sum is: 50
print(a)
NameError: name 'a' is not defined
We tried to use local variable outside their scope; it threw the NameError.
Global Variable
Global variables can be used throughout the program, and its scope is in the entire program. We can use global variables inside or
outside the function.
A variable declared outside the function is the global variable by default. Python provides the global keyword to use global variable
inside the function. If we don't use the global keyword, the function treats it as a local variable. Let's understand the following example.
Example -
# Declare a variable and initialize it
x = 101
# Global variable in function
def mainFunction():
# printing a global variable
global x
Output:
print(x)
# modifying a global variable 101
x = 'Welcome To Class' Welcome To Class
print(x) Welcome To Class
mainFunction()
print(x)
Global Variable
Explanation:
In the above code, we declare a global variable x and assign a value to it. Next, we defined a function and
accessed the declared variable using the global keyword inside the function. Now we can modify its value.
Then, we assigned a new string value to the variable x.
Now, we called the function and proceeded to print x. It printed the as newly assigned value of x.
Reserved Words Or Keywords
● A statement is an instruction that the Python interpreter can execute. We have seen two kinds of
statements: print and assignment.
● When you type a statement on the command line, Python executes it and displays the result, if
there is one. The result of a print statement is a value. Assignment statements don’t produce a
result.
● A script usually contains a sequence of statements. If there is more than one statement, the
results appear one at a time as the statements execute.
● Example:
print 1 1
x=2 2
print x
Chapter 2: Python Data, Expressions and Statements
● Arithmetic Operators
● Comparison Operators
● Logical Operators
● Bitwise Operators
● Identity Operators
● Operator Precedence
● Augmented Assignment Operators
Arithmetic Operator
+ (unary) +a Unary Positive In other words, it doesn’t really do anything. It mostly
exists for the sake of completeness, to complement
Unary Negation.
<= a <= b Less than or equal to True if a is less than or equal to b, False otherwise
>= a >= b Greater than or equal to True if a is greater than or equal to b, False otherwise
Logical Operator
True if x is False
False if x is True
not not x (Logically reverses the sense of x)
| a|b bitwise OR Each bit position in the result is the logical OR of the bits in
the corresponding position of the operands. (1 if either is 1,
otherwise 0.)
~ ~a bitwise negation Each bit position in the result is the logical negation of the bit
in the corresponding position of the operand. (1 if 0, 0 if 1.)
^ a^b bitwise XOR Each bit position in the result is the logical XOR of the bits in
(exclusive OR) the corresponding position of the operands. (1 if the bits in the
operands are different, 0 if they are the same.)
>> a >> n Shift right n places Each bit is shifted right n places.
<< a << n Shift left n places Each bit is shifted left n places.
Identity Operator
Python membership operators are used to check the membership of value inside a Python
data structure. If the value is present in the data structure, then the resulting value is true
otherwise it returns false.
● In :- It is evaluated to be true if the first operand is found in the second operand (list,
tuple, or dictionary).
● not in :- It is evaluated to be true if the first operand is not found in the second
operand (list, tuple, or dictionary).
Operator Precedence
When we string operators together - Python must know which one to do first. This is called
“operator precedence”.
Here is the order of precedence of the Python operators you have seen so far,
from lowest to highest:
1. Boolean (or, and, not)
2. Comparison (==, !=, <, <=, >, >=)
3. Identity (is, is not)
4. Bitwise (|, ^, &, <<, >>)
5. Arithmetic (+, -,*, /, //, %,+x, -x, ~x(bitwise negation), **)
Order of Operation
When more than one operator appears in an expression, the order of evaluation depends on the rules
of precedence. Python follows the same precedence rules for its mathematical operators that
mathematics does.
1. Parentheses have the highest precedence and can be used to force an expression to evaluate in
the order you want. Ex. 2 * (3-1) is 4, and (1+1)**(5-2) is 8.
2. Exponentiation has the next highest precedence, so 2**1+1 is 3 and not 4, and 3*1**3 is 3 and
not 27.
3. Multiplication and Division have the same precedence, which is higher than Addition and
Subtraction, which also have the same precedence. So 2*3-1 yields 5 rather than 4, and 2/3-1 is
-1, not 1 (remember that in integer division, 2/3=0).
4. Operators with the same precedence are evaluated from left to right.
Comments in Python
To add notes to your programs to explain in natural language what the program is doing. These notes are called
comments, and they are marked with the ‘#’ symbol.
Everything from the ‘#’ to the end of the line is ignored. It has no effect on the program. The message is intended
for the programmer or for future programmers who might use this code.
Single-Line Comments
Ex.
# compute the percentage of the hour that has elapsed
percentage = (minute * 100) / 60
OR
percentage = (minute * 100) / 60 # caution: integer division
Comments in Python
Multi-Line Comments - Python doesn't have explicit support for multi-line comments but we can use hash #
character to the multiple lines. For example -
Indentation in Python
Indentation is the most significant concept of the Python programming language. Improper use
of indentation will end up "IndentationError" in our code.
Indentation is nothing but adding whitespaces before the statement when it is needed. Without
indentation Python doesn't know which statement to be executed to next. Indentation also
defines which statements belong to which block. If there is no indentation or improper
indentation, it will display "IndentationError" and interrupt our code.
Basic Syntax of Python
Indentation in Python
Data Types in Python
Variables can hold values, and every value has a data-type. Python is a dynamically typed language; hence we do
not need to define the type of the variable while declaring it. The interpreter implicitly binds the value with its type.
a=5
The variable a holds integer value five and we did not define its type. Python interpreter will automatically interpret
variables a as an integer type.
Python enables us to check the type of the variable used in the program. Python provides us the type() function,
which returns the type of the variable passed.
Consider the following example to define the values of different data types and checking its type.
a=10
b="Hi Python"
c = 10.5 Output:
print(type(a)) <type 'int'>
print(type(b)) <type 'str'>
<type 'float'>
print(type(c))
Standard data types
A variable can hold different types of values. For example, a person's name must be stored as a string whereas its id must be stored as an
integer.
Python provides various standard data types that define the storage method on each of them. The data types defined in Python are given
below.
1. Number
2. Sequence Type
3. Boolean
4. Set
5. Dictionary