Python Unit 1 Nots
Python Unit 1 Nots
AVCCE/MCA/R-21/I-SEM/NS Page 1
2. Allen B. Downey, “Think Python: How to Think Like a Computer Scientist”, Second Edition,
Shroff,O‘Reilly Publishers, 2016 (http://greenteapress.com/wp/thinkpython/)
3. Guido van Rossum, Fred L. Drake Jr., “An Introduction to Python – Revised and Updated
forPython 3.2, Network Theory Ltd., First edition, 2011
4. John V Guttag, “Introduction to Computation and Programming Using Python”,Revised
and Expanded Edition, MIT Press, 2013
5. Charles Dierbach, “Introduction to Computer Science using Python”, Wiley IndiaEdition,
First Edition, 2016
6. Timothy A. Budd, “Exploring Python”, Mc-Graw Hill Education (India) Private Ltd.,First
edition,2011
7. Kenneth A. Lambert, “Fundamentals of Python: First Programs”, Cengage Learning, second
edition,2012
Websites
1. https://www.learnpython.org/
2. https://www.codecademy.com/learn/learn-python
3. https://docs.python.org/3/tutorial/
4. https://runestone.academy/runestone/books/published/thinkcspy/index.html
5. https://nptel.ac.in/courses/106106182/
6. http://172.16.25.76/course/view.php?id=1225
7. https://www.educba.com/list-operations-in-python/
8. https://realpython.com/python-idle/
9. https://data-flair.training/blogs/python-interpreter/
10. https://techvidvan.com/tutorials/python-interpreter/
Online compiler
https://www.programiz.com/python-programming/online-compiler/
https://www.w3schools.com/python/python_compiler.asp
Python is a Second Most popular programming language in the world. It was created by
Guido van Rossum, and released in 1991. It is used for software development. It can be used
on a server to create web applications. It can connect to database systems. It can also read and
modify files. It is used to handle big data and perform complex mathematics. Python works
on different platforms(windows ,Linux, etc.,) It is similar to the English language and follows
simple syntax.
AVCCE/MCA/R-21/I-SEM/NS Page 3
• Versatile - Used in many applications like robotics, machine learning. Even google
uses python programming.
• Free and Open Source - Can be downloaded at free of cost.
• High-level Language - Uses simple english and symbols
• Interactive - This interactive mode helps in displaying the output immediately as
soon as you enter the code.
• Object Oriented – Uses object oriented concepts like message passing,
inheritance,etc.,
• Interpreted - source code (line by line scaning) is translated to machine code by the
interpreter and can be directly executed. No need of pre compilation like C,C++.
• Easy to maintain
• Secure - Allow us to perform cryptographic techniques for security purpose.
• Multi-threaded - allow multiple threads to execute simultaneously.
• Garbage Collection -Performs automatic memory management.
AVCCE/MCA/R-21/I-SEM/NS Page 4
AVCCE/MCA/R-21/I-SEM/NS Page 5
AVCCE/MCA/R-21/I-SEM/NS Page 6
Output:
Enter ur name SRINIVASAN
Your name is SRINIVASAN
AVCCE/MCA/R-21/I-SEM/NS Page 7
• Python doesn’t convert its code into machine code, It actually converts it into byte
code. So within python, compilation happens, but this byte code can’t be understood
by CPU. So we need actually an interpreter called the python virtual machine. The
python virtual machine executes the byte codes.
• The term syntax is referred to a set of rules and principles that describes the structure
of a language. The Python syntax defines all the set of rules that are used to create
sentences in Python programming.
• For example – we have to learn grammar when we want to learn the English
language.
• In the same way, you will need to learn and understand the Python syntax in order to
learn the Python language.
AVCCE/MCA/R-21/I-SEM/NS Page 8
AVCCE/MCA/R-21/I-SEM/NS Page 9
• Since Python doesn’t use curly braces to delimit blocks of code, this Python Syntax is
mandatory. You can indent code under a function, loop, or class.
– >>> if a>b:
print(“a is greater than b");
– Output:
• a is greater than b
1.3.1.4 Python Quotations
• Python supports the single quote and the double quote for string literals. But if you
begin a string with a single quote, you must end it with a single quote. The same goes
for double-quotes. The following string is delimited by single quotes.
– >>> print('Welcome to AVCCE’)
• Output:
– 'Welcome to AVCCE
– This string is delimited by double-quotes.
– >>> print(" Welcome to ‘AVCCE’ ");
• Output:
– Welcome to ‘AVCCE’
1.3.1.5 Python Blank Lines
• If you leave a line with just whitespace, the interpreter will ignore it.
AVCCE/MCA/R-21/I-SEM/NS Page 10
1.3.1.7 Variables
Variable means its value can vary. You can store any piece of information in a
variable. Variables are nothing but just parts of your computer’s memory where information
is stored. To be identified easily, each variable is given an appropriate name.
1. Identifiers are names given variable, function, class, module or other object.
2. Rules for naming Identifier
Special characters are not allowed within identifier
Identifier names are case sensitive, so creation and usage of identifier needs to be
taken care.For example, myvar and myVar are not the same.
Use underscores( ‘_’) to separate multiple words in identifiers.
It should not begin with a number.
Punctuation characters such as @, $, and % are not allowed within identifiers.
AVCCE/MCA/R-21/I-SEM/NS Page 11
The value of a literal constant can be used directly in programs. For example, 7, 3.9,
'A', and "Hello" are literal constants. Numbers are referred to as numeric value. Python
supports four types of numbers - integers, long integers, floating point and complex
numbers.
• Numbers like 5 or other whole numbers are referred to as integers.
• Bigger whole numbers are called long integers. For example, 535633629843L is a
long integer.
• Numbers like are 3.23 are termed as floating point numbers.
• Numbers like 3 + 7i are complex numbers.
Example:
1.3.1.8.1 Strings
• A string is a group of characters.
• Using Single Quotes ('):
– A string can be written as 'HELLO'.
• Using Double Quotes ("):
– A string can also be written in double quotes. Therefore, 'HELLO' is same as
"HELLO".
• Using Triple Quotes (''' '''):
– Multi-line strings can be written using triple quotes.
‘’’ hai hello
This is India’’’
1.3.1.9 Python Identifiers
An identifier is a name of a program element, and it is user-defined. This Python
Syntax uniquely identifies the element. There are some rules to follow while choosing an
identifier:
– An identifier may only begin with A-Z, a-z, or an underscore(_).
– This may be followed by letters, digits, and underscores- zero or more.
– Python is case-sensitive. Name and name are two different identifiers.
– A reserved keyword may not be used as an identifier.
– The following is a list of keywords.
AVCCE/MCA/R-21/I-SEM/NS Page 12
Apart from these rules, there are a few naming conventions that you should follow
while using this Python syntax:
• Use uppercase initials for class names,
– lowercase for all others.
• Name a private identifier with a leading underscore ( _username)
• Name a strongly private identifier with two leading underscores ( __password)
• Special identifiers by Python end with two leading underscores.
1.4 Operators
Arithmetic Operation
AVCCE/MCA/R-21/I-SEM/NS Page 13
Another Example
a=5 Output
b=2 7
print(a+b) 3
print(a-b) 10
print(a*b) 2.5
print(a/b) 1
print(a%b) 2
print(a//b)
Operators:
Operator Description Example
AVCCE/MCA/R-21/I-SEM/NS Page 14
| x|y Bitwise OR
AVCCE/MCA/R-21/I-SEM/NS Page 15
Bitwise OR operator:
If any one of the bit is 1, it returns 1 else it returns 0.
Shift Operators:
By multiplying or dividing the given number by 2, the bits of the figure is shifted to
left or right by using the Shift operators.
& 0 1 | 0 1
0 0 0 0 0 1
1 0 1 1 1 1
AVCCE/MCA/R-21/I-SEM/NS Page 16
AVCCE/MCA/R-21/I-SEM/NS Page 17
Example Programme
a = 21
b = 10
c = 0
c = a + b
print "Line 1 - Value of c is ", c
c += a
print "Line 2 - Value of c is ", c
c *= a
print "Line 3 - Value of c is ", c
c /= a
print "Line 4 - Value of c is ", c
c = 2
c %= a
print "Line 5 - Value of c is ", c
c **= a
print "Line 6 - Value of c is ", c
c //= a
print "Line 7 - Value of c is ", c
AVCCE/MCA/R-21/I-SEM/NS Page 18
OUTPUT
Line 1 - Value of c is 31
Line 2 - Value of c is 52
Line 3 - Value of c is 1092
Line 4 - Value of c is 52
Line 5 - Value of c is 2
Line 6 - Value of c is 2097152
Line 7 - Value of c is 99864
Boolean Values
In programming you often need to know if an expression is True or False. You can
evaluate any expression in Python, and get one of two answers, True or False. When you
compare two values, the expression is evaluated and Python returns the Boolean answer:
Example Output
print(10 > 9) True
print(10 == 9) False
print(10 < 9) False
RULES – PEMDAS
• P - parenthesis
• E - Exponent(Square root & power)
• MD - Multiplication and Division
• AS - Add and Subtract
Example: ( 5 * (4 / 2))
Here, 4/2 is evaluated at first, With that result than 5 is multiplied.
AVCCE/MCA/R-21/I-SEM/NS Page 19
1.5 Expression
An expression is a combination of values, variables, operators, and calls to
functions. Expressions need to be evaluated. If you ask Python to print an expression, the
interpreter evaluates the expression and displays the result.
1.7 Conditionals:
In order to write useful programs, we almost always need the ability to check
conditions and change the behaviour of the program accordingly. Selection statements,
sometimes also referred to as conditional statements, give us this ability. The simplest form
of selection is the if statement.
A selection statement causes the program control to be transferred to a specific part of
the program based upon the condition. If the conditional test is true, one part of the program
will be executed, otherwise it will execute the other part of the program.
Syntax
if(cond):
statement
Example:
a=10
if(a>0):
print(“a is Non Zero”)
AVCCE/MCA/R-21/I-SEM/NS Page 20
Output:
a is non zero
Syntax
if(cond):
statement
elif(cond):
statement
else:
statement
#program for student grade
mark=60
if(mark>80):
print(“ First class”)
elif(mark>=50 and mark<80):
print(” Second class”)
else:
print(“fail”)
Output:
Second class
AVCCE/MCA/R-21/I-SEM/NS Page 21
temp=32
if(temp>30):
if(temp>35):
print(“very hot”)
else:
print(“hot”)
else:
print(“normal”)
Output:
hot
In some programs, certain set of statements are executed again and again based upon
some condition . i.e. executed more than one time. This type of execution is called looping or
iteration. Repeated execution of a sequence of statements is called iteration. Two types
– for loop (auto incremented)
– while loop (not auto incremented)
Syntax
for iteration in sequence:
statements(s)
Example:
AVCCE/MCA/R-21/I-SEM/NS Page 22
The while statement provides a much more general mechanism for iterating. Similar
to the if statement, it uses a boolean expression to control the flow of execution. The body of
while will be repeated as long as the controlling boolean expression evaluates to True.
Syntax
while(condition):
body of loop
# Programme to print natural numbers
i=1
n=int(input("enter the end number"))
while i<=n:
print(i)
i=i+1
Output
1 2 3 4 5 6 7 8 9 10 11
AVCCE/MCA/R-21/I-SEM/NS Page 23
AVCCE/MCA/R-21/I-SEM/NS Page 24
1.9 Function
Function is a sub program which consists of set of instructions used to perform a
specific task. When the program is too complex and large they are divided into parts. Each
part is separately coded and combined into single program.
Functions make it more organized and manageable. Debugging, Testing and
maintenance becomes easy when the program is divided into subprograms. Functions are
used to avoid rewriting same code again and again in a program. Function provides code re-
usability; the length of the program is reduced.
User defined functions are the functions that programmers create for their requirement
and use. These functions can then be combined to form module which can be used in other
programs by importing them.
Programmers working on large project can divide the workload by making different
functions. If repeated code occurs in a program, function can be used to include those codes
and execute when needed by calling that function. A function can be defined and can be
called at any place in a program.
AVCCE/MCA/R-21/I-SEM/NS Page 25
Syntax:
def fun_name(Parameter1,Parameter2…Parameter n):
statement1
statement2…
statement n return[expression]
Once we have defined a function, we can call it from another function, program or
even from the Python prompt. To call a function we simply type the function name with
appropriate arguments.
Syntax:
function_name(parameters);
AVCCE/MCA/R-21/I-SEM/NS Page 26
In this type no argument is passed through the function call and no output is return to
main function. The sub function will read the input values perform the operation and print the
result in the same block
The return statement is used to exit a function and go back to the place from where it
was called. If the return statement has no arguments, then it will not return any values. But
exits from function.
Syntax:
return [expression]
Example Programmes
AVCCE/MCA/R-21/I-SEM/NS Page 27
1.9.4.1 Parameters:
Parameters are the value(s) provided in the parenthesis when we write function
header. These are the values required by function to work. If there is more than one value
required, all of them will be listed in parameter list separated by comma.
1.9.4.2 Arguments :
Example: my_add(x,y)
All parameters (arguments) in the Python language are passed by reference. It means
if you change a parameter refers to within a function that change also reflects back in the
calling function.
1. Required Arguments
2. Keyword Arguments
3. Default Arguments
4. Variable length Arguments
The number of arguments in the function call should match exactly with the function
definition.
Example
AVCCE/MCA/R-21/I-SEM/NS Page 28
Output:
Name: srini Age 41
Python interpreter is able to use the keywords provided to match the values with
parameters even though if they are arranged in out of order.
Example
def my_details(name,age):
print("Name: ", name)
print("Age :", age)
return
my_details(age=41,name="srini")
Output
Name: srini
Age 41
Assumes a default value if a value is not provided in the function call for that
argument.
Example
defmy_details( name, age=41 ):
print("Name: ", name)
print("Age :", age) return
my_details(name=“srini")
Output:
Name: srini Age:41
If we want to specify more arguments than specified while defining the function,
variable length arguments are used. It is denoted by * symbol before parameter.
Example:
def my_details(*name ):
print(*name)
my_details("rajan","rahul","micheal", ärjun")
AVCCE/MCA/R-21/I-SEM/NS Page 29
Output:
rajan rahul micheal ärjun
All variables in a program may not be accessible at all locations in that program. This
depends on where you have declared a variable. The scope of a variable determines the
portion of the program where you can access a particular identifier.
Global Variables
Local Variables
A variable declared inside the function's body or in the local scope is known as a local
variable.
A function that calls itself. A physical world example would be to place two parallel
mirrors facing each other. Any object in between them would be reflected recursively. In
Python, we know that a function can call other functions. It is even possible for the function
to call itself. These types of construct are termed as recursive functions.
def factorial(x):
if x == 1:
return 1
else:
return (x * factorial(x-1))
num =int(input("Enter the value : "))
print("The factorial of", num, "is :", factorial(num))
Output
Enter value 3
The factorial of 3 is : 6
***** SUCCESS!*****
AVCCE/MCA/R-21/I-SEM/NS Page 30