Core Python Programming
Introduction to python
Python was developed by Guido Van Rossum in 1991.
Python name is on the basis of famous TV show, Monty python’s Flying Circus.
Python is open source.
There are many programming languages like procedure oriented programming and object oriented programming.
C is called procedure oriented programming language, where the program is divided in different functions. The program is completed through the functions.
The another popular programming language is object oriented programming language. The object oriented programming languages are c++ and java.
From the above programming languages, python is combination of both languages. That is procedural language and object oriented language.
Python is programming language that provides security of object oriented programming and syntax is as simple as C language.
Features of python
There are many reasons for the popularity of python. The important features of python are as follows:
Simple:
It is simple programming language because its syntax is simple as English like language. it is high level language so programming is easy.
Easy to learn:
It uses very few keywords. Its program use very simple structure. Most of the programming languages written in C is also available in python programming language so it is easy to migrate from C language to python programming language.
Open source:
There is need to pay for the python software. It can be freely download from www.python.org. it can be read, modified and can be used by the programmer.
High level language:
Python use English like language and it is high level language.
Dynamically typed:
In python declaration Is not required. The assignment statement binds a name to an object and the object can be of any type. Unlike C and java language in python variable declaration is not required.
Platform independent:
When a program is compiled using a python compiler, it generates byte code. The byte code is not dependent on hardware or OS. Python Virtual Machine is used to run these byte code instructions on any computer system.
Portable
Python provides portability because of PVM. It provides same output on all machines. Python also provides some system dependent modules, which are specific to operating system.
Procedure and object oriented
python is procedure oriented as well as object oriented programming language
Important features of python
Python is having many important features. The features are listed below:
Interpreted
A python source code is compiled using python compiler. Python compiler code is then executed by PVM. The PVM converts bytecode into machine code. Python Virtual Machine interpret the code so it is called interpreted language.
Extensible
The program written in other languages can be extended in python program. The program written in C or C++ can be extended in python program with use of Cpython. The program written in Java can can be integrated with python with use of jython and can be run under the controllo f JVM. The Ironpython provides support to .Net and run under the control of CLR- Common Language Runtime.
So python supports different code and it is called extensible.
Embeddable
The python program cab be inserted into C and C++ program. In python many applications are available that allows integration with other programming languages.
Huge Library
Python provides huge library support for different operating system. Programmers can develop programs very easily through different modules available in python.
Scripting language
Python is identified as scripting language because it interpreted and support web based applications.
Database connectivity
Python provides support for database connectivity through different modules. It supports almost all databases like MYSql, Oracle and Sybase.
Scalable
Python is called scalable language because python program written on one platform can support any other platform because of PVM- Python Virtual Machine.
Batteries included
Python supports huge library and in that library, there several programs that are readily available to perform small task. So, to perform small task always module should not be included, they are already available it is called ‘batteries included’. The most common batteries- packages are like,
Argparse – that is useful to pass an arguments.
Cherrypy – it supports object orientd HTTP framework.
Pandas – it supports data analysis and statastics.
Matplotlib – it supports electronic ciruits and 2D graphs.
Numpy – it support arrays of single dimensional and multi dimension.
https://www.pythonanywhere.com/batteries_included/ link provides the list of batteries.
Execution of python Program
The python program is executed in above manner.
Suppose we want to create python program named first then the python source file is first.py.
This source file is compiled and after compilation byte code is generated. This byte code is run using PVM- Python virtual machine that interprets the code and output is generated.
The interpreter that is found inside the PVM runs the python program slowly. To overcome the problem in some flavours of compiler is added to the PVM. This compiler is called JIT (Just in Time ) compiler that improves the speed of execution of python program.
The JIT is not available in all types of python.
The steps to execute python source file the command on IDLE is :
python first.py
Through above code output is generated but it will not display the .pyc file because all the process (generation of byte code, interpretation under PVM , machine code generation) is performed only in memory and final out put only generated.
But if we want to generate the byte file we can use py_compile module, and byte code can be generated.
The command is
python –m py_compile first.py
Where the –m stands for module and we have used py_compile module that create directory named
_pycache_ . within the directory the .pyc file is generated.
This .pyc file can be directly executed with use of python and output is generated.
Viewing of Byte Code
When we execute python program it directly provide us output but if we want to see the byte code instructions that were created internally by the python compiler before execution, that is possible though dis module. The command is as follows:
python –m dis first.py
It will produce the output.
The dis stands for disassembler that displays the byte code in the human understandable format.
Python virtual machine
Python virtual machine is machine over the machine.
As per it name suggest it created virtual machine to execute the bytecode.
It interprets the bytecode and generates machine code.
The python virtual machine makes python platform independent.
Flavours of python
Python use different types of compiler, which are useful to integrate various programming languages into python. The different types of compilers are:
CPython: This is the standard Python compiler implemented in C language. in this type of python the byte code is created with use of C language. The PVM is written in C language. This can be downloaded from https://www.python.org/downloads
Jython : This is design to run on java platform. Jython is earlier known as JPython. Jython converts python program to java byte code and it is executed by java virtual machine. Jython have libraries that supports python and java both. Jython supports integration of java program with python program. The jython can be downloaded from http//www.jython.org
Ironpython : This is another implementation of python. It support .net framework. This is written in c# language. The python program when compiled it generates intermediate language (IL) and runs under the control of CLR to produce the output. So iron python support .net. The iron python can be downloaded from http://ironpython.net
Pypy: this is python implementation using python language. pypy is written in RPython which was created in python language. rpython is suitable for creating language interpreter. In the PVM of pypy JIT (just in time compiler)
RubyPython: This flavour of python provides communication of ruby and python.
Pythonxy: This python provides support for scientific and engineering applications as it is having plenty of packages for scientific and engineering tasks.
Memory management in python
In python memory allocation is done at run time, automatically. The memory is allocated when object is created and memory is deallocated when object is destroyed. So the allocation and deallocation taken care by the PVM.
In Python everything is identified as an object. String, List, function all is treat as an object in python. In python modules are also treat as an object.
Memory for all the object is allocated from the memory area called heap. The heap area is always used to allocate memory dynamically. The memory from the heap area, always allocated run time.
The size of heap area is depends on RAM.
The RAM is allocated on the base of operating system. The raw memory allocator taking care for the memory allocation for different objects from the OS memory.
On the top of raw memory allocator there is object specific memory allocator, who is taking care of memory allocation for different objects.
Garbage collection in python
Garbage collection is a module that is used to delete the object from the memory that are no longer used. The name of garbage collector is gc.
There are generally two methods in garbage collection.
Reference Counting
In reference counting the garbage collector counting how many times the object is referenced. When the object is referenced once, the reference counting is 1. When the object is referred twice the reference counting is two. When the object is not referred the reference count of the object is 0. Means that object is no more required for processing and the object will be removed from the memory and memory will be free.
In reference counting the garbage collector may face problem due to reference cycle.
Reference cycle means the object 1 refers object2 and object2 refers object3 and object3 refers object1. Here object1, object2 and object3 are no longer used by the program then also the reference count of all this three objects is 1 always so the garbage collector can not remove the objects from the memory. To solve this problem python use the algorithm for detecting reference cycles and with the help of this algorithm it removes the objects from the reference cycle.
Garbage collection
The garbage collector classify the objects in to three generations.
Generation 0: The newly created objects are considered as generation 0 and first time when collector identifies such objects it will not remove it from the memory because it may be used by the program later on, and it puts it to generation 1.
Generation 1: when garbage collector wish to delete the object from the memory second time and unable to remove from the memory because it is in use then it puts it to next generation.
Generally, garbage collector delete the objects from the younger generation rather than the old.
Garbage collector can run automatically or manually.
If there are reference cycles then garbage collector should be manual otherwise automatic garbage collector can be used.
Automatic garbage collector runs automatically. Python schedule garbage collector on the basis of threshold value. If the allocated objects – deallocated objects value is higher than the threshold value the garbage collector will be invoked automatically.
We can read the threshold value with use of get_threshold().
If program creates many number of objects then the automatic garbage collection will not invoked but program may throw an exception.
The automatic garbage collector work on two basis, event based and time based
Comparison of C and Python
C is procedural language
The syntax of python is as simple as C but it support all the features of Object oriented programming language.
In C variable declaration is compulsory.
In python, data type declaration is not compulsory.
In c dynamic memory allocation is possible through malloc, calloc function.
In python memory allocation is performed dynamically.
Pointer concept is available in C
There is no concept of pointer in python.
Exception handling is not available in C.
Exception handling is available in C.
C supports while, for and do..while loop.
Python supports for loop and while loop.
In C, the variables in for loop does not increase automatically.
In python, the variables in for loop increase automatically.
C supports single and multi dimensional array.
Python supports single dimensional array, and to support multi dimensional numpy module is used.
In C, array index can be positive only.
In python, array index can be positive or negative.
C does not have concept of garbage collection.
Python have concept of garbage collection.
Indentation is not compulsory in C.
Indentation is compulsory in python.
Statement is terminated with semicolon.
Statement is terminated with new line.
Comparison of java and python
In java indentation is not compulsory.
In python indentation is compulsory.
In java variable declaration is compulsory.
In python variable declaration is not compulsory.
In java every statement terminate with semicolon
In python every statement terminate with new line character.
Java supports for, while, do while and for each loop.
Python supports for loop and while loop, the for loop of python is same as for each loop of java that supports auto increment.
Java supports single dimensional and multi dimensional array.
Python support only single dimensional array, multi dimensional array supported by numpy module.
In java, Negative array index position is not possible.
In python, negative array index position is possible.
Java supports switch statement.
Python does not supports switch statement.
JVM java virtual machine manage is used in java.
PVM python virtual machine is used in java.
Comments in python
Single line comment (#)
Multi line comment( “ “ “ “ “ “)
Variables in python
Variables are place holder in python.
We should not declare variable.
When we assign certain value at that time variables are created.
Variable name follows certain rules in python.
Built in data types in python
Python support different built in data types. The data types are:
None type
Numeric type
Sequences
Sets
Mapping
None type
#None type
a=None
if(a):
print("None means true")
else:
print("None means false")
None
None means an object that does not contain any value.
None is equal to null in java
It is default value as function argument.
When calling a function if no value is passed then the default value will be taken as None.
Numeric type
Int
Float
Complex datatype a+bj
C1=1.2+2.3j
C2=3.0-0.5j
C3=c1+c2
Print(c3)
Explicit conversion of data type
To converting one data type to another type is called explicit conversion of data type.
Different examples of explicit conversion are:
n1=0o1234
n2=0b10001
n3=0x12A
print(int(n1))
print(int(n2))
print(int(n3))
The other examples are:
x=12.23
print(int(x))
y=5
print(float(y)
p=20
print(complex(p))
Bool data type
True means 1, false means 0 internally
A=10>5
print(a)
Ans is true
Sequences
Sequence means group of elements or items
Types of sequences:
Str
Bytes
Bytearray
List
Tuple
range
str data type
str represent string datatype
It is represented by group of characters.
It is enclosed within single quotes or double quotes.
It can use even triple double quotes or single quotes. It is useful to embed a string inside another string.
Slice operator is used in string with [ ], *is used to repeat the string
#string sequence
str="this is demo"
print(str)
str1=""" This is 'python' demo"""
print(str1)
str2=''' This is "python" demo'''
print(str2)
print(str[0])
print(str[5:10])
print(str[5:])
print(str[-2])
print(str[-2:])
print(str[:-2])
print(str2 * 2)
output:
this is demo
This is 'python' demo
This is "python" demo
t
is de
is demo
m
mo
this is de
This is "python" demo This is "python" demo
bytes
The byte data type represents group of bytes.
A byte number is any positive number from 0 to 255.
It can not store negative numbers.
bytearray data type
The bytearray datatype is similar to bytes datatype.
The difference between bytearray and byte is bytes type array can not be modified.
But the bytearray type array can be modified.
Example:
#bytes data type
#this is list of bytes
ele=[10,20,30]
x=bytes(ele)
print(x)
#[0]=55
print("Complete byte")
for i in x: print(i)
#byte array
y=bytearray(ele)
print(y[0])
print("Complete byte")
for i in y: print(i)
print("Update")
y[0]=99
print(y[0])
print("Complete byte")
for i in y: print(i)
output:
[10, 20, 30]
Complete byte
[
1
0
,
2
0
,
3
0
]
10
Complete byte
10
20
30
Update
99
Complete byte
99
20
30
list
List is similar to arrays in c and java.
The difference between list and array is, array can store similar type of data and list can store different types of data.
List can grow dynamically in memory but the size of array is fixed.
List represented using []
List can be updated
Example:
#list and tuple
list=[10,-20,2.5,'abc',"def"]
print(list)
print(list[0])
print(list[1:4])
print(list[-1])
print(list*2)
list.append(20)
print(list)
#tuple
print("tuple")
list=(10,-20,2.5,'abc',"def")
print(list)
print(list[0])
print(list[1:4])
print(list[-1])
print(list*2)
#list.append(20)
print(list)
output:
[10, -20, 2.5, 'abc', 'def']
10
[-20, 2.5, 'abc']
def
[10, -20, 2.5, 'abc', 'def', 10, -20, 2.5, 'abc', 'def']
[10, -20, 2.5, 'abc', 'def', 20]
tuple
(10, -20, 2.5, 'abc', 'def')
10
(-20, 2.5, 'abc')
def
(10, -20, 2.5, 'abc', 'def', 10, -20, 2.5, 'abc', 'def')
(10, -20, 2.5, 'abc', 'def')
tuple
A tuple is similar to a list.
A tuple contains a group of elements which can be different types.
The elements in tuple are separated by commas and enclosed in parantheses()
The tuple can not be modified.
Range
The range datatype represent a sequence of numbers.
The numbers in the range are not modifiable.
Range is used for repeating a for loop for a specific number of times
Example of Range
#range
r= range(5)
for i in r: print(i)
#range with starting and ending number and step value
print("another range")
r= range(10,20,2)
for i in r: print(i)
print("Create list with range")
#create list with range
lst=list(range(5))
print(lst)
output:
0
1
2
3
4
another range
10
12
14
16
18
Create list with range
[0, 1, 2, 3, 4]
Sets and mapping
Set
A set is unordered collection of elements much like a set in mathematics
The order of the elements is not maintained in the set.
Means the elements in the set may not appear in the same order as they enter in the set.
Set does not accept duplicate elements.
There are two sub types in the set.
Set datatype
Frozenset data type
Set example
#sets and frozenset
s={10,20,30,10}
print(s)
s.update([40])
print(s)
ch=set("hello")
print(ch)
lst=[1,2,5,3,4,5]
s=set(lst)
print(s)
s.update([50])
print(s)
s.remove(50)
print(s)
#frozenset
s={1,2,3,4,1}
print(s)
fs=frozenset(s)
print(fs)
fs=frozenset("abcd")
print(fs)
output:
set([10, 20, 30])
set([40, 10, 20, 30])
set(['h', 'e', 'l', 'o'])
set([1, 2, 3, 4, 5])
set([1, 2, 3, 4, 5, 50])
set([1, 2, 3, 4, 5])
set([1, 2, 3, 4])
frozenset([1, 2, 3, 4])
frozenset(['a', 'c', 'b', 'd'])
Frozenset datatype
The frozenset datatype is same as the set datatype.
The main difference is that the element in the set datatype can be modified, but the elements of frozenset can not be modified.
We can create frozenset from the set
Mapping types
A map represents a group of elements in the from of key and value pairs.
So that with use of key the value can be retrieved.
The dict datatype is an example of map.
The dict represents dictionary that contains pair of elements.
The first element represent key and the next one is value
The key and its value is separated by :
Every pair should be separated by ,
Empty dictionary can be created by d={ }
#mapping types
map={1:"abc",2:"def",3:"ghi"}
print(map)
print("1 key value")
print(map[1])
print("Only key values")
print(map.keys())
print("Only values")
print(map.values())
map[1]="pqr"
print(map)
del map[3]
print(map)
map[3]="ijk"
print(map)
output:
{1: 'abc', 2: 'def', 3: 'ghi'}
1 key value
abc
Only key values
[1, 2, 3]
Only values
['abc', 'def', 'ghi']
{1: 'pqr', 2: 'def', 3: 'ghi'}
{1: 'pqr', 2: 'def'}
{1: 'pqr', 2: 'def', 3: 'ijk'}
Determining the data type of variable
The type function is used to know the data type.
Example:
#determine the datatype of variable
a=5
print(type(a))
b=5.5
print(type(b))
c="def"
print(type(c))
d='ghi'
print(type(d))
e=[1,2,3]
print(type(e))
f=(4,5,6)
print(type(f))
g={7,8,9}
print(type(g))
Output:
<type 'int'>
<type 'float'>
<type 'str'>
<type 'str'>
<type 'list'>
<type 'tuple'>
<type 'set'>
Identifiers and Reserved word
The name that is given to variable, class or function is called identifier.
The rules for the identifier is mentioned below:
identifier includes letters, numbers and the underscore.
They should always start with non numeric character.
Only one special symbol is allowed that is underscore only.
Capital letter and small letter both are different.
Reserve words can not be used as name of variable.
Reserve words
Reserve words are also referred as keywords.
and del from not while
as elif global or with
assert else if pass yield
break except import print
class exec in raise
continue finally is return
def for lambda try
Naming conventions in python
Naming conventions means, how to write name of the program.
The rules about how to write name of variable, function, class, package, module etc. are called naming conventions.
Package: it name should be written in lower case only.
When multiple words are used name should ne separated using underscore.( _ ).
Modules: modules name should be written in all lower case letters. Multiple word should be separated with underscore.
Classes: Class name always starts with capital letter. This rule is for programmer.
Global variable or Module level variable: in global variable names should be all lower case letters. When multiple words are used, they should separated using underscore.( _ )
Instance variable: all letters are in small letters. Non public instance variable name should begin with _.
Function: function name should use small letters. When multiple words are used, they should separate with _ .
Methods: method name should use small letters. When multiple words are used, they should separate with _ .
Method arguments: in case of instance methods , the first argument name should be self. In case of class method the first argument name should be cls.
Constants: constants names should be all in capital letters. Multiple words are separated with _.
Non accessible entities: variable, functions and method are not accessible outside. Such entities should use two _ before and two _ after.
eg: _ _ init_ _
Operators
Python supports
Arithmetic
Assignment
Unary minus
Relational
Boolean
Logical
Bitwise operators
Example1:
#arithmetic operator
a=15
b=4
add=a+b
sub=a-b
mul=a*b
div=a/b
idiv=a//b
exp=a**b
print("addition %d "% add)
print("subtraction %d "% sub)
print("multiplication %d "% mul)
print("division %f "% div)
print("Idivision %d "% idiv)
print("Exponent %d "% exp)
Output:
addition 19
subtraction 11
multiplication 60
division 3.000000
Idivision 3
Exponent 50625
Example2:
#assignment operator
a=15
b=4
#a=a+b
a+=b
print("addition assignment %d "% a)
Output:
addition assignment 19
Example3:
#unary - operator
a=15
print(-a)
b= -10
print(b)
b=-b
print(b)
Output:
-15
-10
10
Example4:
#Relational operator
#> < >= <= == !=
a=15; b=16;c=17
if(a>b):
print("a is max %d" %a)
else:
print("b is max %d"%b)
#relational operators can be chained
if(c>a>b):
print("c is max %d" %c)
if(b<c>a):
print("c is max %d"%c)
Output:
b is max 16
c is max 17
Example5:
#logical operator
#and, or, not
a=15; b=16;c=17
if(c>b and c>a):
print("c is max %d" %c)
Output:
c is max 17
Membership operator
The membership operator is supported by python.
It suggest that, the element is member or not of the sequence.
The sequence can be strings, lists, tuples or dictionaries.
There are two membership operators:
in
not in
The in operator:
This operator return true if the element is found in the specified sequence and returns false if the element is not found.
The not in operator:
This operator returns true if the element is not found in the sequence and false if found in the sequence.
It works in reverse then ‘in’ operator.
Example:
#membership operator
#in, not in
list =["abc","def","ghi"]
for name in list:
print(name)
add={"ahmedabad":380000, "surat":330000, "baroda":320000}
for city in add:
print(city,add[city])
if("abc" in list):
print("abc is present in list")
if("xyz" in list):
print("xyz is present in list")
else:
print("xyz is not present in list")
if("xyz" not in list):
print("xyz is not present in list")
Output:
abc
def
ghi
('surat', 330000)
('baroda', 320000)
('ahmedabad', 380000)
abc is present in list
xyz is not present in list
xyz is not present in list
Identity operator
This operator compare the memory location of two objects.
With use if this operator it can be identified that, the objects are same or not.
id() function is used to compare two objects.
There are two identity operators
Is
Is not
The is operator is useful to compare whether two objects are same or not. It is internally comparing identity numbers of the objects and if it is same it returns true else returns false.
The isnot operator:
It is reverse than is operator.
Example:
#identity operator
#is,is not
a=25
b=25
if(a is b):
print("a and b have same identity")
else:
print("a and b do not have same identity")
print(id(a))
print(id(b))
l1=[1,2,3,4]
l2=[1,2,3,4]
if(l1 is l2):
print("List1 and List2 are same")
else:
print("List1 and List2 are not same")
if(l1 == l2):
print("List1 and List2 are same")
else:
print("List1 and List2 are not same")
output:
a and b have same identity
3472800
3472800
List1 and List2 are not same
List1 and List2 are same
Output statement
print() statement is used.
Example:
#output statements
print("hi")
print('hi')
print("This is demo of \n new line")
print("This is demo of \t tab space")
print("This is demo of escape \\n sequence character")
print("This is demo of escape \\t sequence character")
print("This is demo of multiplication" *2)
print("String1"+ "String2")
print("String1" +"1")
Output:
hi
hi
This is demo of
new line
This is demo of tab space
This is demo of escape \n sequence character
This is demo of escape \t sequence character
This is demo of multiplicationThis is demo of multiplication
String1String2
String11
Example:
#output statements demo
#print variable list statement
a,b=2,4
print(a)
print(a,b)
x,y,z=1,2,3
#print(x,y,z, sep=",")
print(x,y,z, sep=":")
print(x,y,z, sep="-----")
print("this")
print("is")
print("demo")
print("this",end=" ")
print("is",end=" ")
print("demo",end=" ")
Example
#print objects
lst=[1,'a','abc']
print(lst)
s={'eng':10,'hindi':9}
print(s)
output:
[1, 'a', 'abc']
{'hindi': 9, 'eng': 10}
Example:
#print("string",variable list) statement
a=2
print(a,"is even number")
b=5
print("b value is",b)
#print(formatted string) statement
x=10
print('value of x is %i'%x)
print("value of x is %d"%x)
x,y=10,15
print("x=%d, y=%d"%(x,y))
a=20;b=30
print("a=%d b=%d" %(a,b))
name="abcd"
print(name)
print("%s"%name)
print("%20s"%name)
print("%-20s"%name)
print("%c"%name[0])
print("%c %c %c"%(name[0],name[1],name[2]))
print("%s"%name[0:2])
#print floating point values
n=123.45678
print("%f"%n)
print("%2f"%n)
print("%8f"%n)
print("%8.0f"%n)
print("%8.2f"%n)
print("%8.3f"%n)
print("%-8.0f"%n)
print("%-8.2f"%n)
print("%-8.3f"%n)
print("%-8.4f"%n)
print("%-8.5f"%n)
Output:
(2, 'is even number')
('b value is', 5)
value of x is 10
value of x is 10
x=10, y=15
a=20 b=30
abcd
abcd
abcd
abcd
a
a b c
ab
123.456780
123.456780
123.456780
123
123.46
123.457
123
123.46
123.457
123.4568
123.45678
Example:
#use of replacement field in output statement
n1,n2,n3=1,2,3
print("Format1")
print("number1={0}".format(n1))
print("Format2")
print("number1={0},number2={1},number3={2}".format(n1,n2,n3))
print("Format3")
print("number1={0},number2={1},number3={2}".format(n1,n2,n3))
print("Format4")
print("number1={1},number2={0},number3={2}".format(n1,n2,n3))
print("Format5")
print("number1={one},number2={two},number3={three}".format(one=n1,two=n2,three=n3))
print("Format6")
print("number1={two},number2={one},number3={three}".format(one=n1,two=n2,three=n3))
print("Format7")
print("number1={},number2={},number3={}".format(n1,n2,n3))
name,marks="abc",70
print("Format8")
print("marks of {0} is{1}".format(name,marks))
print("Format9")
print("marks of {n} is{m}".format(n=name,m=marks))
print("Format10")
print("marks of {:s} is{:.2f}".format(name,marks))
print("Format11")
print("marks of {0:s} is{1:.2f}".format(name,marks))
print("Format12")
print("marks of %s is %d" %(name,marks))
Output:
Format1
number1=1
Format2
number1=1,number2=2,number3=3
Format3
number1=1,number2=2,number3=3
Format4
number1=2,number2=1,number3=3
Format5
number1=1,number2=2,number3=3
Format6
number1=2,number2=1,number3=3
Format7
number1=1,number2=2,number3=3
Format8
marks of abc is70
Format9
marks of abc is70
Format10
marks of abc is70.00
Format11
marks of abc is70.00
Format12
marks of abc is 70
Example:
print("This is demo{} of format".format(1))
print("This is demo{0} of format".format(2))
print("This is demo{} and demo{} of format".format(3,4))
print("This is demo{0} and demo{1} of format".format(5,6))
print("This is demo{1} and demo{0} of format".format(7,8))
print("This is name demo{n1}".format(n1=1))
print("This is name demo{n2} and {n3}".format(n1=1,n2=2,n3=3))
print("This is data type demo{0:s} and {1:d}".format("abc",20))
print("This is data type demo{0:s} and {1:f}".format("abc",20))
Output:
This is demo1 of format
This is demo2 of format
This is demo3 and demo4 of format
This is demo5 and demo6 of format
This is demo8 and demo7 of format
This is name demo1
This is name demo2 and 3
This is data type demoabc and 20
This is data type demoabc and 20.000000
Input statement
Input function is used to take input from the user.
Example 1:
#input function demo
str=input()
print(str)
str=input("Enter your name")
print("Name is "+str)
str=input("Enter number")
x=int(str)
print(x)
str=int(input("Enter integer number"))
print(str)
str=float(input("Enter float number"))
print(str)
str=input("Enter character")
print(str[0])
Output:
abc
abc
Enter your namexyz
Name is xyz
Enter number11
11
Enter integer number5
5
Enter float number11.2
11.2
Enter charactera
a
Example2:
#input 2
x=int(input("Enter first number"))
y=int(input("Enter second number"))
print("You Entered ",x,y)
print("You Entered %d,%d" %(x,y))
print("You Entered ",x,y,sep=',')
print("You Entered {},{}".format(x,y))
Output:
Enter first number2
Enter second number3
You Entered 2 3
You Entered 2,3
You Entered ,2,3
You Entered 2,3
Example3:
#input3
#input from other number system
str=input("Enter hexadecimal numbers")
n=int(str,16)
print("Hexadecimal to decimal",n)
str=input("Enter octal numbers")
n=int(str,8)
print("Octal to decimal",n)
str=input("Enter binary numbers")
n=int(str,2)
print("Binary to decimal",n)
Output:
Enter hexadecimal numbers16
Hexadecimal to decimal 22
Enter octal numbers7
Octal to decimal 7
Enter binary numbers11
Binary to decimal 3
Example4:
#input4
var1,var2,var3=[int(x) for x in input("Enter three numbers space seperated: ").split()]
sum=var1+var2+var3
print(sum)
var1,var2,var3=[int(x) for x in input("Enter three numbers comama seperated: ").split(',')]
sum=var1+var2+var3
print(sum)
var1,var2,var3=[int(x) for x in input("Enter three numbers - sepereated: ").split('-')]
sum=var1+var2+var3
print(sum)
lst=[x for x in input("Enter three string , seperated: ").split(",")]
print(lst)
Output:
Enter three numbers space seperated: 1 2 3
6
Enter three numbers comama seperated: 1,2,3
6
Enter three numbers - sepereated: 1-2-3
6
Enter three string , seperated: abc,def,ghi
['abc', 'def', 'ghi']
Command line arguments
Example1:
#command line arguments
import sys
n=len(sys.argv)
args=sys.argv
print("No. of arguments are" ,n)
print("All arguments are")
print(args)
print("All arguements one by one")
for x in args:
print(x)
Output:
D:\DarshanaPatel2020\python lectures\5>python cmd_test1.py a b c
('No. of arguments are', 4)
All arguments are
['cmd_test1.py', 'a', 'b', 'c']
All arguements one by one
cmd_test1.py
a
b
c
Example:
#python program to find sum of two numbers passed through command line arguments
import sys
print("0th arguments is file name: ",sys.argv[0])
ans=int(sys.argv[1])+int(sys.argv[2])
print("sum is :",ans)
args=sys.argv[1:]
print("All arguments other than program")
for x in args:
print(x)
output:
D:\DarshanaPatel2020\python lectures\5>python cmd_test2.py 1 2 3
('0th arguments is file name: ', 'cmd_test2.py')
('sum is :', 3)
All arguments other than program
1
2
3
Example:
import argparse
parser =argparse.ArgumentParser(description="This program display the addition of two numbers")
parser=argparse.ArgumentParser()
parser.add_argument("num1",type=int, help="Input first integer number")
parser.add_argument("num2",type=int, help="Input second integer number")
args= parser.parse_args()
ans= int(args.num1)+ int(args.num2)
print("Sum is " ,ans)
output:
D:\DarshanaPatel2020\python lectures\5>python cmd3_test3.py -h
usage: cmd3_test3.py [-h] num1 num2
positional arguments:
num1 Input first integer number
num2 Input second integer number
optional arguments:
-h, --help show this help message and exit
D:\DarshanaPatel2020\python lectures\5>python cmd3_test3.py 2 4.5
usage: cmd3_test3.py [-h] num1 num2
cmd3_test3.py: error: argument num2: invalid int value: '4.5'
D:\DarshanaPatel2020\python lectures\5>python cmd3_test3.py 2 4
('Sum is ', 6)
Indentation
Code blocks are identified by indentation rather than using symbols like curly braces.
Without extra symbols, programs are easier to read.
Also, indentation clearly identifies which block of code a statement belongs to.
Python's features are that it is simplistic in nature and easy to read.
Python does not support braces to indicate blocks of code for class and function definitions or flow control.
Blocks of code are denoted by line indentation.
All the continuous lines indented with same number of spaces would form a block.
Python strictly follow indentation rules to indicate the blocks.
The if-elif-else statement
#if condition Example:
x=int(input("Enter value of x"))
if(x>10):
print("X is greater then 10")
else:
print("X is less then 10")
Output:
Enter value of x5
X is less then 10
While loops
#while
x=int(input("How many times u want to print hello?"))
i=0
while(i<x):
print("Hello")
i=i+1
print("\n Loop completed")
Nested
Loops
#nested loop
for i in range(1,11):
for j in range(1,11):
print("\t %i * %i = %i"%(i,j,(i*j)),end=" ")
print("\n")
The else Suite
Program1:
x=int(input("Enter number"))
for i in range(x):
print("hello")
else:
print("Loop completed")
Program2:
i=0
sum=0
y=int(input("Enter number less then 10"))
while(y<10):
sum=sum+y
y=y+1
else:
print("sum is ",sum)
Program3:
z=int(input("Enter value 10"))
while(z==10):
print("Entered number is 10")
z=z+1
else:
print("number is not 10")
Break
#break statement demo
#print prime number
x=int(input("Enter number"))
flag=0
i=2
while(i<x):
if(x%i==0):
flag=1
break
i=i+1
if(flag==0):
print("No ",x, "is prime")
else:
print("No ", x, " is not prime")
Continue
#continue statement
#print only even numbers
i=2;
limit=int(input("Enter limit"))
while(i<limit):
if(i%2!=0):
i=i+1
continue
else:
print(i)
i=i+1
Pass
#pass demo
x=int(input("Enter value of x"))
if(x<10):
pass
else:
print(x)
assert
Example1
#assert demo
no=int(input("Enter no between 1 to 3"))
assert 0<no<4, "Enter no between 1 to 3"
if(no==1):
print("One")
elif(no==2):
print("Two")
else:
print("Three")
Example2
#assert demo
try:
no=int(input("Enter no between 1 to 3"))
assert 0<no<4
if(no==1):
print("One")
elif(no==2):
print("Two")
else:
print("Three")
except AssertionError:
print("No not between 1 to 3")
return statements.
#return demo
def sum(a,b):
return(a+b)
res=sum(5,6)
print("Result is ",res)