Python Unit 1
Python Unit 1
Python:
--> Python is a widely used general purpose high level programming language.
--> Python was introduced by "Guido van Rossum" in 1991. after that python org has taken care about
this language development.
--> Connect with databases also. We can also able to make modifications to the database files.
Features of Python:
There are many features in Python, some of which are discussed below –
1. Easy to code:
Python is a high-level programming language. Python is very easy to learn the language as compared to
other languages like C, C#, Javascript, Java, etc. It is very easy to code in python language and anybody
can learn python basics in a few hours or days. It is also a developer-friendly language.
3. Object-Oriented Language:
One of the key features of python is Object-Oriented programming. Python supports object-oriented
language and concepts of classes, objects encapsulation, etc.
5. High-Level Language:
Python is a high-level language. When we write programs in python, we do not need to remember the
system architecture, nor do we need to manage the memory.
9. Interpreted Language:
Python is an Interpreted Language because Python code is executed line by line at a time. like other
languages C, C++, Java, etc. there is no need to compile python code this makes it easier to debug our
code. The source code of python is converted into an immediate form called bytecode.
1) Integer
2) Float
3) String
If you are storing a number to a variable then that variable belongs to integer data type.
EX: a=10;
If you are storing a number with some fractional part (decimal number) to a variable belongs to
float data type.
Ex: a=10.25;
Ex: a=”hello”;
If you wanted to know the type of variable we can use “type()” function.
Ex: type(a);
NOTE:
Operators:
--> Operator is nothing but a symbol which can be used for performing some operation.
1) Arithmetic operators
2) Comparison operators
3) Assignment operators
4) Logical operators
5) Bitwise operators
Arithematic operators:
+ --> addition
- --> subtraction
* --> Multiplication
/ --> divison
o/p: 50
>>> c=a+b;
o/p: 2
>>> d=a-b;
o/p: 0
Comparisonal Operators:
These operators are used for performing comparison between two operands. We also called
these as Relational operators.
== --> equalsto
Ex: first.py
a=5; b=5;
if(a==b):
else:
Assignment operators:
These operators are used for assigning something(either we can assign a value or a variable) to
the variable.
The following are the Assignment operators.
Ex: second.py
a=10
b=5
a+=b (in this line we are performing addition of a&b and the result we are assigning to a)
print(a)
o/p: 15
Logical operators:
2) or
--> When we are using and operator these the statement will execute when the both conditions are
true. "a and b"
--> If anyone are not satisfying the condition then these operator won't work.
--> Or operator can gets work if anyone among the given conditions is true.
a=15
if(a<20 or a>18): (from the given conditions a<20 is correct so if part is going to execute)
print( "TRUE")
else:
print("FALSE")
o/p: TRUE
Ex: four.py
a=15
if(a<20 and a>18): (from the given conditions a>18 is wrong so if part is not executing)
print( "TRUE")
else:
print("FALSE")
o/p: False
Bitwise operators:
--> These operators perform the operation on bits of the given data.
b) | -> bitwise or
a) & -> bitwise and: When both bits have same value then only it will execute. otherwise it won’t.
b) | -> bitwise or: Among the both operands if anyone will be true then it returns true value.
A B A|B
T T T
T F T
F T T
F F F
This operator can perform shifting the left operand bits towards the left side for the given no of
times in the right operand.
you can place 0's at right side.
Ex: 1) a= 011000
a<<2
result: 11000
2) a=1010
a<<3
result: 1010000
3) a=11100
a<<4
result: 111000000
In rightshift we are going to shift right side operand towards right side based on the value given
by the user.
In a simple words how much shifts you want to apply those no of opearnds we just need to
remove.
Ex: 1) a=1010
a>>2
result: 10
2) a=1110
a>>1
result: 111
3) a= 00110
a>>2
result:001
Output
a=5
print('The value of a is', a)
The value of a is 5
In the second print() statement, we can notice that space was added between the string and the
value of variable a. This is by default, but we can change it.
Output formatting
Sometimes we would like to format our output to make it look attractive. This can be done by
using the str.format() method. This method is visible to any string object.
>>> x = 5; y = 10
>>> print('The value of x is {} and y is {}'.format(x,y))
The value of x is 5 and y is 10
Here, the curly braces {} are used as placeholders. We can specify the order in which they are
printed by using numbers (tuple index).
Output
Python Input
To allow flexibility, we might want to take the input from the user. In Python, we have the
input()and raw_input() functions to allow this. The syntax for input() is:
1) raw_input([prompt]):
Here, we can see that the entered value 10 is a string, not a number. To convert this into a
number we can use int() or float() functions.
>>> int('10')
Control Structures:
--> Control structure is a block of code where decisions can be taken to perform certain actions.
1) Selection statements:
--> These statements are used for selecting(taking the decision) what operation need to
perform.
a) if :
--> This statement is used for checking whether the given condition is true or not.
--> if the condition true then only it will perform the operation.
synatx:
if(condition):
block of code;
a=15
b=7
if(a>b):
if(b>a):
b) if-else:
--> This also used for checking whether the given condition is true or not.
--> If the given condition is true then "if" block is going to execute.
--> If the given condition is false then "else" block is going to execute.
synatx:
if(condition):
block of code;
else:
block of code;
Ex:
a=01
b=7
if(a>b):
print("a is bigger than b")
else:
print("b is bigger than a")
c) Switch:
--> To implement switch statement we need to use the keyowrd called "switcher"
syntax:
switcher=
1: choice1
2: choice2
3: choice3
4: choice4
}
Ex:
1:'Sunday',
2:'Monday',
3:'Tuesday',
4:'Wednesday',
5:'Thursday',
6:'Friday',
7:'Saturday'
}
Friday
--> These statements are used for performing some task repeatedly for "n" number of times.
a) for
b) while
c) do-while
a) for loop:
syntax:
for i in condition:
block of statements;
Ex:1) Ex:2)
o/p: re=a*2;
b print(re)
a
n o/p: hellohello
a
n
a
syntax:
while condition:
block of statements;
Ex:1)
i=1 o/p:
while i<4: 1
2
print(i) 3
i=i+1;
3) do-while:
--> First perform the action then it will checks the condition.
syntax:
while True:
block of statements;
Ex:
i=1
print(i) 1
2
i=i+1 3
4
if(i==5):
break
--> These statements are used for controlling the flow of execution.
a) break
b) continue
c) pass
1) break:
synatax: break
Ex:
for i in range(1,10):
print(i)
if(i==5):
break
o/p:
1
2
3
4
5
2) continue:
--> This statement can just skip the execution at particular point.
syntax: continue
Ex:
continue
print(i)
o/p:
1
2
3
4
6
7
8
9
3) pass:
--> if you dont have any code to write inside of any condition or loop then we can place this
"pass" statement.
syntax: pass
Ex:1)
for i in range(1,10):
print(i)
o/p won't get for this type of empty blocks. To avoid this type of problems we are using pass.
for i in range(1,10): 1
2
print(i) 3
4
if(i==5): 5
6
pass 7
8
9
Strings:
--> In python strings are immutable. i.e., we can't able to make modifications to the string.
--> To create a sting first we need to take a variable to that variable we need to assign the value
within either single quotes or double quotes.
Ex: 1) string1="Hello"
2) string2='hi'
--> To access string characters we just need to give the string name and within the[position].
a) string1[3] b) string1[7]
--> If you want to access set of characters from the string then you need to specify the starting
index position and ending index position by placing : between the values.
c) string1[3:7] d) string1[2:9]
e) string1[-1]
o/p: 'd'
--> if you want to access the string (print the string) in reverse order.
f) string1[::-1]
string2="Welcome to my world"
--> If you want to update some content the string that should not possible the reason is strings
are immuatable.
--> If you want to update entire string(replacing with new string) then we need to assign the
new string to the old string name.
--> If you want to delete some part of the string that should not possible the reason is strings
are immutable.
--> But we can able to delete entire string by using "del" keyowrd.
a) concatination:(+)
Ex: string1="Hello"
string2="Welcome"
string3= string1+string2
print(string3)
o/p: HelloWelcome
b) multiply(*):
--> This can be used for multiply the string i.e., if you want to print the string for "n" times then
we need to use this operator.
syntax: string*n
Ex: print(string1*2)
o/p: HelloHello
1) isaplha():
--> This method can be used for checking whether the given string only consist of alphabets or
not.
--> If only alphabets are there it will return the value "True" otherwise "False".
syntax: stringname.isaplpha()
string1="Hello" string2="Hello@123"
string1.isaplha() string2.isalpha()
2) isalnum():
--> This methods can checks whether the given string consist of alphabet and numbers or not.
--> Then only it will return the value true otherwise it will return false.
syntax: stringname.isalnum()
string3.isalnum() string5.isalnum()
3) islower():
--> This method is used for checking whether the given string consist of lowercase characters
only or not.
--> If it having only lower case characters then it will return the value "True" or it will return
"False".
syntax: stringname.islower()
string6.islower() string7.islower()
--> This method can be used for checking whether the given string consist of uppercase letters
only or not.
--> If it is having only uppercase then it will return the value "True" or it will return the value
"False"
syntax: stringname.isupper()
string8.isupper() string9.isupper()
5) isspace():
--> This method can be used for checking whether the given string consist of only spaces or not.
--> If it is having only spaces then it will return the value "True" or it will return the value "False"
syntax: stringname.isspace()
string10.isspace() string11.isspace()
6) isdigit():
--> This method is used for checking whether the string consist of only digits or not.
--> If it is having only digits then it will return the value "True" or it will return the value "False"
syntax: stringname.isdigit()
string12.isdigit() string13.isdigit()
A List is created by placing all items inside the SQUARE BRACKETS “[ ]” separated by commas.
It can have any number of items and they may be of different data types.
Ex: 3) my_list = [1, "Hello", 3.4] # list with mixed data types
A list can also have another list as an item. This is called a nested list.
Ex: my_list = ["mouse", [8, 4, 6], ['a']] # nested list
1) print(my_list[0])
Output: p
2) print(my_list[2])
Output: o
3) print(my_list[4])
Output: e
2) print(n_list[1][3]) Output: 5
Negative Indexing:
1) print(my_list[-1])
Output: e
2) print(my_list[-5])
Output: p
We can access a range of items in a list by using the slicing operator “:” (colon).
1) print(my_list[2:5])
2) print(my_list[:-5])
3) print(my_list[5:])
4) print(my_list[:])
Output: ['p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z']
1) odd[0] = 1
print(odd)
Output: [1, 4, 6, 8]
2) odd[1:4] = [3, 5, 7]
print(odd)
Output: [1, 3, 5, 7]
We can delete one or more items from a list using the “del” keyword.
It can even delete the list entirely.
1) del my_list[1:5]
print(my_list)
2) del my_list
print(my_list)
List Methods:
1) append():
Adds its argument as a single element to the end of a list. The length of the list
increases by one.
1) odd.append(7)
print(odd)
Output: [1 , 3 , 5 , 7 ]
2) list2=[9,11,13]
odd.append(list2)
print(odd)
2) extend():
extend() can be used for adding each element to the list and extending the list. The
length of the list increases by number of elements in it’s argument.
list2=[7 , 9, 11]
odd.extend(list2)
print(odd)
Output: [1 , 3 , 5 , 7, 9 , 11 ]
3) insert():
insert() used for inserting items at specified location of the list.
odd.insert(1,7)
print(odd)
Output: [1, 7, 3, 5]
4) remove():
remove() can be used for removing the specified item from the list.
odd.remove(3)
print(odd)
Output: [1, 5, 7]
5) pop():
pop() can be used for removing the last item from the lsit.
odd.pop()
print(odd)
Output: [1, 3, 5]
Tuples
Creating Tuples:
A tuple is created by placing all the items (elements) inside parentheses (), separated by
commas.
A tuple can have any number of items and they may be of different types (integer, float,
list, string, etc.).
1) my_tuple= ()
print(my_tuple)
Output: ()
2) my_tuple= (1,2,3)
print(my_tuple)
Output: (1,2,3)
3) my_tuple(1,”Hello”,3.4)
print(my_tuple)
Output: (1,”Hello”,3.4)
There are various ways in which we can access the elements of a tuple.
Indexing
We can use the index operator [] to access an item in a tuple, where the index starts from 0.
Trying to access an index outside of the tuple index range(6,7,... in this example) will raise
an IndexError.
1) print(my_tuple[0])
Output: p
2) print(my_tuple[2])
Output: o
3) print(my_tuple[4])
Output: e
1) print(my_tuple[-1])
Output: e
2) print(my_tuple[-2])
Output: b
Slicing
We can access a range of items in a list by using the slicing operator “:” (colon).
1) print(my_tuple[2:5])
2) print(my_tuple[:-5])
Deleting a Tuple:
We cannot delete or remove items from a tuple because tuples are immutable.
But we can able to remove (delete) entire tuple.
Tuple Methods:
Tuples providing us the following methods:
1) count():
This method is used for returning how many times that particular element has occurred in
the tuple.
Output: 2
2) Index():
This method is used for knowing the position of particular element in the tuple.
print(my_tuple.index( ‘ p ’ ))
Output: 1
Dictionary
Ex:
In the above dictionary Dict, The keys Name and Age are the string that is an immutable object.
Output: {}
1) print(Employee*‘Name’+)
Output: John
2) print(Employee*‘salary’+)
Output: 25000
1) Employee*“Name”+=”Sreenu”
print(Employee)
1) del Employee*“Name”+
print(Employee)
1) Clear():
o This method is used for Remove all items from the dictionary.
EX: Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
Employee.clear()
print(Employee)
Output: {}
2) Items():
o This method returns all the items of the dictionary.
print(Employee.items())
Output: [('Salary', 25000), ('Company', 'Google'), ('Name', 'JHON')]
3) keys():
o This method is used for return the all keys of the dictionary.
EX: Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
print(Employee.keys())
4) pop():
o This method is used for removing a item form the dictionary which “key” has passed as
argument.
EX: Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
Employee.pop(‘Salary’)
print(Employee)
5) popitem():
o This method is used for removing an arbitrary item of the dictionary.
Employee.popitem()
print(Employee)
6) values():
o This method is used for printing all the values of the dictionary.