Professional Documents
Culture Documents
Introduction:
General-purpose Object Oriented Programming language.
High-level language
Developed in late 1980 by Guido van Rossum at National Research Institute for
Mathematics and Computer Science in the Netherlands. It is derived from programming
languages such as ABC, Modula 3, small talk, Algol- 68.
It is Open Source Scripting language.
It is Case-sensitive language (Difference between uppercase and lowercase letters).
One of the official languages at Google.
Characteristics of Python:
Interpreted: Python source code is compiled to byte code as a .pyc file, and this byte
code can be interpreted by the interpreter.
Interactive
Object Oriented Programming Language
Easy & Simple
Portable
Scalable: Provides improved structure for supporting large programs.
Integrated
Expressive Language
There are two modes to use the python interpreter:
Interactive Mode: Without passing python script file to the interpreter, directly
execute code to Python (Command line).
Example:
>>>6+3
usually three greater-than signs (>>>); for continuation lines it prompts with the secondary prompt, by
default three dots (...).
python interpreter uses to indicate that it is ready. The interactive mode is better when a programmer
deals with small pieces of code.
Script Mode : In this mode source code is stored in a file with the .py extension and use the interpreter
to execute the contents of the file. To execute the script by the interpreter, you have to tell the interpreter
the name of the file.
python program execution
Python uses both compiler and interpreter to generate the native code
Interpreter is simply a software which executes the source code line by line.
Compiler is a software which executes the source code as whole
the source code is translated to byte code , which is then run by the pvm(python virtual
machine) to form machine code
In python code is first complied that is compiler compiles your source code (the
statements in your file) into a format known as byte code.
Byte code is a:
•lower level,
•platform independent,
•efficient and Intermediate
It is into byte code and 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.
So source code gets converted to byte code, it is fed into PVM (Python Virtual Machine).
to execute the python program we use the following syntax
but even at the Python interactive prompt, your Python is compiled to bytecode, and then the
bytecode is executed.
Variable
Variable Names
Named location that refers to a value and whose value can be used and processed during program execution.
Variables in python do not have fixed locations. The location they refer to changes every time their values change.
A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).
Rules for Python variables:
1. a = b = c = 10
2. a, b, c = 1, 21.2, “sjc”
print(a)
Print(b)
Print(c)
3. a= “Autonomous” Print(a) o/p Autonomous
4. a= 10
5. b= “sjc”
6. c=10.5
Print (a + b) o/p unsupported operand type for +: ‘int’ and ‘str”
Print ( a + c) o/p 20.2
If you want to know the type of variable, you can use type( ) function
Syntax:
type (variable-name)
Example:
x=6
type(x)
The result will be:
<class ‘int’>
If you want to know the memory address or location of the object, you can use id( )
function.
Example:
>>>id(5)
1561184448
You can delete single or multiple variables by using del statement. Example:
del x
del y, z
Python is a highly object oriented language. In fact, virtually every item of data in a Python program is an
object of a specific type or class.
N=300
When presented with the statement print(300), the interpreter does the following:
•Creates an integer object
•Gives it the value 300
•Displays it to the console
You can see that an integer object is created using the built-in type() function:
type (n) o/p (300) <class 'int’>
n = "foo" Now Python creates a string object with the value "foo" and makes n reference
Orphaned Object
There is no longer any reference to the integer object 300. It is orphaned, and there is no way to access it.
Object Identity
Every object that is created is given a number that uniquely identifies . The identity of an object is an integer, which is
guaranteed to be unique and constant for this object during its lifetime its identifying number becomes available and may be
used again
w = 1 # int
y = 2.8 # float
z = 1j # complex
x = 3+5j
y = 2+4j
z=x+y
print(z)
5+9j
z.real
5.0
z.imag
9.0
String: Sequence of characters represented in the quotation marks.
Python allows for either pairs of single or double quotes. Example: 'hello' is the same as "hello" .
Python does not have a character data type, a single character is simply a string with a length of 1.
The python string store Unicode characters.
Each character in a string has its own index.
String is immutable data type means it can never change its value in place.
For example
Arithmetic Operators
<= 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 Operators
or x or y True if either x or y is True
False otherwise
a /= 10 is equivalent to a = a / 10
Bitwise operator
| 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^b bitwise XOR (exclusive OR) Each bit position in the result is the logical XOR of the
bits in the corresponding position of the operands. (1 if
the bits in the operands are different, 0 if they are the
same.)
Output:
False
True
Membership operators- in and not in are the membership operators; used to test
whether a value or variable is in a sequence.
in True if value is found in the sequence
not in True if value is not found in the sequence
Example:
x = 'Digital India'
y = ‘3hjhgb7’
print('D' in x)
print('digital' not in x)
print('Digital' not in x)
print(3 in y)
print('b' in y)
True
True
False
True
False
Boolean literals
A Boolean literal can have any of the two values: True or False.
x = (1 == True) y = (1 == False) a = True + 4 b = False + 10
print("x is", x)
print("y is", y)
print("a:", a)
print("b:", b)
o/p
x is True
y is False
a: 5
b: 10
dec = 344
print("The decimal value of", dec, "is:")
print(bin(dec), "in binary.")
print(oct(dec), "in octal.")
print(hex(dec), "in hexadecimal.")
o/p
Type conversion
int(2.3) o/p 2
int(-2.8) -2
float(5) 5.0
complex('3+5j’) (3+5j)
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
When converting from float to integer, the number gets truncated (integer that is closer to zero).
i Reading a number from a user:
x= int (input(“Enter an integer number”))
The return type of eval() function is automatically considered based on what argument is passed to the eval() function.
If the argument represents If you pass an argument as int, float, boolean, it will return the corresponding datatype only.
The eval() function is used as an alternate for typecasting.
1. ceil() :- This function returns the smallest integral value greater than the number. If
number is already integer, same number is returned.
2. floor() :- This function returns the greatest integral value smaller than the number. If
number is already integer, same number is returned.
3. fabs() :- This function returns the absolute value of the number.
4. factorial() :- This function returns the factorial of the number
5. pi :- This is an inbuilt constant that outputs the value of pi(3.141592).
6.exp(a) :- This function returns the value of e raised to the power a (e**a) .
7.log(a, b) :- This function returns the logarithmic value of a with base b
8.pow(a, b) :- This function is used to compute value of a raised to the power b (a**b).
9. sqrt() :- This function returns the square root of the number.
10. sin() :- This function returns the sine of value passed as argument.
11. cos() :- This function returns the cosine of value passed as argument.
12. trunc() : Returns the truncated integer value of x
Strings
Strings are defined either with a single quote or a double quotes.
The difference between the two is that using double quotes makes it easy to include apostrophes whereas these would terminate the string if using single quotes
s = 'SJC.’
s*4 O/P 'SJCSJCSJCSJC.' The multiplier operand must be an integer. TE: it can be zero, negative or positive
4 * s O/P ‘ SJCSJCSJCSJC.’
S*-4 o/p null for negative and zero
3. in Operator
Python also provides a membership operator that can be used with strings.
The in operator returns True if the first operand is contained within the second, and False otherwise:
s = 'foo s in 'That\'s food for you .' True
s in 'That\'s good for you.' False
String Indexing
String indexing in Python is zero-based:
The first character in the string has index 0, the next has index 1, and so on.
The index of the last character will be the length of the string minus one.
S= ‘foobar’
s[len(s)-1] 'r’
s[-2] ‘a’
len(s) 6
s[- len(s)] 'f'
String Slicing
Note :If the first index in a slice is greater than or equal to the second index, Python returns
an empty string
s = 'foobar’
s[2:5] 'oba’
s[:4] 'foob’
s[0:4] 'foob’
s[2:] 'obar’
s[2:len(s)] 'obar’
s[:4] + s[4:] 'foobar’
s[:4] + s[4:] == s True
s = 'foobar’
s[-5:-2] 'oob'
t = s[:]
id(s) 59598496 Literally. It’s not a copy, it’s a reference to the original string
id(t) 59598496
s is t True
starting with the second character (index 1) and ending with the last character and again the stride value 2 causes every other
character to be skipped
n = 20 m=25
prod = n * m
Print ('The product of', n, 'and', m, 'is', prod) The product of 20 and 25 is 500
String Built in function
1. s.capitalize() returns a copy of s with the first character converted to uppercase and all other characters converted to
lowercase
2. s.swapcase() returns a copy of s with uppercase alphabetic characters converted to lowercase and vice versa
3. s.title() returns a copy of s in which the first letter of each word is converted to uppercase and remaining letters are
lowercase
4. s.upper() returns a copy of s with all alphabetic characters converted to uppercase
5. s.count(<sub>[, <start>[, <end>]]) Counts occurrences of a substring in the target string
6. s.endswith(<suffix>) returns True if s ends with the specified <suffix> and False otherwise
7. use .find() to see if a Python string contains a particular substring. s.find(<sub>) returns the lowest index in s where
substring <sub> is found:
8. use the .startswith() method returns True if s starts with the specified <suffix> and False otherwise
9. s.isalnum() returns True if s is nonempty and all its characters are alphanumeric (either a letter or a number),
and False otherwise
10. s.lower() returns a copy of s with all alphabetic characters converted to lowercase
11. s.isalpha() returns True if s is nonempty and all its characters are alphabetic, and False otherwise
12. s.isdigit() returns True if s is nonempty and all its characters are numeric digits, and False otherwise
13. s.isidentifier() returns True if s is a valid Python identifier according to the language definition, and False otherwise
Python Collections (Arrays)
There are four collection data types in the Python programming language:
•List is a collection which is ordered and changeable. Allows duplicate members.
•Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
•Set is a collection which is unordered and unindexed. No duplicate members.
•Dictionary is a collection which is unordered, changeable and indexed. No duplicate member
List : Items separated by commas are enclosed within brackets [ ] . The elements of a list can be same type , variable
type or complex type
Negative indexing , positive indexing , Range of Indexes is possible
A list with a single object is sometimes referred to as a singleton list:
a = [5,10,15,20,25,30,35,40]
a = [21.42, 'spam', 3, 4, 'egg', False, 3.14159]
Indexing
Note: index and slice tuples using square brackets, just as for strings and lists.
Immutable
deleting tuples
del t[2] error
del t
t = ('foo', 'bar', 'baz', 'qux', 'quux', 'corge’)
slicing
# elements 2nd to 4th print(t[1:4]) # Output: ('bar', 'baz', 'gux')
# elements beginning to 2nd print(t[:-4]) 'foo', 'bar’
# elements 4th to end print(t[3:]) 'qux', 'quux', 'corge'
# elements beginning to end print(t[:])
2. Not in operation
print('g' not in my_tuple) # Output: True
This immutability could be helpful if you're writing a program and want to store data that shouldn't be changed. Possible
examples include:
• credit card information
• birthdate
• birth name
Sets
A set is an unordered collection of items.
a = {}
print(type(a)) # Output: <class 'dict’>
a = set()
print(type(a)) # Output: <class 'set'>
set operations
A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8}
A.union(B)
print(A | B) Output: {1, 2, 3, 4, 5, 6, 7, 8}
A.intersection(B)
print(A & B) Output: {4, 5}
A.difference(B)
print(A - B) output:{1,2,3}
discard() Removes an element from the set if it is a member. (Do nothing if the element
is not in set)
Dictionary
Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data
Types that hold only single value as an element, Dictionary holds key:value pair. Key value is provided in the dictionary to
make it more optimized.
Created by using {} separated by commas,
Value :- any datatype ,it can be repeated, Values can be a list or list within a list, numbers, etc.
Keys:- immutable type and unique, Keys will be a single element
More than one entry per key is not allowed ( no duplicate key is allowed)
Values in a dictionary can be of any datatype and can be duplicated, whereas keys can’t be repeated and must
be immutable.
Dictionary keys are case sensitive- Same key name but with the different case are treated as different keys in Python
dictionaries.
Eg :- dict={1:`apple`, 2: `ball`} key of integer type
dict ={ `name`: `apple`, 1 : [2,4,5]} key of mixed type
Print (dict[name])
Print( dict.get(1))
Print(dict)
dict[2]=‘cat’ update the dictionary
Dict[2]=`welcome’ adding element with key 2 and value welcome
METHODS DESCRIPTION
clear() The clear() method removes all items from the dictionary.
print(a[0][2]) 3
a[0][1] = 7
print(a) [[1, 7, 3], [4, 5, 6]]
Conditional statement
Syntax of if
if testexpression:
statement
num = 3
if num > 0:
print(num, "is a positive number.")
print("This is always printed.")
Syntax of if...else
if test expression:
statement
else:
statement
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")
Looping statement
Syntax of for Loop
for val in sequence:
statement
eg:
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
sum = 0
for val in numbers:
sum = sum+val
print("The sum is", sum)
range() function
range(n): generates a set of whole numbers starting from 0 to (n-1).
eg: range(8) = [0, 1, 2, 3, 4, 5, 6, 7]
range(start, stop, step_size) generates a set of whole number starting and ending with
increment or decrement
range(1, 10, 2) is equivalent to [1, 3, 5, 7, 9]
sum = 0
for val in range(1,10,2):
sum = sum+val
print("The sum is", sum)
Syntax of if...elif...else
if test expression:
statement
elif test expression:
statement
else:
statement
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
Nested if
num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("P ositive number")
else:
print("Negative number")
For loop with else block
for with optional ‘else’ block associated with the loop. The ‘else’ block executes only when the loop has completed all the iterations.
Eg:
for val in range(5):
print(val)
else:
print("The loop has completed execution")
while loop
while condition:
statement
eg:
while num < 10:
print(num)
num = num + 3
while loop with else block
while with optional ‘else’ block associated with while loop. The ‘else’ block is optional. It executes only after the loop finished execution
num = 10
while num > 6:
print(num)
num = num-1
else:
print("loop is finished")
break statement
for num in [10, 99,16, 90, 88, 19]:
print(num)
if(num==88):
print("The number 88 is found")
print("Terminating the loop")
break
Continue Statement
pass statement
for num in [20, 11, 9, 66, 4, 89, 44]:
if num%2 == 0:
pass
else:
print(num) o/p 11,9, 89
we want to declare a function in our code but we want to implement that function in future
Function
function is a block of code that performs a specific task.
1. Code re-usability:
2. Improves Readability: By using functions for frequent tasks you make your code structured and readable..
3. Avoid redundancy: When you no longer repeat the same lines of code throughout the code and use functions in places of those, you actually avoiding the redundancy
Function declaration:
def function_name(function_parameters):
function_body
return
Types of functions
1. Built-in functions:
2. User defined functions: The functions which we create in our code are user-defined functions. The add() function that we have created in above examples is a user-defined function.
Types of user defined function in Python
There are three types of Python function arguments using which we can call a function.
1.Default Arguments
Sometimes we may want to use parameters in a function that takes default values in case the user doesn’t want to
provide a value for them.
For this, we can use default arguments which assumes a default value if a value is not supplied as an argument while
calling the function. In parameters list, we can give default values to one or more parameters.
An assignment operator ‘=’ is used to give a default value to an argument.
if a value is provide it will overwrite the default value any number of argument in a function can have a default value
Keyword Arguments
In function, the values passed through arguments are assigned to parameters in order, by their position.
With Keyword arguments,
we can use the name of the parameter irrespective of its position while calling the function to supply the values. All the
keyword arguments must match one of the arguments accepted by the function.
Sum1=add(num2=300,num1=100)
Variable-length Arguments
Sometimes you may need more arguments to process function then you mentioned in the definition. If we don’t
know in advance about the arguments needed in function, we can use variable-length arguments also called
arbitrary arguments.
For this an asterisk (*) is placed before a parameter in function definition which can hold non-keyworded
variable-length arguments and if we use two asterisks (**) before a variable like **var, then all the positional
arguments from that point till the end are collected as a dictionary called ‘var’.
Arbitary argument
def add( *num):
for I in num:
print(I)
add(1,3,4)
add(4,5,6,7)
• Variables or parameters defined inside a function are called local variables as their scope is limited to the function
only. On the contrary, Global variables are defined outside of the function.
• Local variables can’t be used outside the function whereas a global variable can be used throughout the program
anywhere as per requirement.
• The lifetime of a local variable ends with the termination or the execution of a function, whereas the lifetime of a
global variable ends with the termination of the entire program.
• The variable defined inside a function can also be made global by using the global statement.
def function_name(args):
.............
global x #declaring global variable inside a function
.............
T
Global and local variables
x = "global"
def foo():
print("x inside:", x)
foo()
print("x outside:", x)
o/p
x inside: global
x outside: global
x= "global"
def foo():
x=x*2
print(x)
foo()
//the output shows an error because Python treats x as a local variable and x is also not defined inside foo().
x= "global"
def foo():
global x
x=x*2
print(x)
foo()
def foo():
y = "local"
foo()
print(y)
x= "global "
def foo():
global x
y = "local“
x=x*2
print(x)
print(y)
foo()
local x: 10
global x: 5
Call/Pass By Value:
In pass-by-value, the function receives a copy of the argument objects passed to it by the caller, stored in a new location
in memory.
Call By Reference:
In pass-by-reference, the function receives reference to the argument objects passed to it by the caller, both pointing to
the same memory location
In Python Neither of these two concepts are applicable, rather the values are sent to functions by means of object
reference.
Pass-by-object-reference:
In Python, (almost) everything is an object
if object is immutable(not modifiable) than the modified value is not available outside the function.
if object is mutable (modifiable) than modified value is available outside the function.
Mutable objects:
list, dict, set
Immutable objects:
int, float, complex, string, tuple
call by value
string = “ sjc"
def test(string):
string = “Sjc Autonomous"
print("Inside Function:", string)
test(string)
print("Outside Function:", string)
call by reference
def add_more(list):
list.append(50)
print("Inside Function", list)
# Driver's code
mylist = [10,20,30,40]
add_more(mylist)
print("Outside Function:", mylist)
A function is said to be a recursive if it calls itself.
For example, lets consider a function factorial() and in the body of factorial() there is a call to the factorial().
def factorial(num):
if num == 1:
return 1
else:
return (num * factorial(num - 1))
num = 5
print("Factorial of", num, "is: ", factorial(num))
Note: factorial(1) is a base case for which we already know the value of factorial. The base case is defined in
the body of function with this code:
Format
name = "John“
print("%s Hello, !" % name)
age = 10
print("%s is %d years old." % (name, age))