Unit 2 Notes
Unit 2 Notes
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.
Introduction
PROGRAM:
Python is developed by
Guido van Rossum in 1989.
Python is named after the comedy television show Monty Python’s Flying Circus. It is not
named after the Python snake.
Compiler
• A compiler is a software program that reads the entire program and translates the whole
program into machine code at once.
• The compiler specifies the errors at the end of the compilation with line numbers when
there are any errors in the source code.
Figure:Structure of a Compiler
Interpreter :
• A Interpreter is a software program that converts just one statement of the program at a
time into machine code and executes immediately before moving on to the next line.
• It performs line-by-line execution of a program statement,
• If there is an error in the statement, it displays an error message. The interpreter moves on
to the next line for execution only after the removal of the error .
Figure:Structure of an Interpreter
In the Python programming language, there are two ways in which we can run our code:
1. Interactive mode or Shell Mode 2. Script mode or Program Mode
1. Interactive mode or Shell Mode
• Interactive mode is very convenient for writing very short lines of code.
• In python it is also known as REPL which stands for Read Evaluate Print Loop.
◦ Here, the read function reads the input from the user and stores it in memory.
◦ Eval function evaluates the input to get the desired output.
◦ Print function outputs the evaluated result.
◦ The loop function executes the loop during the execution of the entire program and
terminates when our program ends.
• This mode is very suitable for beginners in programming as it helps them evaluate their
code line by line and understand the execution of code well.
How to run python code in Interactive mode?
2 ways to to run python code in Interactive mode:
a.Using Command prompt in windows
b.Using Python Shell
a.Using Command prompt in windows
In order to run our program in the interactive mode, we can use command prompt in windows:Let
us see understand the execution of python code in the command prompt with the help of an
example:
Example 1:
To run python in command prompt type “python”. Then simply type the Python statement on >>>
prompt. As we type and press enter we can see the output in the very next line.
Mention the List of Keyword available in Python:There are more than 33 keywords in
Python 3.7
Note:
• The above keywords may get altered in different versions of Python.
• Some extra might get added or some might be removed.
• You can always get the list of keywords in your current version by typing the following in
the prompt.
True, False: these are the Boolean values in python. The result of the logical operation is indicated
by any one of these values.
• and, or, not: these are logical operators in python. And the result of these operators is always a
Boolean value.
• if, elif, else: these keywords are used in the decision control structure
• while, for: these keywords are used in a loop control structure
• break, continue: these keywords are used within the loop control structure to terminate the
execution of the loop or to terminate the execution of the current iteration of the loop
• class: this keyword is used to create a user-defined class
• def: this keyword is used to create a user-defined function
• try, except, raise, finally: these keywords are used in exception handling to handle the
exception that occurred during the execution of the program
• from, import: these keywords are used to import any in-built module of python programming
to your current namespace
• global: this keyword is used within the function if you want to access the variable defined
inside the function from outside the function.
Comparing keywords with variable name
( or)Difference between Keywords and Identifiers in Python.
STATEMENTS IN PYTHON
What is a statement in Python?
• A statement is an instruction that a Python interpreter can execute.
◦ print statements:
◦ Assignment statements:
▪ Assignment statements don’t produce a result it just assigns a value to the operand
on its left side.
Example:
◦ Conditional statements
◦ Looping statements.
Multiple statements on a single line:
Multi-Line Statements
• Python statement ends with the token NEWLINE character.
• But we can extend the statement over multiple lines using line continuation character
(\). This is known as an explicit
continuation.
Implicit continuation:
We can use parentheses () to write a multi-line statement. We can add a line continuation statement
inside it. Whatever we add inside a parentheses () will treat as a single statement even it is placed
on multiple lines.
CONSTRUCTING STATEMENTS FROM VARIABLES AND EXPRESSIONS:
EXPRESSION IN PYTHON
Expression statements
• A combination of operands and operators is called an expression.
• The expression in Python produces some value or result after being interpreted by the
Python interpreter.
• An example of expression can be : x=x+10. In this expression, the first110 is added to the
variable x. After the addition is performed, the result is assigned to the 0variable x.
Example :
x = 25 # a statement
x = x + 10 # an expression
print(x)
Output :
35
2.
Arithmetic Expressions
x = 10 # an integer number
y = 5.0 # a floating point number
# we need to convert the floating-point number into an integer or vice versa for summation.
result = x + int(y)
print("The sum of x and y is: ", result)
Output :
The sum of x and y is: 15
4. Floating Expressions
A floating expression in Python is used for computations and type conversion (integer to float,
a string to integer, etc.). A floating expression always produces a floating-point number as a
resultant.
Example :
x = 10 # an integer number
y = 5.0 # a floating point number
# we need to convert the integer number into a floating-point number or vice versa for summation.
result = float(x) + y
Output :
The sum of x and y is: 15.0
5. Relational Expressions
• A relational expression in Python can be considered as a combination of two or more
arithmetic expressions joined using relational operators. The overall expression results
in either True or False (boolean result)
A relational operator produces a boolean result so they are also known as Boolean Expressions.
For example :
10+15>20
1 this example, first, the arithmetic expressions (i.e. 110+15 and 220) are evaluated, and then the
In
results
0 are used for further comparison. 0 0
6.
+ Logical Expressions +
• A logical expression performs the logical computation,
• The overall expression results in either True or False (boolean result).
1 • We have three types of logical expressions in 1Python, let us discuss them briefly.
5 5
>
2
0
Tuple assignment
• Tuple is an ordered sequence of items same as list. The only difference is that tuples
are immutable. Tuples once created cannot be modified.
• Tuples are used to write-protect data and are usually faster than list as it cannot
change dynamically. It is defined within parentheses () where items are separated by
commas.
• Tuple Assignment is often useful to swap the values of two variables. Tuple
assignment is more elegant:
>>> a, b = b, a
• The left side is a tuple of variables; the right side is a tuple of expressions. Each
value is assigned to its respective variable. All the expressions on the right side are
evaluated before any of the assignments.
• The number of variables on the left and the number of values on the right have
to be the same:
>>> a, b = 1, 2, 3
• The right side of tuple can be any kind of sequence (string, list or tuple). For
example, to split an email address into a user name and a domain, you could write:
The return value from split is a list with two elements; the first element is assigned to
uname, the second to domain.
>>> uname
'be'
>>> domain
'gmail.com'
Example program:
a=5
b = 10
print(“Before Swapping”)
print(“a=”,a,”b=”,b)
a, b = b,a
print(“After Swapping”)
print(“a=”,a,”b=”,b)
OPERATORS IN PYTHON
Arithmetic operators
Bitwise operators
Assignment operators
Special operators
Arithmetic operators
Arithmetic operators are used to perform mathematical operations like addition, subtraction,
multiplication etc.
Operator Meaning Example
+ Add two operands or unary plus x+y
- Subtract right operand from the left or unary minus x-y
* Multiply two operands x*y
Divide left operand by the right one (always results into
/ x/y
float)
Modulus - remainder of the division of left operand by
% x % y (remainder of x/y)
the right
** Exponent - left operand raised to the power of right x**y(x to the power y)
Example:
x = 15
y=4
print(x+y)
print(x/y)
print(x%y)
print(x**y)
Output:
19
3.75
50625
Comparison operators are used to compare values. It either returns True or False according
to the condition.
OUTPUT
Operator Meaning Example Assume
x=10;y=20
> Greater than - x>y False
< Less than x<y True
== Equal to x == y False
!= Not equal to x != y True
>= Greater than or equal to x >= y False
<= Less than or equal to x <= y False
Example:
x = 10
y = 12
print(x>y)
print(x<y)
print(x!=y)
Output:
False
True
True
Logical operators
Logical Operators are used to perform logical operations like and, or and not.
Example:
Operator Meaning Output
x=6
and True if both the operands are true x < 5 and x < 10 False
or True if either of the operands is true x < 10 or x < 4 True
True if operand is false
not not(x < 5 and x < 10) True
(complements the operand)
Example:
x = True
y = False
print(x and y)
print(x or y)
print(not x)
Output:
x and y is False
x or y is True
not x is False
Bitwise operators
Bitwise operators act on operands as if they were string of binary digits. They are used to
perform bit by bit operations.
Operator Meaning Example
& Bitwise AND x& y
| Bitwise OR x|y
~ Bitwise NOT ~x
^ Bitwise XOR x^y
>> Bitwise right shift x>> 2
<< Bitwise left shift x<< 2
Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)
Example:
x=10
y=4
print(x&y)
Output:
Assignment operators
Example:
x=5
print(x)
Output
5
Special operators
Python language offers some special type of operators like the identity operator or the
membership operator.
Identity operators
is and is not are the identity operators in Python. They are used to check if two values (or
variables) are located on the same part of the memory. Two variables that are equal does not imply
that they are identical.
Operator Meaning Example
is True if the operands are identical (refer to the same object) x is True
is not True if the operands are not identical (do not refer to the same object) x is not True
Example:
x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
print(x1 is not y1)
print(x2 is y2)
Output:
False
True
Membership operators
in and not in are the membership operators in Python. They are used to test whether a value
or variable is found in a sequence (string, list, tuple, set and dictionary).
Operator Meaning Example
in True if value/variable is found in the sequence 5 in x
not in True if value/variable is not found in the sequence 5 not in x
Example:
x = 'Hello world'
y = {1:'a',2:'b'}
print('H' in x)
print('a' not in y)
Output:
True
False
2.6.1 Precedence of Operators in Python:– PEMDAS
What is Operator Precedence???
Operator Precedence in Python programming is a rule that describe which operator is
solved first in an expression. For example: * and / have same precedence and their associativity
is Left to Right, so the expression 18 / 2 * 5 is treated as (18 / 2) * 5.
When an expression contains more than one operator, the order of evaluation depends on the
order of operations or precedence of operators.
◦ P – Parentheses
◦ E – Exponentiation
◦ M – Multiplication
◦ D – Division
◦ A – Addition
◦ S – Subtraction
NOTE:
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,
• Example Program:
# Parentheses () has higher precedence
>>> (10 - 4) * 2
12
Multiplication and Division have higher precedence than Addition and Subtraction.
Examples: 2*3-1 is 5
6+4/2 is 8.
>>> 10 - 4 * 2
2
Operators with the same precedence are evaluated from left to right (except
exponentiation).
Example: In the expression, degrees / 2 * pi, the division happens first and the result
is multiplied by pi.
• The upper operator holds higher precedence than the lower operator.
Example Program for operator precedence:
colour = "red"
quantity = 0
else:
Output:
• When two operators have the same precedence, associativity helps to determine the order of
operations.
• Almost all the operators have left to right associativity except exponentiation.
Example:
• Hence if both the operators were present in an expression the left one will be evaluated first.
print(10*2//3)
Program:
# Left-right associativity
# Output: 3 Output:
print(5 * 2 // 3) 3
print(5 * (2 // 3))
Program:
# Shows the right-left associativity of ** OUTPUT:
# Output: 512, Since 2**(3**2) = 2**9 512
64
print(2 ** 3 ** 2)
print((2 ** 3) ** 2)
COMMENTS
As programs get bigger and more complicated, they are difficult to understand. So, notes
can be added to the programs in natural language for better understanding.
These notes are called comments, and they start with the # symbol:
Creating a Comment
• Comments starts with a #, and Python Interpreter will ignore them:
Example:
#This is a comment
print("Hello, World!")
Output:
Hello,World
• Comments can be placed at the end of a line, and Python will ignore the rest
of the line:
Example
#This is a comment
#written in
#more than just one line
print("Hello, World!")
• Since Python will ignore string literals that are not assigned to a variable, you
can add a multiline string (triple quotes) in your code, and place your
comment inside it:
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
• As long as the string is not assigned to a variable, Python will read the code,
but then ignore it, and you have made a multiline comment.
Good variable names can reduce the need for comments, but long names can make complex
expressions hard to read.
Example Program:
print(“x=”,x,”y=”,y)
2.11.2 Circulate the values of N variables
Method 1: Method 2:
temp=a[j] a.append(int(input()))
a[j-1]=temp j=len(a)-1
a[j]=a[j-1]
a[j-1]=temp
j=j-1
print("Circulated List:",a)
Output Output
Formula:
Distance =
dist=math.sqrt((x2-x1)**2+(y2-y1)**2) p2=[6,6]
Output Output
5.65685424949 6.32455532034
1. Function Definition
Function Definition
In Python, before using the functions in the program, the function must be defined.
Syntax:
def is a reserved word that tells Python that a function is about to be defined.
List of formal parameters of the function is the sequence of names within the parentheses
following the function name.
body of function refers to any piece of Python code. A special statement return can be used
only within the body of a function.
Example:
if x > y:
return x
else:
return y
A function call(function invocation) is an expression that has a value which is the value
returned by the invoked function.
When the function is used, the formal parameters are bound (as in an assignment statement)
to the actual parameters (arguments) of the function invocation (function call).
Syntax:
functionname (actualarguments)
Example:
max(3, 4)
- binds x to 3 and y to 4.
Example:
The value of the expression max(3,4) * max(3,2) is 12, because the first invocation of max
returns the int 4 and the second returns the int 3.
Program:
return x+y
a=int(input("Enter a:"))
b=int(input("Enter b:"))
print("Addition:",c)
• Inside the function, the arguments are assigned to variables called parameters.
def print_twice(result):
print(result)
print(result)
• The value can also be used as argument. When the function is called, it prints
the value of the parameter twice.
Example:
>>> print_twice('Hello')
Hello
Hello
>>> print_twice(42)
42
42
• The expression can also be used as arguments. The argument is evaluated before the
function is called.
Example:
>>> print_twice('Hello'*4)
Example:
>>> print_twice(m)
Hello Python
Hello Python
#FUNCTION DEFINTION
def swap(x,y):
x, y = y, x
#DRIVER CODE
x = int(input(“Enter x value:”))
y = int(input(“Enter y value:”))
print(“Before Swapping”)
print(“x=”,x,”y=”,y)
swap(x,y)
print(“After Swapping”)
print(“x=”,x,”y=”,y)
OUTPUT:
Swap two variables using function in Python
Swap of two variables using function in Python can be done by passing our variables to
the user defined function as arguments and returning or printing the swapped data.