0 ratings0% found this document useful (0 votes) 103 views299 pagesPython
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
Pa @ python
Learn
Complete
Python
In
Simple Way
1| https://www.youtube.com/durgasoftware@ python
Introductio
Python is a general purpose high level programming language.
Python was developed by Guido Van Rossam in 1989 while working at National
Research Institute at Netherlands.
But officially Python was made available to public in 1991. The official Date of Birth for
Python is : Feb 20th 1991.
Python is recommended as first programming language for beginners.
Eel: To print Helloworld
Java:
public class Helleworld
‘ sv main(String|] args)
‘ SOP("Hello world");
:
11) -#includecstdio.h>
2) void main()
3) {
4) _ print("“Hetlo world");
s))
Python:
print(*Hello World")
£22: To print the sum of 2 numbers
davai
1) public class Add
24
2) public static void main(String[] args)
4)
3) https://www.youtube.com/durgasoftwareSystem.out.printin("The Sum:"+(a+b));
11) Hinelude
2)
3) void main()
4) 4
5) inta,b;
6)
7) b=20;
8) _ printi{"The Sum:%d",(a+b));
9))
3) print{"The Sum:",{a+b))
The name Python was selected from the TV Show
“The Camplete Monty Python's Circus", which was broadcasted in BBC from 1969 to 1974.
Guido developed Python language by taking almost all programming features from
different languages
1. Functional Programming Features from C
2, Object Oriented Programming Features from C++
3. Scripting Language Features from Perl and Shell Script
4, Modular Programming Features from Modula-3
Most of syntax in Python Derived from C and ABC languages.
We can use everywhere. The most commen impartant application areas are
1) For developing Desktop Applications:
2) For developing web Applications
3) For developing database Applicatians
4) https://www.youtube.com/durgasoftware@ python
4) For Network Programming
5) For developing games
6) For Data Analysis Applications
7) For Machine Learning
8) For developing Artificial Intelligence Applications
9) Far loT
Note;
Internally Google and Youtube use Python coding.
NASA and Nework Stock Exchange Applications developed by Python.
Top Software companies like Google, Microsoft, IBM, Yahoo using Python,
Features of Python:
» Simple and easy to learn:
Python is a simple programming language. When we read Python program,we can feel
like reading english statements.
‘The syntaxes are very simple and only 30+ kerywords are available.
‘When compared with other languages, we can write programs with very less number
of lines. Hence more readability and simplicity.
We can reduce development and cost of the project.
We can use Python software without any licence and it is freeware.
Its source code is open,so that we can we can customize based on our requirement,
Eg; Jython is customized version of Python to werk with Java Applications.
Python is high level programming language and hence it is programmer friendly
language.
Being a programmer we are not required to concentrate low level activities like
memory management and security ete.
‘Once we write a Python program, it can run on any platform without rewriting ance
again.
Internally PVM is responsible to convert into machine understandable form.
5) Portability:
Python programs are portable. ie we can migrate from one platform to another
platform very easily. Python programs will provide same results on any paltform.
https://www.youtube.com/durgasoftware@ python
6) Dynamically Typed:
* In Python we are not required to declare type for variables. Whenever we are
assigning the value, based on value, type will be allocated automatically.Hence Pythan
is considered as dynamically typed language.
* But Java, € etc are Statically Typed Languages b'z we have to provide type at the
beginning only.
© This dynamic typing nature will provide more flexibility to the programmer.
7) i it
Python language supports both Pracedure oriented (like C, pascal etc) and object
oriented (like C++, Java) features. Hence we can get benefits of both like security and
reusability etc
8) Interpreted:
+ Weare not required to compile Python programs explcitly, Internally Python
interpreter will take care that compilation.
if compilation fails interpreter raised syntax errors. Once compilation success then:
PVM (Python Virtual Machine) is responsible to execute.
9) Extensible:
«We can use other language programs in Python.
* The main advantages of this approach are:
= We can use already existing legacy non-Python code
= We can improve performance of the application
10) Embedded;
We can use Python pragrams in any other language programs.
Lewe can embedd Python programs anywhere.
11) Extensive Library:
© Python has a rich inbuilt library.
® Being a programmer we can use this library directly and we are net responsible to
implement the functionality, Ete,
Limitations of Python:
1) Performance wise not up to the mark because it is interpreted language.
2) Not using for mobile Applications,
©) https://www.youtube.com/durgasoftware@ python
Flavors of Python:
1) CPython:
It is the standard flavor of Python. It can be used to work with C lanugage Applications.
2) Jython OR JPython:
Itis for Java Applications. It can run on JVM
3)
It is for C#.Net platform
4) Pypy:
The main advantage of PyPy is performance will be improved because JIT compiler is
available inside PVM.
5) RubyPython
For Ruby Platforms
6)
It is specially designed for handling large volume of data pracessing.
Python Versions:
® Python 1.0Vintroduced in Jan 1994
F Python 2.0V introduced in October 2000
® Python 3.0V introduced in December 2008
Note: Python 3 won't provide backward compatibility to Python? i.e there is no
guarantee that Python2 programs will run in Python3,
Current versions
Python 3.6.1 Python 2.7.13
7) https://www.youtube.com/durgasoftware@ python
IDENTIFIERS
+ A\Name in Python Program is called Identifier.
* Itcan be Class Name OR Function Name OR Module Name OR Variable Name.
* a=10
1, The only allowed characters in Python are
+ alphabet symbols(either lower case or upper case)
* digits(0 to 9)
* underscore symbol(_)
By mistake if we are using any other symbol like $ then we will get syntax error.
© cash=104
+ ca$h=20 X
2, Identifier should not starts with digit
© 123total X
* total1273d
3. Identifiers are case sensitive. Of course Python language is case sensitive language.
‘total=10
TOTAL=999
print{total) #10
print(TOTAL) #999
8) https://www.youtube.com/durgasoftware@ python
Identifier:
1) Alphabet Symbols (Either Upper case OR Lower case)
2) Ifldentifier is start with Underscore (_) then it indicates it is private.
3) Identifier should not start with Digits.
4) Identifiers are case sensitive.
5) We cannot use reserved words as identifiers
Eg.def= 10x
6) There is no length limit for Python identifiers. But not recommended to use too
lengthy identifiers.
7) Dollor ($) Symbol is not allowed in Python.
Q) Which of the following are valid Python identifiers?
1) 123total *
2) totaliz3 J
3) java2shared
4) cagh x
5) _abc_abe_J
6) def x
7) itx
Note:
1) If identifier starts with _ symbol then it indicates that itis private
2) Ifidentifier starts with __(Two Under Score Symbols) indicating that strongly private
identifier.
3) If the identifier starts and ends with two underscore symbals then the identifier is
language defined special name, which is also known as magic methods.
4) Ex: add
°) https://www.youtube.com/durgasoftwareIn Python some words are reserved to represent some meaning or functionality.
Such types of words are called reserved words.
There are 33 reserved words available in Python.
+ True, False, None
* and, or ,no'
+ if,elif,else
* while, for, break, continue, return, in, yield
‘© try, except, finally, raise, assert
«import, from, as, class, def, pass, global, nonlocal, lambda, del, with
Note:
1. All Reserved words in Python contain only alphabet symbols.
2. Except the following 3 reserved words, all contain only lower case alphabet symbols.
© True
© False
* None
Eg: a= true X
acTrue J
>>> import keyword
>>> keyword. kwlist
['False’, 'None’, ‘True’, ‘and’, ‘as’, ‘assert, ‘break, ‘class’, ‘continue’, ‘def’, ‘de, ‘elif, ‘else’,
‘except’, ‘finally’, ‘for’, ‘from’, ‘global’, ‘if, ‘import’, ‘in’, ‘is’, ‘lambda’, ‘nonlocal’, ‘not’, ‘or’,
‘pass’, ‘raise’, ‘return’, ‘try’, ‘while’, ‘with’, ‘yield']
10) https://www.youtube.com/durgasoftware@ python
DATA TYPES
+ Data Type represents the type of data present inside a variable.
+ In Python we are not required to specify the type explicitly. Based on value provided,
the type will be assigned automatically. Hence Python is dynamically Typed Language.
Python contains the following inbuilt data types
1) Int
2) Float
3) Complex
4) Bool
5) str
6) Bytes
7) Bytearray
8) Range
5) List
10) Tuple
11)Set
12) Frozenset
13) Diet
14) None
Note; Python contains several inbuilt functions
1) type
to check the type of variable
2) id()
to get address of object
11) https://www.youtube.com/durgasoftware@ python
3) print()
to print the value
In Python everything is an Object.
1) int Data Type:
We can use int data type to represent whole numbers (integral values)
Egia=10
‘type(a} #int
Note:
+ In Python2 we have long data type to represent very large integral values.
‘+ But in Python3 there is no long type explicitly and we can represent long values also by
using int type only.
We can represent int values in the following ways
2) Decimal form
2) Binary form
3) Octal form
4) Hexa decimal form
|) Decimal Form (Base-10);
* Itis the default number system in Python
+ The allowed digits are: 0 to 9
© Ega=10
Il)Binary Form (Base-2):
+ The allowed digits are:0 & 1
Literal value should be prefixed with Ob or OB
12) https://www.youtube.com/durgasoftware@ python
Ill) Octal Form (Base-8):
+ The allowed digits are :0 to7
+ Literal value should be prefixed with Oo or 00,
© Egza=00123
IV)
+ The allowed digits are: 0 to 9, a-f {both lower and upper cases are allowed)
+ Literal value should be prefixed with Ox or OX
a= OXBeer
Note: Being a programmer we can specify literal values in decimal, binary, octal and hexa
decimal forms. But PVM will always provide values only in decimal form.
a=10
b=0010
<-0X10
d=0B10
print(a}10
print(b)&
int(c}16
print{d)2
Base Conversions
Python provide the following in-built functions for base conversions
1)bin():
‘We can use bin() to convert from any base to binary
1) >>> bin(15)
2) ‘0b1111"
3) >>> bin(0011)
4) ‘Ob1001°
5) >>> bin(0X10)
13) https://www.youtube.com/durgasoftware@ python
6) ‘ob10000'
2)oct():
We ean use oct() to canvert from any base to octal
1) >>> oet(10)
2) "0012"
3) >>> oct(0B1111)
'4) ‘O017'
5) >>> oct(0X123)
6) "00443"
3)hex():
We can use hex) to convert from any base ta hexa decimal
|1) >>> hex{100)
2) "0x64"
3) >>> hex(0B111111)
\4) ‘Oxat"
5) >>> hex{0012345)
6) 'Oxtdes*
2) Float Data Type:
We can use float data type to represent floating point values (decimal values)
Egif= 1.234
typelf) float
‘We can also represent floating point values by using exponential form
(Scientific Notation)
Egif=1.2¢3 > instead of 'e' we can use 'E’
print(f) 1200.0
‘The main advantage of exponential form is we can represent big values in less
memory.
We can represent int valuesin decimal, binary, octal and hexa decimal forms. But we
can represent float values only by using decimal form.
14) https://www.youtube.com/durgasoftware@ python
2) >>> f20B12.01
2) File “”, tine 1
3) f-0B11,01
la) a
5) Syntax€rror: invalid syntax
6)
7) >>> f00123.456
8) Syntaxerrar: invalid syntax
9)
10) >>> f=0X123.456
111) SyntaxError: invalid syntax
3) Complex Data Type:
+ Acomplex number is of the form
i
i
Real Part Imaginary Part
a+bj——
‘a’ and ‘b’ contain Intergers OR Floating Point Values.
Fai 3+5)
1045.5)
0.5+0.1j
© Inthe real part if we use int value then we can specify that either by decimal, octal,
binary or hexa decimal form.
But imaginary part shauld be specified only by using decimal farm.
1) >>> ac0B11+5)
2) >>>a
3) (+5)
4) >>>a=340B13j
5) SyntaxError: invalid syntax
Even we can perform operations on complex type values.
2) >>>a=1041.5)
2) >>> b=20+2.5]
3) >>>ezatb
14) >>> print(e)
15) https://www.youtube.com/durgasoftware@ python
5) (30+4j)
6) >>> typete}
7), 10.5,
caimag > 3.6
We can use complex type generally in scientific Applications and electrical engineering
Applications.
4) bool Data Type:
We can use this data type to represent boolean values.
‘The only allowed values for this data type are:
True and False
internally Python represents True as 1 and False as 0
b=True
type(b) boot
Eg:
a=10
b=20
ceach
print(c) > True
True+True > 2
True-False > 1
5) str Data Type:
str represents String data type.
A String is a sequence of characters enclosed within single quotes or double
quotes.
16) https://www.youtube.com/durgasoftwareBy using single quotes or double quotes we cannot represent multi line string
literals.
si="durga
soft"
For this requirement we should go for triple single quotes("") or triple double
quotes(""")
"durga
soft"
si="""durga
soft"
We can also use triple quotes to use single quote or double quate in our String.
Thi sharacter™
"This i” Character”
We can embed one string in another string
“This “Python class very helpful” for java students"
Slicing of Strings:
1)
2)
3)
4)
5)
6)
slice means a piece
[] operator is called slice operator, which can be used to retrieve parts of String.
In Python Strings follows zero based index.
‘The index can be either 4ve or -ve.
+ve index means forward direction from Left to Right
~ve index means backward direction from Right to Left
5 3 4
LeTeT:fela]
oO 1 2 3 4
1) >>>s="durga™
2) >>>s{0]
3) “a
4) >>>s{l]
5)‘
6) >>>s[-t]
7) ‘at
18) >>> laa]
17) https://www.youtube.com/durgasoftware@ python
IndexError: string index out of range
1) >>>s{1:40]
2) ‘urea
3) >>>s[1:]
la)
5)
6)
7)
8)
9)
10)
Li)po>s*3
12) 'durgadurgadurga'
13)
114) >>> len(s)
15)5
Note:
1) In Python the following data types are considered as Fundamental Data types
int
complex
boo!
oot
© float
2) In Python, we can represent char values also by using str type and explici
is not available.
1) 23> e'a!
2) >>> typele)
3)
3) long Data Type is available in Python2 but not in Python3. In Python3 long values also
‘we can represent by using int type only.
4) In Python we-can present char Value also by using str Type and explicitly char Type is
not available.
18) https://www.youtube.com/durgasoftware@ python
TYPE CASTING
& We can convert one type value to another type. This conversion is called Typecasting
or Type coersion.
© The following are various inbuilt functions for type casting.
2) int()
2) float()
3) complex()
4) beol()
5) str()
@ inth:
We can use this function to convert values from other types to int
|2) >>> int(123,987}
2) 123
3) >>> int(10+5j)
4) Typeérror: can’t convert complex ta int
5) >>> int(True)
eB) 2
7) >>> int(False)
8) 0
9) >>> int("10")
10)10
12) >>> int("20.5")
12) Value€rror: invalid literat for int() with base 10: ‘10.5"
13) >>> int("ten")
18) ValueErrar: invalid literal for int() with base 10: ‘ten’
15) >>> int("0B1111")
16) ValueError: invalid literal for int() with base 10: 0B1121"
Note:
1) We can convert from any type to int except complex type.
2) if we want to convert str type to int type, compulsary str should contain only integral
value and should be specified in base-10.
19) https://www.youtube.com/durgasoftware@ python
® floatl):
We can use float() function to convert other type values to float type.
2) >>> float{10)
2) 10.0
3) >>> float(10+5))
4) TypeError: can't convert complex ta float
5) >>> float(True)
6) 1.0
7) >>> float(False)
8) 0.0
9) >>> float("10")
10) 10.0
11) >>> float("10.5")
12) 10.5
13) >>> float("ten")
14) ValueError: could not convert string to float: ‘ten’
15) >>> float("0B1111")
16) ValueError: could not convert string to float: ‘OBL114'
Note:
1) We-can convert any type value to float type except complex type.
2) Whenever we are try to convert str type ta float type compulsary str should be
either integral or floating point literal and shauld be specified only in base-10,
G complex()
We can use complex() function to convert other types to complex type.
Form-1: complex(x)
We can use this function to convert x into complex number with real part x and imaginary
part.
a)
2)
3)
4)
5) camplext"10"
6) complex{"10.5"
7) complex("ten")
8) ValueError: complex() arg [sa malformed string
20) https://www.youtube.com/durgasoftware@ python
Form-2: complex(x,y)
We can use this method to convert x and y into complex number such that x will be real
part and y will be imaginary part.
Eg: complex(10, -2) > 10-2)
complex(True, False) > 1+0j
® bool()
We cain use this function to convert other type values to bool type.
1) bool{0) > False
2) bool() > True
3) bool(10) > True
4) bool(10.5) > True
5) bool(0.178) > True
6) bool{0.0) > False
7) bool(10-2)) > True
8) bool{O+1.5)) > True
9) bool{0+0}) > False
10) bool{"True") > True
11) bool("False") > True
112) bool{"") > False
(int Gatetyee
4. O means False
2. Non-zero mean: True
[Kis float datatype
1, If total number value is zero then the recult ic Faleo
otherwise the result is True
1X is Complex datatype
1. If both real and imaginary parts are zero .i.e 0+0)
then the result is False otherwise the result Is True
Tig str dataryp
ait pty string then the result is False otherwise
the result is True
21 | https://www.youtube.com/durgasoftware@ python
® seri):
We can use this method to convert other type values to str type.
2) >>> str(10)
2) ‘10°
3) >>> str(10.5)
4) ‘105°
5) >>> str(1045))
6} '(2045))'
7) >>> str(True)
8) ‘True’
Fundamental Data Types vs Immutability
& All Fundamental Data types are immutable. i.e once we creates an object,we cannot
perform any changes in that object. If we are trying to change then with those changes
‘a new object will be created. This non-chageable behaviour is called immutability.
In Python if a new object is required, then PVM won't create abject immediately. First
it will check is any object available with the required content or not. if available then
existing object will be reused. if it is not available then only a new object will be
created. The advantage of this approach is memory utilization and performance will be
improved.
But the problem in this approach is, several references pointing to the same object, by
using one reference if we are allowed to change the content in the existing object then
the remaining references will be effected. To prevent this immutability concept is
required. According to this once creates an object we are not allowed to change
content. If we are trying to change with those changes a new object will be created.
1) >>>a=10
2) >>> bet
3) spraisb
4) True
5) >>> ida)
6) 1572353952
7) >>>id{(b)
8) 1572353952
8) >>>
22) https://www.youtube.com/durgasoftwarepee asl0 >>> a=2045] >>> aTrue lurea’
pep b=10 32> b=10+5) pee beTrue >>> be'durga’
>>> dla) >raish pepaisb poraish
1572353952 False True True
>>> id{b) >>> ida) >>> dla) >>> id(a)
1572353952 15980256 1572172624 16378848
sso aisb 35> id(b) 29> id{b) >>> id(b)
True 15979944 1572172624, 16378848
6) bytes Data Type:
bytes data type represens a group of byte numbers just like an array.
1) x= [10,20,30,40]
2) b= bytes(x)
3) type(b) > bytes
a) prine(b[a}) > 10
5) print(bf-1)) > 40
6) >>> for lin b: print)
7)
8)
9)
10)
1)
Conclusion 1:
The only allowed values for byte data type are 0 to 256. By mistake if we are trying to
provide any other values then we will get value error,
Conclusion 2:
Once we creates bytes data type value, we cannot change its values,otherwise we will get
TypeError.
23) https://www.youtube.com/durgasoftware@ python
>>> x=[10,20,30,40]
>>> bebytes(x)
>>> b[0]=
Type€rror: ‘bytes’ abject does not support item assignment
bytearray Data Type:
bytearray is exactly same as bytes data type except that its elements can be
x=[10,20,30,40]
ytearray(x)
fori in b: print(i}
10
20
30
40
b[0}=100
fot iin
11)20
12)30
13)40
fez
1) p>>x=[10,256]
2) >>> b= bytearray{x)
3) Value€tror: byte must be in range(0, 256)
If we want to represent a group of values asa single entity where insertion order
required to preserve and duplicates are allowed then we should go for list data
type.
1) Insertion Order is preserved
2) Heterogeneous Objects are allowed
3) Duplicates are allowed
4) Growable in nature
5) Values should be enclosed within square brackets.
24) https://www.youtube.com/durgasoftware@ python
list=[10,10.5,'durga’ ,True,10]
print(list) # [10,10.5, durga',True, 10]
41) Hist=(10,20,30,40}
2) >>> list[0]
3) 10
4) >>>list[-1]
5) 40
6) >>>list[1:3]
7) (20, 30]
8) >>> list[0]=100
'9) >>> foriin list:print(i)
10).
11) 100
12)20
13) 30
1a)4o
list is growable in nature. i.e based on our requirement we can increase or decrease the
size.
1) >>> list=[10,20,30]
2) >>> list.append("durga")
3) >> list
4) [10, 20, 30, “durga’]
5) >>> list.remove(20)
6) >>>list
7) [10, 30, ‘durga’)
8) >>> list2clist"2
9) >>> ist2
10) [10, 30, ‘durga’, 10, 30, "durga']
Note: An ordered, mutable, heterogenous collection of eleemnts is nothing but list,
where duplicates also allowed.
25) https://www.youtube.com/durgasoftware@ python
Tuple Data Type:
tuple data type is exactly same as list data type except that it is immutable.i.e we
cannot chage values.
‘Tuple elements can be represented within parenthesis.
t=(10,20,30,40)
type(t)
t{0}=100
‘Type€rror: ‘tuple’ object does not support item assignment
>>> Lappend(“durga")
AttributeError: ‘tuple’ object has no attribute ‘append’
>>> tremove(10)
AttributeError: ‘tuple’ object has no attribute ‘remove!
Note: tuple is the read only version of list
10) Range Data Type:
range Data Type represents a sequence of numbers.
‘The elements present in range Data type are not modifiable. i.e range Data type is
immutable.
Form-1: range(10)
generate numbers from 0 tad
Eg:
1 = range(10)
for iin r: print{i) > 00 9
Form-2: range(10, 20)
generate numbers from 10 to 19
Eg:
r= range(10,20)
for fin print{i) 240 to 19
26) https://www.youtube.com/durgasoftware@ python
Form-3: range(10, 20, 2)
2 means increment value
Eg:
r= range(10,20,2)
for iin r: print(i) > 10,12,24,16,18
We can access elements present in the range Data Type by using index.
Eg
= range(10,20)
{0} > 10
#[15] > Indexérror: range object index out of range
We cannot modify the values of range data type
Eg
{0} = 100
TypeError: ‘range’ object does nat support item assignment
We can create a list of values with range data type
Ee:
A) >>> 1 =list{range(10))
2) >>>l
3) [0,1,2,3,4,5, 6,7, 8,9]
11) set Data Type:
@ If we want to representa group of values without duplicates where order isnot
important then we should go for set Data Type.
2) Insertion order is not preserved
2) Duplicates are not allowed
3) Heterogeneous objects are allowed
4) Index concept is not applicable
5) Itis mutable collection
6} Growable in nature
27) https://www.youtube.com/durgasoftware|1) s=€100,0,10,200,10,'durga'}
2) s#{0, 100, 'durga’, 200, 10}
|3) s[0] > TypeError: ‘set’ object does not support indexing
® set is growable in nature, based on our requirement we can increase or decrease the
size.
1) >>> s.add(60)
2) >9>5
3) {0, 100, ‘durga’, 200, 10, 60)
4) >>> s.remove(100)
5) >>>5
(8) {0, ‘durga’, 200, 10, 60)
12) frozenset Data Type:
® Itis exactly same as set except that itis immutable,
® Hence we cannot use add or remove functions.
1) >>>s=(10,20,30,40}
2) >>> fs-frozensett(s)
'3) >>> typetfs)
4)
5) >o>fs
6) frozenset({40, 10, 20, 30})
7) >> for iin fs:print{i)
B) aw
9) 40
10)10
11}20
12)30
13)
14) >>> fs.add(70)
115) AttributeError: 'frozenset' object has no attribute ‘add’
16) >>> fs.remove(10)
17) AttributeError: 'frozenset’ object has no attribute ‘remave
28) https://www.youtube.com/durgasoftware@ python
13) dict Data Type:
If we want to represent a group of values as key-value pairs then we should go for
dict data type.
@ Eg: d = {101;'durga',102;'ravi',103:'shiva'}
® Duplicate keys are not allowed but values can be duplicated. If we are trying to
insert an entry with duplicate key then old value will be replaced with new value.
>>>d={101:'durga',102:'ravi',103:'shiva’}
>>> d[101]='sunny’
ood
We can create empty dictionary as follows
d={}
We can add key-value pairs as follows
df'a'J-'apple’
10} df'b']="banana®
11) print(d)
Note: dict is mutable and the order won't be preserved.
Note:
4)
2)
3)
In general we can use bytes and bytearray data types to represent binary information
like images, video files ete
In Python2 long data type is available. But in Python3 itis not available and we can
represent long values also by using int type only.
In Python there is na char data type. Hence we can represent char values also by using
str type.
25) https://www.youtube.com/durgasoftwareSummary of Datatypes in Python 3
[Datatype |Description |isimmutable? [Example
We can use to
represent the
whole/integral
numbers
We can use to
represent the
decimal/floating
point numbers
Immutable
>>> aal0
>>> typela)
>>> b=10.5.
>>> type(b)
‘Complex
bytearray
We can use to
represent the
complex numbers
immutable
We can use to
represent the logical
values (Only allowed
values are True and
False)
To represent
sequence of
Characters
Torepresent a
sequence of byte
values from 0-255
Torepresent a
sequence of byte
values from 0-255
To represent arange | immutable
of values
>>> c=1045)
>>> typele)
>>> teal
10.0
>>> imag
5.0
>>> flageTrue
>>> flag=False
>>> type(flag)
>>> seidurga’
>>> type(s)
>>> s="Durga Software
Solutions... Ameerpet™*
>>> types)
>> bebytes(list)
>>> typelb)
>>> ba=bytearray(list)
>>> type(ba)
>>> r=range(10)
>>> rlsrange(0,10)
>>> r2=range(0,10,2)
30 | https://www.youtube.com/durgasoftwareTo represent an
ordered collection of
objects
tuple Torepresent an
ordered collections of
le represent an Mutable
unerdered collection
"ls unique objects
To represent an Immutable
unordered callection
of unique objects.
To represent a group | Mutable
of key value pairs
14) None Data Type:
* None means nothing or No value associated,
>>p I-[10,11,12,13,14,15]
>>> typell)
353t=(1,2,3,4,5)
>>> typelt)
>>> s={1,2,3,4,5,6)
>>> types)
>>> 5=(11,2,3, Durga’,100,'Ramu'}
>>> fs=frozenset(s)
>>> typelts)
3
d= {101:'durga’, 10,
103:'hari'}
>>> type(d)
+ Ifthe value is not available, then to handle such type of cases None introduced.
* Itissomething like null value in Java.
Ee:
def mi(}:
a=10
print(m1())
None
31) https://www.youtube.com/durgasoftwarein String literals we can use esacpe characters to associate a special meaning.
1) >>> s="durga\nsoftware"
2) >>> printis)
3)
4)
5) “durga\tsaftware”
6) >>> print(s)
7) durga software
8) >>>s="This is " symbol”
9) stdin>", ine 2
10) s="Thisis " symbol"
11) “
12) SyntaxError: invalid syntax
13) >>> s="This is \" symbol
14) >>> prints)
115) This is " symbol
The following are various important escape characters in Python
1) \n
2) Mt
3) \r
4) \b
5) \f
6) Ww
7
8) \"
9) \
New Line
Horizontal Tab
Carriage Return
Back Space
Form Feed
Vertical Tab
Single Quote
Double Quote
Back Slash Symbal
vou
Constants:
Constants concept is nat applicable in Python.
But it is convention to use only uppercase characters if we don’t want to change value.
MAX_VALUE = 10
Itis just convention but we can change the value.
32) https://www.youtube.com/durgasoftware@ python
* Operator is a symbol that performs certain operations,
«Python provides the fallowing set of operators
1) Arithmetic Operators
2) Relational Operators OR Comparison Operators
3) Logical operators
4) Bitwise oeprators
5) Assignment operators
6) Special operators
1) Arithmetic Operators:
at Addition
2) - Subtraction
ag Multiplication
a) / Division Operator
5) % Medulo Operator
ey Floor Division Operator
an Exponent Operator OR Power Operator
Eg: test.py
a=i0
Output:
Python test.py OR py test.py
atb=12
arb= 8
atb=20
3) https://www.youtube.com/durgasoftwareavb= 12.5
ab=85
a*b= 21.0
a/b= 5.25
a//b= 5.
a%b= 0.5
10)a**b= 110,25
Eg:
10/2 > 5.0
10//25
10.0/2 > 5.0
10.0//2 > 5.0
Note:
® / operator always performs floating point arithmetic. Hence it will always returns float
value.
& But Floor division (//) can perform both floating point and integral arithmetic. If
arguments are int type then result is int type. If atleast one argument is float type then
result is float type,
Note:
@& Wecan use +,* operators for str type also.
& If we want to use + operator for str type then compulsory both arguments should be
str type only otherwise we will get error.
1) >>> "durga"+10
2) TypeError: must be str, not int
3) >>> "durga"+"10"
\4) ‘durgaio’
4) https://www.youtube.com/durgasoftware@ python
© If we use * operator for str type then compulsory one argument should be int and
other argument should be str type,
® 2°"durga"”
“durga"*2
2.5*"durga" > Typetrror: can't multiply sequence by non-int of type ‘float’
“durga"*"durga" > TypeError: can't multiply sequence by non-int of type ‘str’
& + String concatenation Operator
© * > String Multiplication Operator
Note: For any number x,
x/0 and x360 always raises "ZeroDivisionError"
10/0
10.0/0
a)
2)
3)
a) =
5) print(“a< bis”,
6) print("a<:
7)
8) a>bis False
8) a>=bis False
10)acbis Tue
11) acebis Tue
We can apply relational operators for str types also.
a="durga"
b="durga"
print(“a > bis ",a>b)
print(“a >= b is “ja:
print("a < bis ",acb)
print("a c= bis “,ac=b)
5) https://www.youtube.com/durgasoftware@ python
'8) a>bis False
8) a>=bis True
Oja=True) True
3) print(10 >True) True
44) print(False > True) False
5)
6) print{10>'durga')
7) TypeEtror:'>' not supported between instances of ‘int’ and ‘sts*
Ee:
1)
2)
3) if
4) int("a is greater than b")
5) else:
6) _print("ais not greater than b")
Output: ais not greater than b
Note: Chaining of relational operators is possible. In the chaining, if all comparisons
returns True then only result is True. If atleast ane comparison returns False then the:
result is False
1) 10¢20 True
2) 10<20<30 > True
3) 10¢20<30<40 > True
4) 10<20¢30<4050 > False
We can apply these operators for any type even for incompatible types also.
1) >>> 10==20
2) False
3) >>> 10l=20
4) True
5) >>> 10-=Tue
©) https://www.youtube.com/durgasoftware@ python
False
>>> False==False
True
559 "durga"=="durga"
10) True:
11) >>> 10=="durga”
12) False
Note: Chaining concept is applicable for equality operators. If atleast one comparison
returns False then the result is False. Otherwise the result is True.
1) >>> 10==20==:
2) False
3) >>> 10==10:
4) True
4) Logical Operators: and, or, not
We can apply for all types.
For boolean Types Behaviour:
and -> If both arguments are True then only result is True
or > If atleast one arugemnt is True then result is True
not > Complement
‘True and False > False
True or False > True
not False > True
means False
non-zero means True
empty string is always treated as False
If xis evaluates to false return x otherwise return y
Es,
10 and 20
Oand 20
If first argument is zero then result is zero otherwise result is y
7) https://www.youtube.com/durgasoftware@ python
xory:
If x evaluates to True then result is x otherwise result is y
10 or 20 > 10
Dor20> 20
not x:
fixis evalutates to False then result is True otherwise False
not 10 > False
not 0 > True
“durga” and “durgasoft" ==>durgasoft
and “durga" ==>"
“durga” and "*
or “durga”
“durga” or *:
not ==>True
not “durga" ==>False
5) Bitwise Operators:
@ We can apply these operators bitwise.
© These operators are applicable only far int and boolean types.
® By mistake if we are trying to apply for any other type then we will get Error.
BRL <6 >>
@ print(4&s) > valid
& print(10.5 &5.6)
~> TypeError: unsupported aperand type(s) for &: “float! and ‘float’
® print{True & True) > valid
© & > if both bits are 1 then only result is 1 otherwise result is 0
& | tf atleast one bit is 1 then result is 1 otherwise result is 0
© * If bits are different then only result is 1 otherwise result is 0
© ~~ bitwise complement operator
Biro wot
© << > Bitwise Loft shift
8) https://www.youtube.com/durgasoftware@ python
&® >> > Bitwise Right Shift
© printtaas) >4
® printl4|5) 35
® print(a45) > 1
[Description
[if both bits are then only result is Lotherwiseresultiso |
[_=> _J[pitwise Left shift Operator
Binwike Comp 0 i
We have to apply complement for total bits.
Ex: print(-5)>-6
Note:
© The most significant bit acts as sign bit. 0 value represents +ve number where as 1
represents -ve value.
®& Positive numbers will be repesented directly in the memory where as -ve numbers will
be represented indirectly in 2's complement form.
6) Shift Operators:
< 40
LeLeTeoTot:Tet:To]
Lofotitojsifofoto]
°) https://www.youtube.com/durgasoftware@ python
>> Right Shift Operator
After shifting the empty cells we have to fill with sign bit.( 0 for +ve and 1 for -ve)
print(10>>2) > 2
[ofoToTo]: Jor T+
Lofotofofofofifo|
We can apply bitwise operators for boolean types also
® print(True & False) > False
® print(true | False) > True
® print(True * False) > True
@ print(-True) > -2
@ print(true<<2) > 4
® print(true>>2) > 0
7) Assignment Operators:
® We canuse assignment operator to assign value to the variable.
Eg:x= 10
© We can combine asignment operator with some other operator to form compaund
assignment operator.
Eat X42 109 x= xHIO
The following is the list of all possible compound assignment operators in Python,
10) https://www.youtube.com/durgasoftware2) x#=20
3) print) > 30
1) x10
2) x&e5
13) print(x) 30
8)
Syntax: x = firstValue if condition else secondvalue
If condition is True then firstValue will be considered else secondValue will be considered.
Eel:
1) a,b=10,20
2) x=30 if ach else 40
3) print(x) #30
Ez.2; Read two numbers from the keyboard and print minimum value
int{input("Enter First Number:"))
int(input(" Enter Second Number:"))
ymin)
Enter First Number:10
Enter Second Number:30
Minimum Value: 10
Note: Nesting of Ternary Operator is Possible.
Q) Program for Minimum of 3 Numbers
1) acint{input("Enter First Number:"))
2) beint(input("Enter Second Number:"}}
3) _csint{input("Enter Third Number:"))
il | https://www.youtube.com/durgasoftware@ python
4) minza if acb and ace else b if bee else €
5) print(*Minimum Value:",min)
Q) i
1) asint{input(*Enter First Number:"))
2) bsint{input{"Enter Second Number:"))
3) csint(input("Enter Third Number:"))
maxza if a>b and a>c else b if b>celse c
int("Maximum Value:",max)
asint(input(" Enter First Number:"))
beint(input("Enter Second Number:"))
print("Both numbers are equal” if a==b else "First Number is Less than Second
Number" if acb else "First Number Greater than Second Number")
Outputs
D:\python_classes>py test.py
Enter First Number:10
Enter Second Number:10
Both numbers are equal
D:\python_classes>py test.py
Enter First Number:10
Enter Second Number:20
First Number is Less than Second Number
D:\python_classes>py test:py.
Enter First Number:20
Enter Second Number:10
First Number Greater than Second Number
9) Special Operators:
Python defines the fallowing 2 special operators
1) Identity Operators
2) Membership operators
12) https://www.youtube.com/durgasoftware@ python
1)ldentity Operators
* We can use identity operators for address comparison.
* There are 2 identity operators are available
1) is
2) isnot
11 isr2_ returns True if both ri and 1? are pointing to the same object.
11 Is not r2 returns True if both r1 and r2 are not pointing to the same abject.
0
0
print(aisb) True
xeTrue
y-True
print{xisy) True
(i
print{id(b))
print(a is b)
“one","two","three")
"one","two","three"}
print(id(list2))
print{id(list2))
print{list2 is list2) False
Note: We can useis operator for address comparison where as == operator for content
comparison,
13) https://www.youtube.com/durgasoftware@ python
2) Membership Operators:
‘We can use Membership operators to check whether the given object present in the
given collection, (It may be String, List, Set, Tuple OR Dict)
In > Returns True if the given object present in the specified Collection
not in > Retruns True if the given object not present in the specified Collection
x="hello learning Python is very easy!!!"
print('h'inx) True
print('d' inx) False
print('d' notin x) True
print('Python' inx) True
1) lista=["sunny","bunny","chinny","pinny"]
2) print("sunny” in list) True
3) print("tunny” in listd) False
4) print("tunny” not in ist!) True
Operator Precedence:
if multiple operators present then which operator will be evaluated first is decided by
operatar precedence.
Eg:
print(3+10*2) > 23
print((3+10}*2) > 26
The following list describes operator precedence in Python
1) ()> Parenthesis
2) ** > Exponential Operator
3) ~,--> Bitwise Complement Operator, Unary Minus Operator
4) +, /, %, // > Multiplication, Division, Modulo, Floor Division
5) +,- > addi , Subtraction:
6) <<,>> > Left and Right Shift
7) & > Bitwise And
8) * > Bitwise X-OR
9) | > Bitwise OR
10)>, >=,<, > Relational OR Comparison Operators
11)=, > Assignment Operators
https://www.youtube.com/durgasoftware@ python
12)is, is not > Identity Operators
13)in , not in Membership operators
14)not > Logical not
1S}and > Logical and
16)or > Logical or
1) 330
2) b=20
3) ¢10
4) dS
5) print((a+b)*c/d) > 100.0
6) print{{atb)*(c/d)) > 100.0
7) printlat(b*c)/d) > 70.0
8)
9) 3/2*443+(10/5)**3-2
10) 3/2*4+3+2.0**3-2
11) 3/2*4+3+8.0-2
(12) 1.5°443+8.0-2
13) 6.0+348.0-2
14) 15.0
Mathematical Functions (math Module)
& A Module is collection of functions, variables and classes etc.
© math is amodule that contains several functions to perform mathematical operations.
® If we want to use any module in Python, first we have to import that module.
import math
Once we import a module then we can call any function of that module.
1) import math
2) print(math.sqrt(46))
3) print{math.pi)
Qutput
4
3.101592653589793
@ We can create alias name by using as keyword. import math asm
© Once we create alias name, by using that we can access functions and variables of that
module.
fh import math asm
2) print{m.sqrt(16))
15) https://www.youtube.com/durgasoftware@ python
{3). print(m.pi)
® Wecan import a particular member of a module explicitly as follows
from math import sqrt
from math import sqrt,pi
® If we import a member explicitly then it is nat required ta use module name while
accessing.
|2) from math import sqrtjpi
2) print{sqrt(16))
3) print(pi)
4) print NameError: name \(math.pi) 'math' is not defined
Important Functions of math Module:
ceil(x)
floor(x)
pow(x,y)
factorial(x)
trune(x)
ecd(x,y)
sin(x)
cos(x)
tankx)
10)...
Important Variables of math Module:
pi3.14
e271
inf > infinity
nan > nota number
Q) Write a Python Program to find Area of Circle pi*r**2
1) from math impart pi
2) r=16
3) print{"Area of Circle is :",pi*r**2)
Output: Area of Circle is: 804.247719318987
16 | https://www.youtube.com/durgasoftware@ python
Reai Dynamic Input from the Keyboard:
In Python 2 the following 2 functions are available to read dynamic input from the
keyboard.
2) raw_input()
2) input)
1)raw_input():
This function always reads the data from the keyboard in the form af String Format.
We have to convert that string type to our required type by using the corresponding
‘type casting methods.
Eg: x= raw_Input("Enter First Number:")
print(type(x)) > It will always print str type only for any input type
2)input():
input{) function can be used to read data directly in our required farmat.We are not
required to perform type casting.
x= input("Enter Value)
type(x)
10> int
“durga"> str
10.5 > float
True > bool
***Note:
‘+ But in Python 3 we have only input() method and raw_input() method is not available.
+ Python3 input) function behaviour exactly same as raw_input() method of Python2.
ie every input value is treated as str type only.
* raw_input() function of Python 2 is renamed as input() function in Python 3.
1) >>> type(input("Enter value:"))
Enter value:10
Enter value:10.5
‘
Enter value:True
3| https://www.youtube.com/durgasoftware@ python
Q) Write a program to read 2 numbers from the keyboard and print sum
a) iput("Enter First Number:'
2) ysinput("Enter Second Number:")
3) f= imt{x}
4) j=intly)
|5)_print{"The Sum:",i
Enter First Number: 100
Enter Second Number: 200
The Sum: 300
int{input("Enter First Number:"))
2) y=int(input(“Enter Second Number
3) print(“The Sum:" x+y)
|print(*The Sum:",int{input(“Enter First Number:")}+int{input("“Enter Second Number:*)))
Q) Write a Program to read Emplovee Data from the Keyboard and
print that Data
1) itlinput{"Enter Emplayee No:"
2) ename=input("Enter Employee Name:")
'3) loat{input{"Enter Employee Salary:"))
4) eaddr=input("Enter Employee Address:")
5) married=boollinput("Emplayee Married 2[True|False}:"))
6)_print("Please Confirm Information")
7) print("Employee No:",eno)
'8) print{"Employee Name :",ename)
5) print("Employee Salary :*,esal)
110) print("Employee Address
11) print("Employee Married ? :
:\Pythan_classes>py test.py
Enter Employee No:100
Enter Employee Name:Sunny
Enter Employee Salary:1000
Enter Employee Address:Mumbai
Employee Married ?[True|False]:True
Please Confirm Information
4) https://www.youtube.com/durgasoftware@ python
Employee No : 100
Employee Name : Sunny
Employee Salary : 1000.0
Employee Address : Mumbai
Employee Married ? : True
How to read multiple values from the keyboard ina
single line:
1) a,b= fint(x) for x in input{"Enter 2 numbers ;").split()]
2) print("Product is :", a*b)
D:\Pythan_classes>py test.py
Enter 2 numbers :10 20
Product is : 200
Note: split() function can take space as seperator by default But we can pass
anything as seperator.
Q) Write a program to read 3 float numbers from the keyboard
with, seperator and print their sum
i a,b,c= [float(x) for xin input("Enter 3 float numbers :*).split(')]
2) print{"The Sumis :", aebee)
D:\Python_classes>py test. py
Enter 3 float numbers :10.5,20.6,20.1
The Sum is: 52.2
eval():
eval Function take a String and evaluate the Result.
Eg: x = eval(“10+20+30")
print(x)
Output: 60
Eg: x = evallinput("Enter Expression”)
Enter Expression: 10+2*3/4
Qutout; 11.5
evall) can evaluate the Input to list, tuple, set, etc based the provided Input.
5| https://www.youtube.com/durgasoftware@ python
Eg: Write a Program to accept list from the keynboard an the display
1) [= evalfinput(“Enter List")
2) (type(l))
3) print(!)
COMMAND LINE ARGUMENTS
+ argvis not Array it is a List. It is available sys Module.
+ The Argument which are passing at the time of execution are called Command Line
‘Arguments,
Eg: D:\Python_classes py ae 20
PX
Command Line Arguments
Within the Python Program this Command Line Arguments are available in argv. Which is
present in SYS Module.
[20 | 20 [20 |
Note: argvi0] represents Name of Program, But not first Command Line Argument.
argv[1] represent First Command Line Argument.
Program:To check type of argu from sys
import argv
print(type(ary))
D:\Python_classes\py test.py
Write a Program to display Command Line Arguments
{1) from sys import arev
2) print{"The Number of Command Line Arguments:”, len(argv))
3) print("The List of Command Line Arguments:", argv)
4) print(“Command Line Arguments one by one:”)
5) for x in argu:
print(x)
®) https://www.youtube.com/durgasoftware@ python
D:\Python_classes>py test.py 10 20 30
The Number of Command Line Arguments: 4
The List of Command Line Arguments: ‘test. py’, “10",'20','30']
Command Line Arguments one by o!
test.py
10
20
11) from sys import arev
2) sume
3) argszargv{t:
'4) for xin args. :
5) nsintix)
6) sum=sumén
7) print("The Sum:",sum)
D:\Python_classes>py test. py 10 20 30 40
The Sum: 100
Note 1: Usually space is seperator between command line arguments. If our command
line argument itself contains space then we should enclose within double quotes(but nat
single quotes)
from sysimport argv
2) printtargvi1])
B:\Python_classes>py test.py Sunny Leone
Sunny
D:\Python_classes>py test.py ‘Sunny Leone!
‘sunny
:\Python_classes>py test. py "Sunny Leone”
Sunny Leone
Note 2: Within the Python program command line arguments are available in the String
form. Based on our requirement, we can convert into corresponding type by using type
casting methods.
1) from sys import arev
2) printlargv{t}+argv[2})
|). print{int(argv{2])+int(argv{2]))
7) https://www.youtube.com/durgasoftware@ python
D:\Python_classes>py test.py 10 20
1020
30
Note 3: If we are trying to access command line arguments with aut of range index then
we will get Error.
4) from sys import argv
2), print{argv{00})
D:\Python_classes>py test. py 10 20
IndexError: list index out of range
Note; in Python there is argparse module to parse command line arguments and display
some help messages whenever end user enters wrong input.
input()
raw_input()
Command Line Arguments
Output Statement:
We can use print() function to display output.
Form-1; print() without any argument
Just it prints new line character
Form-2:
1) print{String):
2) print("Hello World")
3) We canuse escape characters also
'4) print{"Hello \n World")
5) print("Hello\tWorld")
6) We can use repetetion operator (*) in the string
7) print{10*"Hello")
'8) print{"Hello”*10)
9) We can use + operator also
("Hello+*Warld")
8) https://www.youtube.com/durgasoftware@ python
& If both arguments are String type then + operator acts as concatenation operator.
© Ifone argument is string type and second is any other type like int then we will get
Error.
© If both arguments are number type then + operator acts as arithmetic addition
operator.
Note:
11) print("Hello"+"World")
2) print("Hello","World")
HelloWorld
Hello World
Form-3: print() with variable number of arguments
21) a,b,c=10,20,30
2) print{"The Values are :",a,b,c)
Qutput; The Values are: 10 20 30
By default output values are seperated by space.if we want we can specify seperator by
using "sep" attribute
1) a,b,c=10,20,30
2) print(a,b,<,sey
3) print{a,b,c,sey
D:\Python_classes>py test.py
10,20,30
10:20:30
Form-4:print() with end attribute
1) print(“Hello*)
2), print(“Durga")
3) print{"soft")
8 | https://www.youtube.com/durgasoftware@ python
if we want output in the same line with space
2). print{"Helio” en
2) print("Durga”,end:
3) print{"Soft")
Output: Hello Durga Soft
Note: The default value for end attribute is \n, which is nothing but new line character.
Form-5: print(abject) statement
We can pass any object (like list, tuple, set etc) as argument to the print() statement.
1) t[20,20,30,40)
2) t=(10,20,30,40)
3) print(l)
\4) print(t)
Form-6: print(String, variable list)
We can use print() statement with String and any number of arguments.
a)
2)
3)
4) s2="Python"
5) print{"Hello",s,"Your Age is",a)
|6)_print{"You are teaching",s4,"and",s2)
Output;
Hello Durga Your Age is 48
You are teaching java and Python
Form-7: print (formatted string)
i) %1 int
2) %d Pint
3) %f > float
4) %s > String type
Syntax: print("formatted string" %{variable list))
10) https://www.youtube.com/durgasoftware@ python
a=10
b=20
30
prink("a value is 261" 96a)
print("b value is %d and ¢ value is %d" %(b,¢))
Qutput
avalue is 10
b value is 20 and c value is 30
fez
31) s="Durga"
2) list=(10,20,30,40]
3) print{"Hello %s ...The List of Items are %s" %(s,list))
Output: Hello Durga ...the List of Items are [10, 20, 30, 40]
Form:8: print() with replacement operator {)
fe:
ef="Sunny"
print{"Hello {0} your salary is {1} and Your Friend {2} is waiting”.
format(name,salary,gf))
print("Hello {x} your salary is {y} and Your Friend {z} is waiting".
format(x=name,y=salary.2=f))
Output
Hello Durga your salary is 10000 and Your Friend Sunny is waiting
Hello Durga your salary is 10000 and Your Friend Sunny is waiting
11) https://www.youtube.com/durgasoftware@ python
Flow control describes the order in which statements
Transfer
Statements Statements.
1) break
2) continue
3) pass
1) if
2) if-elif
3) if-elif-else
|. Conditional Statements
1)if
if condition : statement
oR
if condition :
statement-1
statement-2
statement-3
If condition is true then statements will be executed.
t("Enter Name:")
‘durga” :
Hello Durga Good Morning”)
4) print("How are yout!!")
D:\Python_classes>py test.py
Enter Name:durga
Hello Durga Good Morning
How are you!
2 executed at runtime.
Iterative
Statements
1) for
2) while
3) https://www.youtube.com/durgasoftware@ python
D:\Python_classes>py test.py
Enter
Name: Ravi
How are you!
condition:
Action-1
else:
Action-2
if condition is true then Action-1 will be executed otherwise Action-2 will be executed,
A)
2)
'3)
4)
5)
6)
name=input(“Enter Name:*)
‘if name=="durga™ :
print("Hello Durga Good Morning")
else:
print("Hello Guest Good Moring")
print{"How are youll!”
D:\Python_classes>py test.py
Enter
Hello
Name:durga
Durga Good Morning
How are you!!!
D:\Pythan_classes>py test.py
Enter
Hello
Name:Ravi
Guest Good Maring
How are you!!!
3) if-elif-else:
if
condition1:
Action-1
elif condition2:
Action-2
‘elif condition3:
Default Action
Based condition the corresponding action will be executed.
4) https://www.youtube.com/durgasoftware@ python
2) jput("“Enter Your Favourite Brand:")
2) i "RC":
3) itis childrens brand”)
4) KF":
5) not that much kick")
6) FO":
7) _ print("Buy one get Free One")
8) else:
8) print("Other Brands are not recommended")
D:\Pythan_classes>py test.py
Enter Your Favourite Brand:RC
It is childrens brand
D:\Python_classes>py test.py
Enter Your Favourite Brand:KF
It is not that much kick
D:\Python_classes>py test. py
Enter Your Favourite Brand: KALYANI
Other Brands are not recommended
Note:
1) else partis always optional. Hence the following are various possible syntaxes,
1) If
2) if-else
3) if-elif-else
4) it-elif
2) There is na switch statement in Python
Q) Write a Program to find Biggest of given 2 Numbers from the
Commad Prompt?
|1)_ni=int{input("Enter First Number:"))
2) n2cint(input("Enter Second Number:"))
3) ifnton2:
4) _ print("Biggest Number is:",ni)
5) el
6) _ print("Biggest Number is:",n2)
D:\Python_classes>py test.py
Enter First Number:10
Enter Second Number:20
Biggest Number is: 20
5) https://www.youtube.com/durgasoftware