Basics of Python Programming
Basics of Python Programming
Literal Constants
Numbers1
i) Integer
Example:
10
>>> type(10)
<class 'int'>
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 1
Techno Main Saltlake
ii) Floating point
Example:
3.14
>>> type(3.14)
<class 'float'>
Example:
2+4j
>>> type(2+4j)
<class 'complex'>
>>> 'hello'
'hello'
>>> "hello"
'hello'
>>> print("hello")
hello
Python concatenates two string literals that are placed side by side.
Example:
Example:
Some characters (like ‘, “”,\) connot be directly included into the string.
Example:
>>> print("aaa\nbbb\nccc")
aaa
bbb
ccc
Example:
>>> print("aaa\tbbb\tccc")
If a single backslash (\) at the end of the string is added, then it indicates that
the string is continued in the next line, but no new line is added.
Example:
>>> print("Welcome to \
Techno India")
To specify a string that should not handle any escape sequences and want to
display exactly as specified ; then the string should be specified as raw string.
Example:
The built-in function format() can be used to control the display of the string.
Example:
>>> format('hello','<10')
'hello '
>>> format('hello','>10')
' hello'
>>> format('hello','^10')
' hello '
>>> format("hello",">10")
' hello'
>>> format("hello","^10")
' hello '
Number
String
List
Tuple
Dictionary
ii) Rest of the character name can be underscore(‘_’), letter (upper or lower
case) and digits( 0 to 9).
print("i=",i,"Datatype:",type(i))
print("f=",f,"Datatype:",type(f))
print("c=",c,"Datatype:",type(c))
print("msg=",msg,"Datatype:",type(msg))
Output:
x=10
print("x=",x,type(x))
x=3.14
print("x=",x,type(x))
x=4+8j
print("x=",x,type(x))
x="hello"
print("x=",x,type(x))
Output:
x= 10 <class 'int'>
x= 3.14 <class 'float'>
x= (4+8j) <class 'complex'>
x= hello <class 'str'>
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 17
Techno Main Saltlake
Multiple Assignments
Example
>>> a=b=c=d=0
>>> print("a=",a,"b=",b,"c=",c,"d=",d)
a= 0 b= 0 c= 0 d= 0
Example
>>> a,b,c,d=10,3.14,4+5j,"xyz"
>>> print("a=",a,"b=",b,"c=",c,"d=",d)
Example
>>> print(y)
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
print(y)
NameError: name 'y' is not defined
>>> x=10
>>> print(x)
10
>>> del x
>>> print(x)
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
print(x)
Dr. Shiladitya Chowdhury,
NameError: name 'x' is not defined
Assistant Professor, Dept. of MCA, 19
Techno Main Saltlake
Multiple statements on a single line
In python we can specify more than one statements in a single line using
semicolon (;).
Example
print("Your Name:",name,"Age:",age)
Output:
Enter your Name:Raja Roy
Enter your age:35
Your Name: Raja Roy Age: 35
Comments
>>> help("keywords")
Here is a list of the Python keywords. Enter any keyword to get more help.
False class from or
None continue global pass
True def if raise
and del import return
as elif in try
assert else is while
async except lambda with
await finally nonlocal yield
break for not
Arithmetic Operators
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
// Floor Division
** Exponent
Operator Description
== Returns True if two values are exactly equal
!= Returns True if two values are not equal
> Returns True if value of the left side operand is
greater than value of the right side operand
>= Returns True if value of the left side operand is
greater than or equal to value of the right side
operand
< Returns True if value of the left side operand is less
than value of the right side operand
<= Returns True if value of the left side operand is less
than or equal to value of the right side operand
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 26
Techno Main Saltlake
>>> a=5
>>> b=3
>>> print(a==b)
False
>>> print(a!=b)
True
>>> print(a>b)
True
>>> print(a>=b)
True
>>> print(a<b)
False
>>> print(a<=b)
False
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 27
Techno Main Saltlake
Assignment Operators
Operator Description
= Assign value of the right side operand to the value of the
left side operand
+= Addition and assign
-= Subtraction and assign
*= Multiplication and assign
/= Division and assign
%= Modulus and assign
//= Floor Division and assign
**= Exponent and assign
>>> a=11
>>> b=-a
>>> print(b)
-11
>>> print(a)
11
Bitwise OR (|)
Identity Operators
is Operator
Returns True if operands or values on both sides of the operator point to the
same object and False otherwise.
is not Operator
Returns True if operands or values on both sides of the operator point to the
different object and False otherwise.
>>> id(a)
1452423568
>>> id(b)
1452423728
>>> id(c)
1452423568
>>> a is b
False
>>> a is c
True
>>> a is 20
False
>>> a is not b
True
>>> a is not c
False
>>> a is not 10
False
>>> a is not 20
True
in Operator
The operator returns True if a variable is found in the specified sequence and
False otherwise.
not in Operator
The operator returns True if a variable is not found in the specified sequence and
False otherwise.
>>> l=[10,20,30]
>>> 10 in l
True
>>> 15 in l
False
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 38
Techno Main Saltlake
>>> 10 not in l
False
>>> 15 not in l
True
>>> a=10
>>> b=12
>>> a in l
True
>>> b in l
False
>>> a not in l
False
>>> b not in l
True
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 39
Techno Main Saltlake
Operators precedence in python
The following table lists all operators from highest precedence to lowest.
Operator Description
** Exponentiation (raise to the power)
~ ,+ ,- Complement, unary plus and minus
* ,/, %, // Multiply, divide, modulo and floor division
+, - Addition and subtraction
>>, << Right and left bitwise shift
& Bitwise 'AND'
^ ,| Bitwise exclusive `OR' and regular `OR'
<= ,<, >, >= Comparison operators
<>, ==, != Equality operators
= ,%=, /=, //=, -=, +=, *=, **= Assignment operators
is, is not Identity operators
in, not in Membership operators
not, or, and Logical operators
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 40
Techno Main Saltlake
Operator precedence table is important as it affects how an expression is
evaluated.
Example:
>>> print("10"+"20")
1020
>>> print("10"+20)
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
print("10"+20)
TypeError: can only concatenate str (not "int") to str
>>> print(5*"Abcd")
AbcdAbcdAbcdAbcdAbcd
>>> print("abcd"*3)
abcdabcdabcd
>>> print("abcd"*"3")
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
print("abcd"*"3")
TypeError: can't multiply sequence by non-int of type 'str'
>>> print("abcd"*3.0)
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
print("abcd"*3.0)
TypeError: can't multiply sequence by non-int of type 'float'
Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 43
Techno Main Saltlake
Slice a String
We can extract subsets of string by using the slice operator ( [ ] and [ : ] ).
The index of first character is 0 and the index of last character is n-1; where n
is the number of characters in the string.
>>> print(s[0])
T
>>> print(s[3:8])
hno M
>>> print(s[4:])
no Main Saltlake
>>> print(len(s))
20
>>> print(s[-1])
e
>>> print(s[-17:-2])
hno Main Saltla
Lists
List consist of items separated by commas and enclosed within square brackets ( [ ] ).
The only difference in an array and list is that, array contains values of same data
type but the list can have values belonging to different types.
The index of first element of list is 0 and the index of last element is n-1; where n is
the total number of elements in the list.
>>> list1=['a','bc',10,3.14]
>>> list2=['d',75]
>>> print(list1)
['a', 'bc', 10, 3.14]
>>> print(list2)
['d', 75] Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 46
Techno Main Saltlake
>>> print(list1[0])
a
>>> print(list1[1])
bc
>>> print(list1[2])
10
>>> print(list1[3])
3.14
>>> print(list1[1:3])
['bc', 10]
>>> print(list1[2:])
[10, 3.14]
>>> print(list1+list2)
['a', 'bc', 10, 3.14, 'd', 75]
>>> list1[0]='ABC'
>>> print(list1)
['ABC', 'bc', 10, 3.14]
It is very similar to list, but the main difference between lists and tuples is that we
can change the value in a list but that is not possible in tuple.
The index of first element of tuple is 0 and the index of last element is n-1; where
n is the total number of elements in the tuple.
>>> print(tup2)
('P', 77) Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 49
Techno Main Saltlake
>>> print(tup1[0])
A
>>> print(tup1[1])
XYZ
>>> print(tup1[2])
20
>>> print(tup1[3])
11.22
>>> print(tup1[1:3])
('XYZ', 20)
>>> print(tup1[2:])
(20, 11.22)
>>> print(2*tup2)
('P', 77, 'P', 77) Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 50
Techno Main Saltlake
>>> print(tup2*3)
('P', 77, 'P', 77, 'P', 77)
>>> print(tup1+tup2)
('A', 'XYZ', 20, 11.22, 'P', 77)
>>> tup1[0]='P'
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
tup1[0]='P'
TypeError: 'tuple' object does not support item assignment
>>> d1={"A":1,"B":2,"C":3,"D":4}
>>> print(d1)
{'A': 1, 'B': 2, 'C': 3, 'D': 4}
>>> print(d1["B"])
2
>>> print(d1[1])
Traceback (most recent call last):
File "<pyshell#45>", line 1, in <module>
print(d1[1])
KeyError: 1 Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 52
Techno Main Saltlake
Functions of Type conversion
Some of the type conversion functions are as follows:
>>> x=30
>>> float(x)
30.0
>>> str(x)
'30'
>>> x=12
>>> oct(x)
'0o14'
>>> hex(x)
'0xc'
>>> bin(x)
'0b1100' Dr. Shiladitya Chowdhury,
Assistant Professor, Dept. of MCA, 54
Techno Main Saltlake