Python Features
Python Features
Python Features
Note:
Surprisingly Python is older than Java, java script and R.
Why is it called Python? When he began implementing Python, Guido van
Rossum was also reading Python's Flying
Python Features:
Python provides lots of features that are listed below.
Literal Constants:
in the program. Constant is a fixed value that does not change. Let us see
Number and string constants in C.
Numbers:
decimal point.
Complex numbers have real ,imaginary part like a+bj
Eg:1+5j ,7-8J
Complex numbers are identified by the word by complex.
Note: Commas are not allowed in numerical. Eg: 3,567 -8,90876 are
invalid numbers.
No size limit for integer number that can be represented in python but
floating point number have a range of 10-323 to 10308 with 15 digits
precision.
Issues with floating point numbers:
Arithmetic Overflow Problem: It occurs when a result is too large in
size to be represented. Eg: 2.7e200*4.3e200 you will get infinity.
Arithmetic Underflow Problem: It occurs when a result is too small in
size to be represented. Eg: 2.7e-200/4.3e200 you will get infinity.
Loss of precision: Any floating number has a fixed range and precision,
the result is just approximation of actual or true value. Slight loss in
accuracy is not a concern in practically but in scientific computing ,it is
an issue.
Strings
A string is a group of characters.
Using Single Quotes ('): For example, a string can be written as 'HELLO'.
Using Double Quotes ("): Strings in double quotes are exactly same as those in
single quotes. Therefore, 'HELLO' is same as "HELLO".
Using Triple Quotes (''' '''): You can specify multi-line strings using triple
quotes. You can use as many single quotes and double quotes as you want in a
string within triple quotes.
Examples:
Escape Sequences
Some characters (like ", \) cannot be directly included in a string. Such
characters must be escaped by placing a backslash before them.
Example:
\\Vmeg\\
Output:Welocme to \Vmeg\
\ \
Output:Welcom to Vmeg
Output:
The tr
Output:Hello
How are
You?
How are
Output:Hello
How are
You?
2) Triple quotes can be used for printing a single quotes or double quotes
llo
How are
Output:Hello
You?
Output:Hello
You?
String Formatting:
) left justification
o/p:
H E L L O
Rightt justification(>)
H E L L O
Central Justification ( ^)
H E L L O
By using format function, we can fill the width with other characters also
Ex
Identifiers:
An identifier is a name used to identify a variable, function, class, module, or
object.
In Python, an identifier is like a noun in English.
Identifier helps in differentiating one entity from the other. For
example, name and age which speak of two different aspects are
called identifiers.
Python is a case-sensitive programming language. Means, Age and age are two
different identifiers in Python.
Let us consider an example:
Name = "VMEG"
name = "VMEG"
Here the identifiers Name and name are different, because of the difference in
their case.
Below are the rules for writing identifiers in Python:
1. Identifiers can be a combination of lowercase letters (a to z) or uppercase
letters (A to Z) or digits (0 to 9) or an underscore ( _ ).
Eg: myClass, var_1, print_this_to_screen, _number are
valid Python identifiers.
2. An with a digit.
Eg: 1_variable is invalid, but variable_1 is perfectly fine.
3.Keywords cannot be used as identifiers. (Keywords are reserved words
in Python which have a special meaning).
Eg: Some of the keywords are def, and, not, for, while, if, else and so on.
UNDERSTANDING VARIABLES:
For example in the below code snippet, age and city are variables which store
their respective values.
age = 21
city = "Tokyo"
For example :
marks = 100 # Here marks is the variable and 100 is the value assigned to it.
Python interpreter automatically determines the type of the data based on the
data assigned to it.
Note: Henceforth, where ever we say Python does this or that, it should be
understood that it is the Python interpreter (the execution engine) which we are
referring to.
In Python, we can even change the type of the variable after they have been set
once (or initialized with some other type). This can be done by assigning a value
of different type to the variable.
A variable in Python can hold any type of value
like 12 (integer), 560.09 (float), "Vmeg" (string) etc.
Associating a value with a variable using the assignment operator (=) is called
as Binding.
Let us assign the variables value1 with 99, value2 with "Hello Python"
and value3 with "Hello World", and then print the result.
99
Hello Python
Hello World
#python program
Value1=99
print(Value1)
print(Value2)
print(Value3)
ASSIGNMENT OF VARIABLES:
The operand to the left of the = operator is the name of the variable and the
operand (or expression) to the right of the = operator is the value stored in the
variable.
In the above example 100, 1000.50, and "John" are the values assigned to the
variables counter, miles, and name respectively.
Expected Output:
Miles:·3.7282260000000003
Here an integer object is created with the value 100, and all the three
variables are references to the same memory location. This is called chained
assignment.
We can also assign multiple objects to multiple variables, this is called multiple
assignment.
Here the integer object with value 1 is assigned to variable value1, the float
object with value 2.5 is assigned to variable value2 and the string object with
the value "Ram" is assigned to the variable value3.
Write a program to assign the integer 999, float 24.789 and string "Python
Interpreter" to three variables using multiple assignment and print them
individually.
CHAINED ASSIGNMENT:
At the time of execution, the program should print message on the console as:
Enter a value:
Note: Let us assume that input() is used to read values given by the user. We
will learn about input() later sections.
Here,
a = b = c = str
Python enables us to check the type of the variable used in the program.
Python provides us the type() function which returns the type of the variable
passed.
Consider the following example to define the values of different data types and
checking its type.
1. A=10
2. b="Hi Python"
3. c = 10.5
4. print(type(a));
5. print(type(b));
6. print(type(c));
Output:
<type 'int'>
<type 'str'>
<type 'float'>
A variable can hold different types of values. For example, a person's name
must be stored as a string whereas its id must be stored as an integer.
Python provides various standard data types that define the storage method on
each of them. The data types defined in Python are given below.
1. Numbers
2. String
3. List
4. Tuple
5. Dictionary
Python Keywords
Python Keywords are special reserved words which convey a special meaning to
the compiler/interpreter. Each keyword have a special meaning and a specific
operation. These keywords can't be used as variable. Following is the List of
Python Keywords.
Comments:
A computer program is a collection of instructions or statements.
1. Comments
2. Whitespace characters
3. Tokens
In Python, to read the input from the user, we have an in-built function
called input().
The print() function converts those expressions into Strings and write
the result to standard output which then displays the result on Screen.
a = 10
b = 50
print("A value is", a, "and", "B value is", b) # will print output as follows
A value is 10 and B value is 50
The above print() statement consists of both strings and integer values.
At the time of execution, the program should print the message on the
console as:
Enter Language:
o Arithmetic operators
o Comparison operators
o Assignment Operators
o Logical Operators
o Unary operators
o Bitwise Operators
o Membership Operators
o Identity Operators
1.Arithmetic Operators:
2.Comparison Operators:
Comparison operators are used to comparing the value of the two operands
and returns boolean true or false accordingly. The comparison operators are
described in the following table a=5,b=6
3. Assignment operators
The assignment operators are used to assign the value of the right expression
to the left operand. The assignment operators are described in the following
table.
Operator Description
= It assigns the the value of the right expression to the left operand.
+= It increases the value of the left operand by the value of the right
operand and assign the modified value back to left operand. For
example, if a = 10, b = 20 => a+ = b will be equal to a = a+ b and
therefore, a = 30.
-= It decreases the value of the left operand by the value of the right
operand and assign the modified value back to left operand. For
example, if a = 20, b = 10 => a- = b will be equal to a = a- b and
therefore, a = 10.
*= It multiplies the value of the left operand by the value of the right
operand and assign the modified value back to left operand. For
example, if a = 10, b = 20 => a* = b will be equal to a = a* b and
therefore, a = 200.
%= It divides the value of the left operand by the value of the right
operand and assign the reminder back to left operand. For example, if
a = 20, b = 10 => a % = b will be equal to a = a % b and therefore, a =
0.
**= a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b will
assign 4**2 = 16 to a.
4. Logical Operators:
The logical operators are used primarily in the expression evaluation to make a
decision. Python supports the following logical operators.
Operator Description
And If both the expression are true, then the condition will be true. If a
and b are the two expressions, a true, b true => a and b
true.
Not If an expression a is true then not (a) will be false and vice versa.
5. Unary Operators:
b = 10 a = -(b)
The bitwise operators perform bit by bit operation on the values of the two
operands.
Operator Description
& (binary If both the bits at the same place in two operands are 1, then 1 is
and) copied to the result. Otherwise, 0 is copied.
| (binary or) The resulting bit will be 0 if both the bits are zero otherwise the
resulting bit will be 1.
^ (binary The resulting bit will be 1 if both the bits are different otherwise
xor) the resulting bit will be 0.
~ (negation) It calculates the negation of each bit of the operand, i.e., if the bit
is 0, the resulting bit will be 1 and vice versa.
<< (left The left operand value is moved left by the number of bits
shift) present in the right operand.
>> (right The left operand is moved right by the number of bits present in
shift) the right operand.
For example,
1. if a = 7;
2. b = 6;
3. then, binary (a) = 0111
4. binary (b) = 0011
5. hence, a & b = 0011 (3 in decimal number)
6. a | b = 0111 (7 in decimal number)
7. a ^ b = 0100 (4 in decimal number)
8. ~ a = 1000
9. a<<2=11100(28 in decimal number)
10. a>>2=0001(1 in decimal number)
Similarly 5 binary equivalent is 0101 and 3 is 0011
7. Membership Operators:
Python supports two types of membership operators in and not in. These
operators, test for membership in a sequence such as strings, lists, or tuples.
in Operator: The operator returns true if a variable is found in the specified
sequence and false otherwise.
For example,a=6
nums=[1,4,3,7,6]
a in nums returns True, if a is a member of nums.
not in Operator: The operator returns true if a variable is not found in the
specified sequence and false otherwise.
For example, a=99
Nums=[1,3,5,7,2,0]
a not in nums returns True, if a is not a member of nums otherwise returns
False.
8. Identity Operators
is Operator: Returns true if operands or values on both sides of the operator
point to the same object (Memory location)and False otherwise. For example, if
a is b returns True , if id(a) is same as id(b) otherwise returns False. id(a) gives
memory location of a
is not Operator: Returns true if operands or values on both sides of the
operator does not point to the same object(Memory location) and False
otherwise. For example, if a is not b returns 1, if id(a) is not same as id(b).
Operator Precedence
Operator Description
** The exponent operator is given priority over all the others used in
the expression.
~+- The negation, unary plus and minus.
<= < > >= Comparison operators (less then, less then equal to, greater then,
greater then equal to).
Flow chart:
Example1:
Example 2:
Write a program to find small number of two numbers
a=int(input
if(a<b):
print )
if(b<a):
)
Note: This program is an example of multiple if statements
Exercise:
1. Write a Program to find biggest number of three numbers using if
statement.
2. Write a Program to find whether the given character is vowel or didgit
using if statement.
2. if else statement:
statement. It is a two way selection statement.
Syntax:
if(expression):
statementblock1
else:
statementblock2
statementx #this statement is optional
Explanation:
In this statement first expression will be evaluated.if the expression
evaluates to true then statementblock1 under if condition executed and
executes the remaining statements of the program.
Otherwise statementblock2 under else part will be executed and executes
the remaining statements of the program.
Flow chart:
Programs:
1. Write a Program to input age and check whether the person is eligible to
vote or not
if(a<b):
print )
if(b<a):
)
3. Program to check whether the given character is vowel or not using if else
statement.
ch
if
print is
else:
print
Exercise:
1. Write a Program to check whether the given number is even number or not
2. Write a Program to input employee salary .If the employee is male(m) then
given 10% bonus otherwise give 25% bonus on salary.Display the final salary
will get by that employee.
Syntax:
if( expression1):
if(expression2):
Statementblock1
else:
Statementblock2
else:
if(expression3):
Statementblock3
else:
Statementblock4
Flow Chart:
if(a>b):
if(a>c):
else:
else:
if(b>c):
print
else:
print(c, )
2. Program to check whether the given number is zero ,positive or
negative using nested if statement concept.
if(n>=0):
if(n==0):
print(n,
else:
print(n,
else:
print(n,
Explanation:
In this the expressions are evaluated from top to bottom. Whenever the
expression evaluates true then the corresponding statement block will be
executed and come out of the if elif else statement process. If that expression is
false we move to next expression and evaluate it.if all the expressions evaluate
to false then last else part will be executed i.e. staementblockn . The statement
may have single or multiple statements.
Flow chart:
Example Programs:
1. Write a Program to check whether the given number is zero, positive or
negative using if elif else statement.
2. Write a Program to accept five subject marks and then calculate the
total,average.Display the total marks,average marks and result based on
the following criteria.
Average Result
>=70 distinction
60-70 first class
50-60 second class
40-50 third class
Answer:
c=int(
total=a+b+c+d+e
avg=total/5
elif(avg>=70):
elif(avg>=60):
elif(avg>=50):
else :
a=int(in
d=b*b-4*a*c;
if(d==0):
print
r1=-b/(2*a);
r2=r1;
print root1 value= , r2)
elif(d>0):
r1=(-b+d**0.5)/(2*a);
r2=(-b+d**0.5)/(2*a);
else:
elif(b>c):
else:
.
If it is above 100, print that
boiling point
Answer:
if(t<-273.15):
elif(t==-273.15):
elif(t==0):
else:
Exercise:
1. Write a program to display the day of a week based on number.
2. Write a program to generate electricity bill amount based on the following
constraints
Consumed Units amount
<100 Rs. 1.60/unit
100-200 Rs.2.35/unit
201-400 Rs.3.40/unit
>400 Rs.5.25/unit
3. Write a Program to input a digit and then display that digit in word using if
elif else statement.
Important Topics:
1.Expalin various conditional or selection statements(if,if else,nested if ,if elif
else statement) with an example.(Hint:For every statement,write
synatax,explanation,draw a flow chart(diagram) and small example program)
2. Programs on if else and if elif else statements.
Flow Chart:
initialization
Expression False
? Out of loop
TRUE
Statement
block
Example Programs:
1.Wrie a Program to display the 1 to 5 numbers line by line using while
loop
i=1
sum=0
while(i<=n):
sum=sum+i
i=i+1
avg=sum/n
4. Write a program to find the sum of the digits of a given number.
Input:
Enter n value 156
Output:
Sum of the digits of number 156 is 12
if(sum==t):
else:
Input:
Enter n value 156
Output:
Sum of the digits of number 156 is 12
156 is not an Armstrong number
6. Write a program to find the reverse number of a given number
Input:
Enter n value 156
Output:
The reverse number of given number 156 is 651
Exercise:
1. Write a program to check whether the given number is palindrome
number or not.
2. Write a program to check whether the given number is perfect number or
not.
(Hint:
then that number is called perfect number.Ex:6 is a input number and
are 1,2,3,6 ---6 is a perfect number because 6=1+2+3)
3. Write a program to the given decimal number into binary number using
while loop.( binary
number is 101,Hint: use %,// and denominator is 2)
4. Write a program to the given binary number into decimal number using
while loop.(
number is 5)
5. Write a Program to display all the numbers divisible by 3,divisible by 5
,divisible by both 3 and 5 from 1 to n numbers
Solutions for your reference
Solution for 3:
#Program to convert decimanl number to binary number
n=int(input("enter a decimal number"))
t=n
sum=0
i=0
while(n!=0):
r=n%2
sum=sum + r*10**i
n=n//2
i=i+1
print(t,"binary equivalent is",sum)
Input:
enter a decimal number34
Output:
34 binary equivalent is 100010
Solution for 4:
#Program to convert binary number to decimal number
n=int(input("enter a binary number"))
t=n
sum=0
i=0
while(n!=0):
r=n%10
sum=sum+ r*2**i
n=n//10
i=i+1
print(t,"decimal equivalent is",sum)
input:
enter a binary number1011
Output:
1011 decimal equivalent is 11
Note:
Syntax:
range(start,stop,step)
start:
sequence. By default its value is 0(zero)
stop:
this value will not be included in the sequence.
Step:
in sequence .Default increment value is 1.
Ex:
FOR LOOP:
Examples:
1.for i in range(1,4):
print(i)
output: 1
End
End
End
2. for i in range(1,4):
print(i)
output: 1
End
3. for i in range(-100,-95,2):
print(i)
output: -100
-98
-96
Programs:
if(c==2):
print(n,"is a prime number")
else:
print(n,"is not a prime number")
input:
enter a number 6
Output:
6 is not a prime number
n=int(input("enter a number"))
print("**********************")
for i in range(1,11):
print(n,"X",i," =",n*i)
print("**********************")
input:
enter a number 5
Output:
multiplication table of 5
**********************
5X1 =5
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
5 X 6 = 30
5 X 7 = 35
5 X 8 = 40
5 X 9 = 45
5 X 10 = 50
**********************
#1/2+2/3+3/4+..............n/n+1
n=int(input("enter n value"))
s=0
for i in range(1,n+1):
s=s+i/(i+1)
input:
enter n value 4
Output:
sum of the series is 2.716666666666667
Exercise:
1.Write a Program to check whether the given number is perfect number or not
+1/n
Nested Loops:
Python allows its users to have nested loops, that is, loops that can be placed
inside other loops. Although this feature will work with any loop like while loop
as well as for loop.
A for loop can be used to control the number of times a particular set of
statements will be executed. Another outer loop could be used to control the
number of times that a whole loop is repeated.
Examples:
1) 2)
while(condition1): while(condition1):
3) 4)
Example programs:
for i in range(1,1001):
n=i
c=0
for i in range(1,n+1):
if(n%i==0):
c=c+1
if(c==2):
print(n,"is a prime number")
2) Write a Program to check whether the given number is strong
number or not
num=int(input("enter a number"))
t=num
s=0
while(num!=0):
d=num%10
n=d
f=1
for i in range(1,n+1):
f=f*i
s=s+f
num=num//10
if(t==s):
else:
input:
enter a number 145
Output:
145 is a strong number
print( )
4) Write a Program to print the following pattern
12345
12345
12345
12345
12345
print( )
5) Write a Program to print the following pattern
11111
22222
33333
44444
55555
for i in range(1,6): #i indicates row
for j in range(1,6):
print(i,end=
print( )
print( )
Exercise:
1) Write a Program to print the following pattern
1
12
123
1234
12345
2) Write a Program to print the following pattern
1
22
333
4444
55555
3) Write a Program to print the following pattern
12345
1234
123
12
1
4) Write a Program to print the following pattern
12345
2345
345
45
5
5) Write a Program to print the following pattern
54321
5432
543
54
5
6) Write a Program to print the following pattern
54321
4321
321
21
1
""" *
* *
* * *
* * * *
"""
for i in range(1,5):
for s in range(1,5-i):
print(" ",end="")
for j in range(1,i+1):
print("*",end=" ")
print()
Output:
* *
* * *
* * * *
***********
* *
* *
* *
* *
* *
***********
*******
** *
* * *
* * *
* * *
*******
print()
* *
* * *
* * * *
* * *
* *
Break Statement:
The break statement is used to terminate the execution of the nearest enclosing
loop in which it appears. The break statement is widely used with for loop and
while loop. When interpreter encounters a break statement, the control passes
to the statement that follows the loop in which the break statement appears.
Example:
The Continue Statement
Like the break statement, the continue statement can only appear in the body
of a loop. When the interpreter encounters a continue statement then the rest
of the statements in the loop are skipped and the control is unconditionally
transferred to the loop-continuation portion of the nearest enclosing loop.
Example:
Pass Statement:
Example:
Unlike C and C++, in Python you can have the else statement associated with
a loop statements. If the else statement is used with a for loop, the else
statement is executed when the loop has completed iterating. But when used
with the while loop, the else statement is executed when the condition becomes
false.
Examples:
STRINGS
INTRODUCTION:
Python treats strings as contiguous series of characters delimited by single,
double or even triple quotes. Python has a built-in string class named "str" that
has many useful features. We can simultaneously declare and define a string
by creating a variable of string type.
name = "India"
graduate = 'N'
country = name
science
NOTE: we
Indexing:
The index of the first character is 0 and that of the last character is n-1 where
n is the number of characters in the string. If you try to exceed the bounds
(below 0 or above n-1), then an error is raised.
Traversing a String:
Example2:
for I in Message:
Output:
WELCOME
Python strings are immutable which means that once created they cannot be
changed. Whenever you try to modify an existing string variable, a new string is
created.
Example:
Built-in String Methods and Functions
Slice Operation
A substring of a string is called a slice. The slice operation is used to refer to
sub-parts of sequences and strings. You can take subset of string from original
string by using [ ] operator also known as slicing operator.
Examples:
In the slice operation, you can specify a third argument as the stride, which
refers to the number of characters to move forward after the first character is
retrieved from the string. By default the value of stride is 1, so in all the above
examples where he had not specified the stride, it used the value of 1 which
means that every character between two index numbers is retrieved.
Example:
Write a program that asks the user to enter a string. The program should
print the following:
(c) The first character of the string (remember that string indices start at 0)
(g) The seventh character of the string if the string is long enough and a error
message otherwise
(h) The string with its first and last characters removed(use slice operation)
replaced with an
Ans:
s=input("Enter a String")
l=len(s)
print("string",s,"repeated 10 times:",s*10)
if(l<7):
else:
print("String",s,"after removing first and last characters:",s[1:l-1]) #here l is the length of the string
for i in s:
s=s.replace(i," -")
for i in s:
s=s.replace(i," ")
print("String \" ",os," \"after repalcing every letter by space:",s)
ord() function returns the ASCII number of the character and chr() function
returns character represented by a ASCII number.
Examples:
2.
Programs:
BB
CCC
DDDD
EEEEE
2. Write a Program to display the following pattern
AB
ABC
ABCD
ABCDE
in and not in operators can be used with strings to determine whether a string
is present in another string. Therefore, the in and not in operator are also
known as membership operators.
Examples:
Comparing Strings
String is a sequence type (sequence of characters). You can iterate through the
string using for loop.
Examples:
Programs:
Ans:
s=input("enter a string")
if(s==rs):
else:
Output:
enter a stringmadam
s=input("enter a sentence")
noa=nod=nos=0
s=input("enter a sentence")
noa=nod=nos=0
for i in s:
if(i.isalpha()):
noa=noa+1
elif(i.isdigit()):
nod = nod+1
else:
nos=nos+1
Output:
import string
Examples:
print(string.ascii_letters)
Output:
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
Some functions:
PYTHON PROGRAMMING
Data Structure
A data structure is a group of data elements that are put together under one name.
Data structure defines a particular way of storing and organizing data in a computer so that it
can be used efficiently.
Data Structure: Sequence
A sequence is a data type that represents a group of elements. The purpose of any
sequence is to store and process group elements. In python, strings, lists, tuples and
dictionaries are very important sequence data types.
LIST:
A list is similar to an array that consists of a group of elements or items. Just like an
array, a list can store elements. But, there is one major difference between an array and a list.
An array can store only one type of elements whereas a list can store different types of
elements. Hence lists are more versatile and useful than an array.
Creating a List:
Creating a list is as simple as putting different comma-separated values between
square brackets.
We can create empty list without any elements by simply writing empty square
brackets as: student=[ ]
We can create a list by embedding the elements inside a pair of square braces []. The
elements in the list should be separated by a comma (,).
Accessing Values in list:
To access values in lists, use the square brackets for slicing along with the index or
indices to obtain value available at that index. To view the elements of a list as a whole, we
can simply pass the list name to print function.
Ex:
print student
print student[0] # Access 0th element
print student[0:2] # Access 0th to 1st elements
print student[2: ] # Access 2nd to end of list elements
print student[ :3] # Access starting to 2nd elements
print student[ : ] # Access starting to ending elements
print student[-1] # Access last index value
print student[-1:-7:-1] # Access elements in reverse order
Output:
Mothi
84
Output:
12345
Deleting an element from the list can be done using statement. The del statement
takes the position number of the element to be deleted.
Example:
lst=[5,7,1,8,9,6]
del lst[3] # delete 3rd element from the list i.e., 8
print lst # [5,7,1,9,6]
If we want to delete entire list, we can give statement like del lst.
Concatenation of Two lists:
We can simply use operator on two lists to join them. For example, and are
two lists. If t
Example:
x=[10,20,32,15,16]
y=[45,18,78,14,86]
print x+y # [10,20,32,15,16,45,18,78,14,86]
Repetition of Lists:
We can repeat the elements of a list number of times using operator.
x=[10,54,87,96,45]
print x*2 # [10,54,87,96,45,10,54,87,96,45]
Membership in Lists:
We can check if an element is a member of a list by using and operator. If
True otherwise returns False. If
True otherwise returns False.
Example:
x=[10,20,30,45,55,65]
a=20
print a in x # True
a=25
print a in x # False
a=45
print a not in x # False
a=40
print a not in x # True
Aliasing and Cloning Lists:
Giving a new name to an existing list is called The new name is called
To provide a new name to this list, we can simply use assignment operator (=).
Example:
x = [10, 20, 30, 40, 50, 60]
y=x # x is aliased as y
print x # [10,20,30,40,50,60]
print y # [10,20,30,40,50,60]
x[1]=90 # modify 1st element in x
print x # [10,90,30,40,50,60]
print y # [10,90,30,40,50,60]
In this case we are having only one list of elements but with two different names
cloning
we can take help of the slicing operation [:].
Example:
x = [10, 20, 30, 40, 50, 60]
y=x[:] # x is cloned as y
print x # [10,20,30,40,50,60]
print y # [10,20,30,40,50,60]
x[1]=90 # modify 1st element in x
print x # [10,90,30,40,50,60]
print y # [10,20,30,40,50,60]
The lists and are independent lists. Hence, any modifications to will not affect
and vice versa.
Basic List Operations
List Methods:
Nested Lists:
A list within another list is called a nested list. We know that a list contains several
elements. When we take a list as an element in another list, then that list is called a nested list.
Example:
a=[10,20,30]
b=[45,65,a]
print b # display [ 45, 65, [ 10, 20, 30 ] ]
print b[1] # display 65
print b[2] # display [ 10, 20, 30 ]
print b[2][0] # display 10
print b[2][1] # display 20
print b[2][2] # display 30
for x in b[2]:
print x, # display 10 20 30
Nested Lists as Matrices:
Suppose we want to create a matrix with 3 rows 3 columns, we should create a list
with 3 other lists as:
mat = [ [ 1, 2, 3 ] , [ 4, 5, 6 ] , [ 7, 8, 9 ] ]
print( )
for i in range(3):
for j in range(3):
print( )
M.A.RANJITH KUMAR Page 3.6
PYTHON PROGRAMMING
Output:
One of the main use of nested lists is that they can be used to represent matrices. A
matrix represents a group of elements arranged in several rows and columns. In python,
matrices are created as 2D arrays or using matrix object in numpy. We can also create a
matrix using nested lists.
Output:
print ( )
Output:
List Comprehensions:
List comprehensions represent creation of new lists from an iterable object (like a list,
set, tuple, dictionary or range) that satisfy a given condition. List comprehensions contain
very compact code usually a single statement that performs the task.
We want to create a list with squares of integers from 1 to 100. We can write code as:
squares=[ ]
for i in range(1,11):
squares.append(i**2)
The p
[ 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 ]
The previous code can rewritten in a compact way as:
squares=[x**2 for x in range(1,11)]
This is called list comprehension. From this, we can understand that a list
comprehension consists of square braces containing an expression (i.e., x**2). After the
expression, a fro loop and then zero or more if statements can be written.
[ expression for item1 in iterable if statement1
for item1 in iterable if statement2
for item1 in iterable if statement3
Example:
Even_squares = [ x**2 for x in range(1,11) if x%2==0 ]
It will display the list even squares as list.
[ 4, 16, 36, 64, 100 ]
Looping in Lists
Python's for and in constructs are extremely useful especially when working with lists. The
for var in list statement is an easy way to access each element in a list (or any other
sequence). For example, in the
following code, the for loop is used to access each item in the list.
List=[22,33,11,9,77]
for i in list:
print(i)
Output:
[22,33,11,9,77]
Output:
Index=0 value=1
Index=1 value=2
c=c+1
print("no of evens in list=",c)
2.Write a Program to define a list of countries as BRICS member and check whether give
country is a member or not.
3.Write a program to create a list of numbers from 1 to 100 and then delete all the even
numbers from list and finally display it.
4.Write a Program to input a list and value to be searched in the list.If value is found print it
Example-2:
A={1,2,3}
del(A[1])
print(a)
Output:
TypeError
However, you can always delete the entire tuple by using the statement.
Note that this exception is raised because you are trying print the deleted
element.
Operations on tuple:
Nested Tuples:
Python allows you to define a tuple inside another tuple. This is called a
nested tuple.
for i in students:
print( i)
Output:
Lab Program:
Write a python program to demonstrate various operations on tuples.
#various operations on tuples
t1=(1,2,4,3)
t2=(1,"abc",2.6)
print("length lof t1=",len(t1))
print("concatnation of t1,t2:",t1+t2)
print("Repetition of t2:",t2*2)
print("maximum of t1:",max(t1))
print("minimum of t1:",min(t1))
print("count of 2 in t1:",t1.count(2))
print("index of 9 in t2:",t2.index(2.6))
print("sorted of t1 in order:",sorted(t1))
Output:
length lof t1= 4
concatnation of t1,t2: (1, 2, 4, 3, 1, 'abc', 2.6)
Repetition of t2: (1, 'abc', 2.6, 1, 'abc', 2.6)
maximum of t1: 4
minimum of t1: 1
count of 2 in t1: 1
index of 9 in t2: 2
sorted of t1 in order: [1, 2, 3, 4]
2.Write a Program to find the second largest and smallest number in a tuple
T=(3,2,4,1,5,0)
C=soreted(T)
Example:
print(s
Creating an empty is possibly through only set( ) function.
Example:
S=set( ) # S is empty set
print(S) # displays set ( )
Even if we write duplicates in the set,but set does not contain duplicates.
Example:
S={1,2,1,2,3}
print(S) # {1,2,3}
print s
We can also convert tuple or string into set.
tup= ( 1, 2, 3, 4, 5 )
print( set(tup)) # {1, 2, 3, 4, 5 }
str=
print (set(str) ) 'i', 'n', 'a' }
Operations on set:
Some operations on set
S.n Operation Descripti Example Output
o on
1 len(A) number of elements in set A={1,2} 2
A(cardinality) B={2,3,4,5}
len(A)
2 x in A test x for membership in A X=9 False
X in A
error.
Note:
To create an empty set you cannot write s={}, because python will make
this as a
directory. Therefore, to create an empty set use
set( ) function. s=set( ) s={}
print( type(s)) # display <type set > print (type(s) )#
display <type dict >
Updating a set:
Since sets are unordered, indexing has no meaning. Set operations do
not allow users to access or change an element using indexing or slicing.
Example:
for I in S:
p #1aabc2.6(unordered output)
Output:
A Set= {1, 2}
B Set= {2, 3, 4, 5}
length lof A= 2
maximum of B: 5
minimum of A: 1
A union B = {1, 2, 3, 4, 5}
A intersection B= {2}
A difference B= {1}
A symmetric difference B= {1, 3, 4, 5}
A is subset of B: False
A is superset of B: False
After Adding new element 9 to set A: {1, 2, 9}
After Deleting 4 from set B {2, 3, 5}
Dictionary Methods:
Method Description Example
d.clear() Removes all key-value pairs from dict= { : 556,
. : Kothi , : }
d= { : 556,
: Kothi , : }
d.clear() # { }
d2=d.copy( ) into a c=dict.copy()
new dictionary d2. print(c) #{'Branch': 'CSE', 'Name':
'Kothi', 'Regd.No': 556}
Returns the value associated with
d.get(key ) . If key is notfound, it
returns None(Nothing).
Returns an object that contains dict.items( )
d.items( ) key- . The pairs #{'Branch': 'CSE', 'Name': 'Kothi',
are stored as tuples in the object. 'Regd.No': 556}
d.keys( ) Returns a sequence of keys from dict.keys( )
. # dict_keys(['Regd.No', 'Name',
'Branch'])
d.values( ) Returns a sequence of values from dict.values( )
. # dict_values([556, 'Kothi', 'CSE'])
d.update(x) Adds all elements from dictionary c={"Gender":"Male"}
. dict.update(c )
# {'Regd.No': 556, 'Name': 'Kothi',
'Branch': 'CSE', 'Gender': 'Male'}
Nested dictionaries:
Dictionary contains another dictionary within it called Nested Dictionary.
Q) Lab program 1
Write a python Program to demonstrate various dictionary operations
d= {"Regd.No": 556,"Name":"Kohli","Branch":"CSE" }
]=",d["Regd.No"])
]=",d["Name"])
]=",d["Branch"])
print("Number of key value pairs in dictionary d=", len(d))
d["Gender"]="Male"
print ("dictionary d=",d)
del(d["Regd.No"])
print("dictionary d=",d)
print("\"Name\" in d=","Name" in d)
c=d.copy()
print("After copying dictionary d to c=",c)
M.ANAND RANJITH KUMAR
print("value of key Name=",d.get("Name"))
print("Items of dictionary d=",d.items())
print("Keys of dictionary d=",d.keys( ))
print("Values of dictionary d=",d.values( ))
e={"Marks":94}
d.update(e)
print("After Updating dictionary d=",d)
Output:
]= 556
]= Kohli
]= CSE
Number of key value pairs in dictionary d= 3
dictionary d= {'Regd.No': 556, 'Name': 'Kohli', 'Branch': 'CSE',
'Gender': 'Male'}
dictionary d= {'Name': 'Kohli', 'Branch': 'CSE', 'Gender': 'Male'}
"Name" in d= True
After copying dictionary d to c= {'Name': 'Kohli', 'Branch': 'CSE',
'Gender': 'Male'}
value of key Name= Kohli
Items of dictionary d= dict_items([('Name', 'Kohli'), ('Branch',
'CSE'), ('Gender', 'Male')])
Keys of dictionary d= dict_keys(['Name', 'Branch', 'Gender'])
Values of dictionary d= dict_values(['Kohli', 'CSE', 'Male'])
After Updating dictionary d= {'Name': 'Kohli', 'Branch': 'CSE', 'Gender': 'Male',
'Marks': 94}
Output:
how many user names u want3
enter user namereyan
enter password20915
enter user namevihan
enter password182017
enter user nameranjith
enter password3282
{'reyan': '20915', 'vihan': '182017', 'ranjith': '3282'}
enter user namereyan
enter passwordabc
invalid password
Output:
d={561:"a",562:"b",563:"c",564:"d",565:"e",566:"f",567:"g",568:"h",569:"i",570:"j"}
pas
else:
else:
Output:
First, a list is an ordered set of items. But, a dictionary is a data structure that is
used for matching one item(key) with another (value).
M.ANAND RANJITH KUMAR
Second, in lists, you can use indexing to access a particular item. But, these
indexes should be a number. In dictionaries, you can use any type (immutable)
of value as an index.
For example, when we write Dict['Name'], Name acts as an index but it is not a
number but a string.
Third, lists are used to look up a value whereas a dictionary is used to take one
value and look up another value. For this reason, dictionary is also known as a
lookup table.
Fourth, the key-value pair may not be displayed in the order in which it was
specified while defining the dictionary.
Additional Topics:
Converting Lists into Dictionary:
When we have two lists, it is possible to convert them into a
dictionary. For example, we have two lists containing names of countries
and names of their capital cities.
There are two steps involved to convert the lists into a dictionary. The
zip class object by passing the two lists to zip( )
function. The zip( ) function is useful to convert the sequences into a zip
class object. The second step is to convert the zip object into a dictionary by
using dict( ) function.
Example:
countries = [ 'USA', 'INDIA', 'GERMANY', 'FRANCE' ]
cities = [ 'Washington', 'New Delhi', 'Berlin', 'Paris' ]
z=zip(countries, cities)
d=dict(z)
print d
Output:
{'GERMANY': 'Berlin', 'INDIA': 'New Delhi', 'USA': 'Washington', 'FRANCE':
'Paris'}
s="Vijay=23,Ganesh=20,Lakshmi=19,Nik
hil=22" s1=s.split(',')
s2=[]
d={}
for i in s1:
9)isaplha()
10)isdidigit()
11)isalnum()
12)isupper()
13)islower()
14)isspace()
15) find(x)
16)upper()
17)lower()
18)split()
19)join()
20)reverse()
List Ordered mutable Yes yes Yes 1) len()
collection 2)max()
of elements 3)min()
Ex: 4)count(x)
L=[1,2,3] 5)index(x)
6)concatenation(+)
7)repetition(*)
8)membership
operators(in,not
in)
9)append(x)
M.ANAND RANJITH KUMAR
10)remove(x)
11)copy()
12)reverse()
13)
insert(index,value)
14)sort()
tuple Read only Immutabl Yes yes Yes 1) len()
version of e 2)max()
list 3)min()
Ex:t=(1,2,3) 4) membership
operators(in,not
in)
5)
concatenation(+)
6)repetition(*)
7)count(x)
8)index(x)
9)sorted(tuple)
10)converting list to
tuple
tuple([1,2,3])
FUNCTIONS
So far we have written programs to solve small problems. When we want to solve
large or complex problems, our program may contain more statements means the
length of the program (size of the program) increases. This causes the following
drawbacks
Drawbacks or Disadvantages:
Program size is big (number of statements are more).
Understanding of the program logic is difficult.
Identifying the mistakes in the program also difficult.
Same code of the program (statements) may be repeated.
To overcome the above drawbacks, instead of writing a big program for large
or complex problems. We divide the actual program into sub programs. The
process of dividing the program in to subprograms is called modularization
and this approach is called Top down approach.
Program
Standard functions
User defined functions.
M.A.RANJITH KUMAR
PYTHON PROGRAMMING
Examples:
User defined functions: These functions are created or defined by the user to solve a
problem. User can create or define own functions to solve the problems.
Examples:
Myfunction () - user can create a function like Myfucntion ().
You can define functions to provide the required functionality. Here are
simple rules to define a function in Python.
Function blocks begin with the keyword def followed by the function name
and parentheses ( ).
Any input parameters or arguments should be placed within these
parentheses. You can also define parameters inside these parentheses.
The first statement of a function can be an optional statement - the
documentation string of the function or docstring.
The code block within every function starts with a colon (:) and is indented.
The statement return [expression] exits a function, optionally passing back
an expression to the caller. A return statement with no arguments is the
same as return none.
Syntax:
def functionname (parameters):
"""function_docstring"""
function_suite
return [expression]
By default, parameters have a positional behavior and you need to inform them
in the same order that they were defined.
M.A.RANJITH KUMAR
PYTHON PROGRAMMING
Example:
def add(a,b):
"""This function sum the numbers"""
c=a+b
print c
return
Here, represents starting of function. is function name. After
this name, parentheses ( ) are compulsory as they denote that it is a function
and not a variable or something else. In the parentheses we wrote two variables
a and b parameters . A parameter is a variable
that receives data from outside a function. So, this function receives two values
-----
g()
---------
def g ( ):
-----
-----
-----
--------
M.A.RANJITH KUMAR
PYTHON PROGRAMMING
Here f() is called as calling function and g() is called as called function.
Function call
Function gets invoked when it is called. To use the function we have
to call that function. We can call the function many ways. Some ways
are
1. Using function
name.
Example: add ()
2. using function name with parameters(only
variables or constants )
Example: add (5, 6, 7)
Sub (a, b)
3. function with parameters and return value
Ex:result=fact(n)
Actual arguments and Formal Arguments
The arguments that are specified at calling a function are called Actual
arguments and the arguments that are specified at called function are called
formal arguments. Arguments are called Parameters.
Example:
def f(): # calling function
----
----
G(p) # calling function G()
----
----
------
M.A.RANJITH KUMAR
PYTHON PROGRAMMING
return expression
Expression may
contain a
variable,constant or
both
Example:
return 9
return 1.7
M.A.RANJITH KUMAR
PYTHON PROGRAMMING
a) Positional Arguments:
These are the arguments passed to a function in correct positional order.
Here, the number of arguments and their position in the function definition
should match exactly with the number and position of argument in the function
call.
def attach(s1,s2):
s3=s1+s2
print s3
This function expects two strings that too in that order only.
function attaches the two strings as s1+s2.So, while calling this function, we are
supposed to pass only two strings as: attach("New","Delhi").
The preceding statements displays the following output NewDelhi. Suppose, we passed
"Delhi" first and then "New", then the result will be: "DelhiNew". Also, if we try to pass
more than or less than 2 strings, there will be an error.
b) Keyword Arguments:
Keyword arguments are arguments that identify the parameters by their names.
For example, the definition of a function that displays grocery item and its price can
be written as:
def grocery(item, price):
At the time of calling this function, we have to pass two values and we can mention
which value is for what. For example,
Here, we are mentioning a keyword and its value and then another keyword
and its value. Please observe these keywords are nothing but the parameter
names which receive these values. We can change the order of the arguments as:
grocery(
In this way, even though we change the order of the arguments, there will not be any
problem as the parameter names will guide where to store that value.
def grocery(item,price):
print( "item=",item )
print( "price=",price)
M.A.RANJITH KUMAR
PYTHON PROGRAMMING
grocery(item="sugar",price=50.75) # keyword arguments
output:
item= sugar price= 50.75
item= oil price= 88.0
c) Default Arguments:
We can mention some default value for the function parameters in the definition.
Output:
item= sugar
price= 50.75
item= oil
price= 40.00
M.A.RANJITH KUMAR
PYTHON PROGRAMMING
to add two numbers, he/she can write:
add(a,b)
But, the user who is using this function may want to use this function to find sum of
three numbers. In that case, there is a chance that the user may provide 3 arguments
to this function as:
add(10,15,20)
Then the add( ) function will fail and error will be displayed. If the programmer want to
deve n arguments, that is also possible in python. For
this purpose, a variable length argument is used in the function definition. a variable
length argument is an argument that can accept any number of values. The variable
len * symbol before it in the function definition as:
def add(farg, *args):
farg *args represents variable length argument.
We can *args and it will store them all in a tuple.
Example:
def add(farg,*args):
sum=0
for i in args:
sum=sum+i
print "sum is",sum+farg
add(5,10)
add(5,10,20)
add(5,10,20,30)
Output:
Sum is 15
Sum is 35
Sum is 65
M.A.RANJITH KUMAR
PYTHON PROGRAMMING
is removed from memory and it is
not available.
Example-1:
def myfunction():
a=10
print "Inside function",a #display 10
myfunction()
print "outside function",a # Error, not available
Output:
Inside function 10 outside function
NameError: name 'a' is not defined
When a variable is declared above a function, it becomes global variable. Such
variables are available to all the functions which are written after it.
Example-2:
a=11
def myfunction():
b=10
print "Inside function",a #display global
var
print "Inside function",b #display local var
myfunction()
print "outside function",a # available
print "outside function",b # error
Output:
Inside function 11
Inside function 10
outside function 11 outside function
NameError: name 'b' is not defined
M.A.RANJITH KUMAR
PYTHON PROGRAMMING
that case, the function, by default, refers to the local variable and ignores the global
variable. So, the global variable is not accessible inside the function but outside of it,
it is accessible.
Example-1:
a=11
def myfunction():
a=10
print "Inside function",a # display local variable
myfunction()
print "outside function",a # display global variable
Output:
Inside function 10
outside function 11
When the programmer wants to use the global variable inside a function, he can use
the keyword global before the variable in the beginning of the function body as:
global a
Example-2:
a=11
def myfunction():
global a
a=10
print "Inside function",a # display global variable
myfunction()
print "outside function",a # display global variable
Output:
Inside function 10
outside function 10
M.A.RANJITH KUMAR
PYTHON PROGRAMMING
Example:
r=fact(n)
r=reverse(n)
M.A.RANJITH KUMAR
PYTHON PROGRAMMING
3.Write a Program to find the sum of the digits of a given number using function
def sod(n):
sum=0
while(n!=0):
d=n%10
sum=sum+d
n=n//10
return sum
r=sod(n)
4.Write a Program to find the nth term of a Fibonacci series using function
def fibonacci(n):
if(n==1):
return 0
elif(n==2):
return 1
else:
a=0
b=1
for i in range(3,n+1):
c=a+b
a=b
b=c
return c
r=fibonacci(n)
print(n, Fibonacci number is ,r)
M.A.RANJITH KUMAR
PYTHON PROGRAMMING
Recursive Functions
A recursive function is defined as a function that calls itself to solve a
smaller version of its task until a final call is made which does not require a
call to itself.
Every recursive solution has two major cases, which are as follows:
base case, in which the problem is simple enough to be solved directly
without making any further calls to the same function.
in which first the problem at hand is divided into simpler
sub parts.
1.Write a Program to find the factorial of a given number using recursive function
or recursion
2. Write a Program to find the sum of the digits of a given number using recursive function
#finding the sum of the digits of a number using function
def sod(n):
if(n==0):
return 0
else:
return (n%10+sod(n//10))
M.A.RANJITH KUMAR
PYTHON PROGRAMMING
3. Write a Program to find the nth term of a Fibonacci series using recursive
function
def fibonacci(n):
if(n==1):
return 0
elif(n==2):
return 1
else:
return Fibonacci(n-1)+Fibonacci(n-2)
r=fibonacci(n)
4. Write a Program to find the reverse of a given number using recursive function
or recursion
rev=0
def reverse(n):
if(n==0):
return 0
else:
d=n%10
rev=rev*10+d
n=n//10
reverse(n)
return rev
r=reverse(n)
M.A.RANJITH KUMAR
PYTHON PROGRAMMING
def fun(x,y):
if(y==0):
return 0
else:
return x+fun(x,y-1)
print(fun(2,3))
M.A.RANJITH KUMAR
PYTHON PROGRAMMING
M.A.RANJITH KUMAR
FILES
Definition:
Second, when doing I/O using terminal, the entire data is lost when
either the program is terminated or computer is turned off.
File Path:
Example:
C:\Students\Under Graduate\BTech_CS.docx is an absolute path.
but
Types of Files:
Based on content or data of a file. Files are two types
Text files
Binary files
Text files:
Text files contain data in the form of letters,digits or special symbols
which can be read and understand by humans.
Ex: abc.txt, c7p1.c, p.py
Binary files:
Binary files contain data in the form of bits that can be easily understood
by computers and not by humans.
Ex: all audio, video, images, 1.exe,xyz.dll // exe means executable files
Example:
The readlines() method is used to read all the lines in the file.
Example:
for line in f.readlines():
print(line)
Splitting Words
Python allows you to read line(s) from a file and splits the line (treated as
a string) based on a character. By default, this character is space but
you can even specify any other character to split words in the string.
Example:
Programs:
1. Write a python program to read contents from a file and
display the contents
Source code:
f=open("python.txt","w")
f.write("this is my first file program")
f.close()
f=open("python.txt","r")
print(f.read())
f.close()
Source code:
s=0
d=0
a=0
f=open("p26.py","r")
t=f.read()
for c in t:
if(c.isdigit()):
d=d+1
elif(c.isalpha()):
a=a+1
else:
s=s+1
print("number of alphabets in a file",a)
print("number of digits in a file",d)
print("number of special characters in a file",s)
f.close()
3.
You are given a file called grades.txt, where each line of the file
contains a one-word student username and three test scores
separated by spaces, like below:.
Rathan 83 77 54
Adams 86 69 90
Write code that scans through the file and determines how
many students passed all three tests (Hint:- Pass % based on user
input).
Source code:
f=open('listfile.txt', 'r')
l=[]
c=0
for line in f:
l.append([])
l[c]=line
l[c]=l[c].split( )
c=c+1
for i in range(0,c):
c1=0
print(l[i])
for j in range(1,4):
if(int(l[i][j])>35):
c1=c1+1
if(c1==3):
print("pass")
else:
print("fail")
f.close()