Python_Unit1
Python_Unit1
UNIT II
DATA, EXPRESSIONS, STATEMENTS 1.3. Python interpreter:
Python interpreter and interactive mode; values and types: int, float, boolean, string, Interpreter: To execute a program in a high-level language by translating it one line at
and list; variables, expressions, statements, tuple assignment, precedence of operators, a time.
comments; Modules and functions, function definition and use, flow of execution, Compiler: To translate a program written in a high-level language into a low-level
parameters and arguments; Illustrative programs: exchange the values of two language all at once, in preparation for later execution.
variables, circulate the values of n variables, distance between two points.
Compiler Interpreter
1. INTRODUCTION TO PYTHON: Interpreter Takes Single instruction as
Python is a general-purpose interpreted, interactive, object-oriented, and high- Compiler Takes Entire program as input
input
level programming language. No Intermediate Object Code
It was created by Guido van Rossum during 1985- 1990. Intermediate Object Code is Generated
is Generated
Python got its name from “Monty Python’s flying circus”. Python was released in the Conditional Control Statements are Conditional Control Statements are
year 2000. Executes faster Executes slower
Python is interpreted: Python is processed at runtime by the interpreter. You Memory Requirement is More(Since Object
do not need to compile your program before executing it. Memory Requirement is Less
Code is Generated)
Python is Interactive: You can actually sit at a Python prompt and interact with Every time higher level program is
the interpreter directly to write your programs. Program need not be compiled every time
converted into lower level program
Python is Object-Oriented: Python supports Object-Oriented style or technique Errors are displayed after entire Errors are displayed for every
of programming that encapsulates code within objects. program is checked instruction interpreted (if any)
Python is a Beginner's Language: Python is a great language for the beginner- Example : C Compiler Example : PYTHON
level programmers and supports the development of a wide range of
applications. 1.4 MODES OF PYTHON INTERPRETER:
1.1. Python Features: Python Interpreter is a program that reads and executes Python code. It uses 2 modes
Easy-to-learn: Python is clearly defined and easily readable. The structure of Execution.
of the program is very simple. It uses few keywords. 1. Interactive mode
Easy-to-maintain: Python's source code is fairly easy-to-maintain. 2. Script mode
Portable: Python can run on a wide variety of hardware platforms and has the Interactive mode:
same interface on all platforms. Interactive Mode, as the name suggests, allows us to interact with OS.
Interpreted: Python is processed at runtime by the interpreter. So, there is no When we type Python statement, interpreter displays the result(s)
need to compile a program before executing it. You can simply run the program. immediately.
Extensible: Programmers can embed python within their C,C++,Java script Advantages:
,ActiveX, etc. Python, in interactive mode, is good enough to learn, experiment or explore.
Free and Open Source: Anyone can freely distribute it, read the source code, and Working in interactive mode is convenient for beginners and for testing small
edit it. pieces of code.
High Level Language: When writing programs, programmers concentrate on Drawback:
solutions of the current problem, no need to worry about the low level details. We cannot save the statements and have to retype all the statements once again to
Scalable: Python provides a better structure and support for large programs re-run them.
than shell scripting. In interactive mode, you type Python programs and the interpreter displays the result:
1.2. Applications: >>> 1 + 1
Bit Torrent file sharing 2
Google search engine, Youtube The chevron, >>>, is the prompt the interpreter uses to indicate that it is ready for you
Intel, Cisco, HP, IBM to enter code. If you type 1 + 1, the interpreter replies 2.
i–Robot >>> print ('Hello, World!')
NASA Hello, World!
Value:
Value can be any letter ,number or string.
Eg, Values are 2, 42.0, and 'Hello, World!'. (These values belong to different
datatypes.)
Data type:
Every value in Python has a data type.
It is a set of values, and the allowable operations on those values.
Python has four standard data types:
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 the
extension .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.
2.1Numbers:
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,
Interactive mode Script mode
A way of using the Python interpreter by A way of using the Python interpreter to
typing commands and expressions at the read and execute statements in a script.
prompt.
Cant save and edit the code Can save and edit the code
If we want to experiment with the code, If we are very clear about the code, we can
we can use interactive mode. use script mode.
we cannot save the statements for further we can save the statements for further use
use and we have to retype and we no need to retype
all the statements to re-run them. all the statements to re-run them.
We can see the results immediately. We cant see the code immediately.
Operations on list:
Indexing
Slicing
Concatenation
Positive indexing helps in accessing the string from the beginning Repetitions
Negative subscript helps in accessing the string from the end. Updation, Insertion, Deletion
Subscript 0 or –ve n(where n is length of the string) displays the first element.
Example: A[0] or A[-5] will display “H” Creating a list >>>list1=["python", 7.79, 101, Creating the list with
Subscript 1 or –ve (n-1) displays the second element. "hello”] elements of different data
Example: A[1] or A[-4] will display “E” >>>list2=["god",6.78,9] types.
Operations on string: Indexing >>>print(list1[0]) Accessing the item in
i. Indexing python the position 0
ii. Slicing >>> list1[2] Accessing the item in
iii. Concatenation 101
iv. Repetitions the position 2
v. Member ship Slicing( ending >>> print(list1[1:3]) - Displaying items from 1st
Creating a string >>> s="good morning" Creating the list with elements of position -1) [7.79, 101] till 2nd.
different data types. Slice operator is >>>print(list1[1:]) - Displaying items from 1st
Indexing >>> print(s[2]) Accessing the item in the used to extract [7.79, 101, 'hello'] position till last.
o position 0 part of a string, or
>>> print(s[6]) Accessing the item in the some part of a list
O position 2 Python
Slicing( ending >>> print(s[2:]) - Displaying items from 2nd till Concatenation >>>print( list1+list2) -Adding and printing the
position -1) od morning last. ['python', 7.79, 101, 'hello', 'god', items of two lists.
Example Output
a = 60 # 60 = 0011 1100 Line 1 - Value of c is 12
b = 13 # 13 = 0000 1101 Line 2 - Value of c is 61
c=0 Line 3 - Value of c is 49
c = a & b; # 12 = 0000 1100 Line 4 - Value of c is -61 Example
print "Line 1 - Value of c is ", c Line 5 - Value of c is 240 x=5 Output
c = a | b; # 61 = 0011 1101 Line 6 - Value of c is 15 y=5 False
print "Line 2 - Value of c is ", c x2 = 'Hello' True
c = a ^ b; # 49 = 0011 0001 y2 = 'Hello'
print "Line 3 - Value of c is ", c print(x1 is not y1)
c = ~a; # -61 = 1100 0011 print(x2 is y2)
17 Unit 2: Data ,expressions, Statements 18 Unit 2: Data ,expressions, Statements
5.OPERATOR PRECEDENCE: Example:
When an expression contains more than one operator, the order of evaluation a=9-12/3+3*2-1 A=2*3+4%5-3/2+6
depends on the order of operations. a=? A=6+4%5-3/2+6 find m=?
a=9-4+3*2-1 A=6+4-3/2+6 m=-43||8&&0||-2
Operator Description a=9-4+6-1 A=6+4-1+6 m=-43||0||-2
a=5+6-1 A=10-1+6 m=1||-2
** Exponentiation (raise to the power)
a=11-1 A=9+6 m=1
~+- Complement, unary plus and minus (method a=10 A=15
names for the last two are +@ and -@)
a=2,b=12,c=1 a=2*3+4%5-3//2+6
* / % // Multiply, divide, modulo and floor division d=a<b>c a=2,b=12,c=1 a=6+4-1+6
d=2<12>1 d=a<b>c-1 a=10-1+6
+- Addition and subtraction d=1>1 d=2<12>1-1 a=15
d=0 d=2<12>0
>> << Right and left bitwise shift d=1>0
d=1
& Bitwise 'AND'
6.9 MODULES:
A module is a file containing Python definitions ,functions, statements and
instructions. Built-in python modules are,
Standard library of Python is extended as modules. 1.math – mathematical functions:
To use these modules in a program, programmer needs to import the some of the functions in math module is,
module. math.ceil(x) - Return the ceiling of x, the smallest integer greater
25 Unit 2: Data ,expressions, Statements 26 Unit 2: Data ,expressions, Statements
than or equal to x print(a) ['1', '2', '3', '4']
math.floor(x) - Return the floor of x, the largest integer less than or for i in range(1,len(a),1): ['2', '3', '4', '1']
equal to x. print(a[i:]+a[:i]) ['3', '4', '1', '2']
math.factorial(x) -Return x factorial. math.gcd(x,y)- Return the ['4', '1', '2', '3']
greatest common divisor of the integers a and b
math.sqrt(x)- Return the square root of x
math.log(x)- return the natural logarithm of x Part A:
math.log10(x) – returns the base-10 logarithms 1. What is interpreter?
math.log2(x) - Return the base-2 logarithm of x. 2. What are the two modes of python?
math.sin(x) – returns sin of x radians 3. List the features of python.
math.cos(x)- returns cosine of x radians 4. List the applications of python
math.tan(x)-returns tangent of x radians 5. List the difference between interactive and script mode
math.pi - The mathematical constant π = 3.141592 6. What is value in python?
math.e – returns The mathematical constant e = 2.718281 7. What is identifier? and list the rules to name identifier.
8. What is keyword?
2 .random-Generate pseudo-random numbers 9. How to get data types in compile time and runtime?
random.randrange(stop) 10. What is indexing and types of indexing?
random.randrange(start, stop[, step]) 11. List out the operations on strings.
random.uniform(a, b) 12. Explain slicing?
-Return a random floating point number 13. Explain below operations with the example
(i)Concatenation (ii)Repetition
ILLUSTRATIVE PROGRAMS 14. Give the difference between list and tuple
Program for SWAPPING(Exchanging )of Output 15. Differentiate Membership and Identity operators.
values 16. Compose the importance of indentation in python.
a = int(input("Enter a value ")) Enter a value 5 17. Evaluate the expression and find the result
b = int(input("Enter b value ")) Enter b value 8 (a+b)*c/d
c=a a=8 a+b*c/d
a=b b=5 18. Write a python program to print ‘n’ numbers.
b=c 19. Define function and its uses
print("a=",a,"b=",b,) 20. Give the various data types in Python
21. Assess a program to assign and access variables.
Program to find distance between two Output 22. Select and assign how an input operation was done in python.
points 23. Discover the difference between logical and bitwise operator.
import math enter x1 7 24. Give the reserved words in Python.
x1=int(input("enter x1")) enter y1 6 25. Give the operator precedence in python.
y1=int(input("enter y1")) enter x2 5 26. Define the scope and lifetime of a variable in python.
x2=int(input("enter x2")) enter y2 7 27. Point out the uses of default arguments in python
y2=int(input("enter y2")) 2.5 28. Generalize the uses of python module.
distance =math.sqrt((x2-x1)**2)+((y2- 29. Demonstrate how a function calls another function. Justify your answer.
y1)**2) 30. List the syntax for function call with and without arguments.
print(distance) 31. Define recursive function.
32. What are the two parts of function definition? give the syntax.
Program to circulate n numbers Output: 33. Point out the difference between recursive and iterative technique.
a=list(input("enter the list")) enter the list '1234' 34. Give the syntax for variable length arguments.