Python-Unit-1 Part2
Python-Unit-1 Part2
For example:
Program:
a=3
b = 2.65
c = 98657412345L
d = 2+5j
print ("int is",a)
print ("float ",b)
print ("long ",c)
print ("complex is",d)
Output:
int is 3
float is 2.65
long is 98657412345
complex is (2+5j)
PYTHON PROGRAMMING
Python Strings:
Strings in Python are identified as a contiguous set of characters represented in the
quotation marks. Python allows for either pairs of single or double quotes. Subsets of strings
can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of
the string and working their way from -1 at the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition
operator. For example:
Program:
str ="WELCOME"
print (str) # Prints complete string
print (str[0]) # Prints first character of the string
print (str[2:5])# Prints characters starting from 3rd to 5
print (str[2:]) # Prints string starting from 3rd character
print (str * 2) # Prints string two times
print (str + "CSE") # Prints concatenated string
Output:
WELCOME
W
LCO
LCOME
WELCOMEWELCOME
WELCOMECSE
Example:
str1="welcome"
print ("Capitalize function:",str1.capitalize())
print (str1.center(15,"*"))
print ("length is",len(str1))
print ("count function---",str1.count('e',0,len(str1)))
print ("endswith function",str1.endswith('me',0,len(str1)))
print ("startswith function",str1.startswith('me',0,len(str1)))
print ("find function---",str1.find('e',0,len(str1))
str2="welcome2017"
print "isalnum function---",str2.isalnum()
print "isalpha function---",str2.isalpha()
print "islower function---",str2.islower()
print "isupper function---",str2.isupper()
str3=" welcome"
print("lstrip ",str3.lstrip())
str4="77777777cse777777"
print("lstrip function-",str4.lstrip('7'))
print("rstrip function",str4.rstrip('7'))
print("strip function",str4.strip('7'))
str5="welcome to java"
print("replace function---",str5.replace("java","python"))
Output:
Capitalize function--- Welcome
****welcome****
length is 7
count function--- 2
endswith function--- True
startswith function--- False
find function--- 1
isalnum function--- True
isalpha function--- False
PYTHON PROGRAMMING
Python Boolean:
Booleans are identified by True or False.
Example:
Program:
a = True
b = False
print (a)
print (b)
Output:
True
False
Function Description
int(x [,base]) Converts x to an integer.
long(x [,base] ) Converts x to a long integer.
float(x) Converts x to a floating-point number.
complex(real [,imag]) Creates a complex number.
str(x) Converts object x to a string representation.
repr(x) Converts object x to an expression string.
eval(str) Evaluates a string and returns an object.
tuple(s) Converts s to a tuple.
list(s) Converts s to a list.
set(s) Converts s to a set.
dict(d) Creates a dictionary, d must be a sequence of (key, value) tuples.
frozenset(s) Converts s to a frozen set.
chr(x) Converts an integer to a character.
unichr(x) Converts an integer to a Unicode character.
ord(x) Converts a single character to its integer value.
hex(x) Converts an integer to a hexadecimal string.
oct(x) Converts an integer to an octal string.
PYTHON PROGRAMMING
Types of Operators:
Python language supports the following types of operators.
Arithmetic Operators +, -, *, /, %, **, //
Comparison (Relational) Operators = =, ! =, < >, <, >, <=, >=
Assignment Operators =, +=, -=, *=, /=, %=, **=, //=
Logical Operators and, or, not
Bitwise Operators &, |, ^, ~,<<, >>
Membership Operators in, not in
Identity Operators is, is not
Arithmetic Operators:
Some basic arithmetic operators are +, -, *, /, %, **, and //. You can apply these
operators on numbers as well as variables to perform corresponding operations.
Operator Description Example
+ Addition Adds values on either side of the operator. a + b = 30
Subtracts right hand operand from left hand
- Subtraction a – b = -10
operand.
* Multiplication Multiplies values on either side of the operator a * b = 200
Divides left hand operand by right hand
/ Division b/a=2
Operand
Divides left hand operand by right hand
% Modulus b%a=0
operand and returns remainder
Performs exponential (power) calculation on a**b =10 to
** Exponent
Operators the power 20
The division of operands where the result is
9//2 = 4 and
// Floor Division the quotient in which the digits after the
9.0//2.0 = 4.0
decimal point are removed.
Program:
a = 21
b = 10
print ("Addition is", a + b)
print "Subtraction is ", a - b
print "Multiplication is ", a * b
print "Division is ", a / b
print "Modulus is ", a % b
a=2
b=3
print "Power value is ", a ** b
a = 10
b=4
print "Floor Division is ", a // b
PYTHON PROGRAMMING
Output:
Addition is 31
Subtraction is 11
Multiplication is 210
Division is 2
Modulus is 1
Power value is 8
Floor Division is 2
Comparison (Relational) Operators
These operators compare the values on either sides of them and decide the relation
among them. They are also called Relational operators.
Operator Description Example
If the values of two operands are equal, then the
== (a == b) is not true.
condition becomes true.
If values of two operands are not equal, then
!= (a != b) is true.
condition becomes true.
(a <> b) is true. This
If values of two operands are not equal, then
<> is similar to !=
condition becomes true.
operator.
If the value of left operand is greater than the value
> (a > b) is not true.
of right operand, then condition becomes true.
If the value of left operand is less than the value of
< (a < b) is true.
right operand, then condition becomes true.
If the value of left operand is greater than or equal
>= to the value of right operand, then condition (a >= b) is not true.
becomes true.
If the value of left operand is less than or equal to
<= the value of right operand, then condition becomes (a <= b) is true.
true.
Example:
a=20
b=30
if a < b:
print "b is big"
elif a > b:
print "a is big"
else:
print "Both are equal"
Output:
b is big
PYTHON PROGRAMMING
Assignment Operators
Logical Operators
Example:
a=20
b=10
c=30
if a >= b and a >= c:
print "a is big"
elif b >= a and b >= c:
print "b is big"
else:
print "c is big"
Output:
c is big
Bitwise Operators
Operator Description Example
Operator copies a bit to the
& (a & b) = 12
result if it exists in both
Binary AND (means 0000 1100)
operands.
| It copies a bit if it exists in either (a | b) = 61
Binary OR operand. (means 0011 1101)
^ It copies the bit if it is set in one (a ^ b) = 49
Binary XOR operand but not both. (means 0011 0001)
(~a ) = -61 (means 1100 0011
~
It is unary and has the effect of in 2's complement form due to
Binary Ones
'flipping' bits. a signed binary number.
Complement
Membership Operators
Python‟s membership operators test for membership in a sequence, such as strings,
lists, or tuples.
Operator Description Example
available
Identity Operators
Identity operators compare the memory locations of two objects.
Operator Description Example
Evaluates to true if the variables on
x is y, here is results in 1 if
is either side of the operator point to the
id(x) equals id(y).
same object and false otherwise.
Evaluates to false if the variables on x is not y, here is not results
is not either side of the operator point to the in 1 if id(x) is not equal to
same object and true otherwise. id(y).
Example:
a = 20
b = 20
if ( a is b ):
print "Line 1 - a and b have same identity"
else:
print "Line 1 - a and b do not have same identity"
if ( id(a) == id(b) ):
print "Line 2 - a and b have same identity"
else:
print "Line 2 - a and b do not have same identity"
Output:
Expression:
An expression is a combination of variables constants and operators written according
to the syntax of Python language. In Python every expression evaluates to a value i.e., every
expression results in some value of a certain type that can be assigned to a variable. Some
examples of Python expressions are shown in the table given below.
Evaluation of Expressions
Expressions are evaluated using an assignment statement of the form
Variable = expression
Variable is any valid C variable name. When the statement is encountered, the
expression is evaluated first and then replaces the previous value of the variable on the left
hand side. All variables used in the expression must be assigned values before evaluation is
attempted.
Example:
a=10
b=22
c=34
PYTHON PROGRAMMING
x=a*b+c
y=a-b*c
z=a+b+c*c-a
print"x=",x
print "y=",y
print "z=",z
Output:
x= 254
y= -738
z= 1178
Decision Making:
Decision making is anticipation of conditions occurring while execution of the program
and specifying actions taken according to the conditions.
Decision structures evaluate multiple expressions which produce True or False as
outcome. You need to determine which action to take and which statements to execute if
outcome is True or False otherwise.
Following is the general form of a typical decision making structure found in most of
the programming languages:
Python programming language assumes any non-zero and non-null values as True, and
if it is either zero or null, then it is assumed as False value.
Statement Description
if statements if statement consists of a boolean expression followed by one or more
statements.
if...else statements if statement can be followed by an optional else statement, which
executes when the boolean expression is FALSE.
nested if statements You can use one if or else if statement inside another if or else if
statement(s).
PYTHON PROGRAMMING
The if Statement
It is similar to that of other languages. The if statement contains a logical expression
using which data is compared and a decision is made based on the result of the comparison.
Syntax:
if condition:
statements
First, the condition is tested. If the condition is True, then the statements given after
colon (:) are executed. We can write one or more statements after colon (:).
Example:
a=10
b=15
if a < b:
print “B is big”
print “B value is”,b
Output:
B is big
B value is 15
The if ... else statement
An else statement can be combined with an if statement. An else statement contains the
block of code that executes if the conditional expression in the if statement resolves to 0 or a
FALSE value.
The else statement is an optional statement and there could be at most only one else
statement following if.
Syntax:
if condition:
statement(s)
else:
statement(s)
PYTHON PROGRAMMING
Example:
a=48
b=34
if a < b:
print “B is big”
print “B value is”, b
else:
print “A is big”
print “A value is”, a
print “END”
Output:
A is big
A value is 48
END
Q) Write a program for checking whether the given number is even or not.
Program:
a=input("Enter a value: ")
if a%2==0:
print(" EVEN number")
else:
print(" NOT EVEN Number")
Output-1: Output-2:
Enter a value: 56 Enter a value: 27
a is EVEN Number a is NOT EVEN Number
PYTHON PROGRAMMING
Example:
a=20
b=10
c=30
if a >= b and a >= c:
print "a is big"
elif b >= a and b >= c:
print "b is big"
else:
print "c is big"
Output:
c is big
Decision Loops/Repetition Statements:
In general, statements are executed sequentially: The first statement in a function is
executed first, followed by the second, and so on. There may be a situation when you need to
execute a block of code several number of times.
Programming languages provide various control structures that allow for more
complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times.
The following diagram illustrates a loop statement:
PYTHON PROGRAMMING
Example-1: Example-2:
i=1
i=1
while i < 4:
while i < 4:
print( i)
print( i)
i=i+1
i=i+1
print (‘END’) print “END”
Output-1: Output-2:
1 1
END 2
2 3
END END
3
END
Output:
Enter the number: 5
Factorial is 120
The first element of the sequence is assigned to the variable written after „for‟ and then
the statements are executed. Next, the second element of the sequence is assigned to the
variable and then the statements are executed second time. In this way, for each element of the
sequence, the statements are executed once. So, the for loop is executed as many times as there
are number of elements in the sequence.
PYTHON PROGRAMMING
Example-1: Example-2:
for i range(1,5): for i range(1,5):
print( i) print(i)
print “END” print (‘END’)
Output-1: Output-2:
1 1
END 2
2 3
END END
3
END
Example-3: Example-4:
name= "python" for x in range(10,0,-1):
for letter in name: print( x)
print (letter)
Output-3: Output-4:
p 10 9 8 7 6 5 4 3 2 1
y
t
h
o
n
Output:
Enter the number: 5
Factorial is 120
PYTHON PROGRAMMING
Nested Loop:
It is possible to write one loop inside another loop. For example, we can write a for loop
inside a while loop or a for loop inside another for loop. Such loops are called “nested loops”.
Example-1:
for i in range(1,6):
for j in range(1,6):
print j,
print ""
Example-2:
for i in range(1,6):
for j in range(1,6):
print "*",
print ""
Example-3:
for i in range(1,6):
for j in range(1,6):
if i==1 or j==1 or i==5 or j==5:
print "*",
else:
print " ",
print ""
Example-4:
for i in range(1,6):
for j in range(1,6):
if i==j:
print "*",
elif i==1 or j==1 or i==5 or j==5:
print "*",
else:
print " ",
print ""
Example-5:
for i in range(1,6):
for j in range(1,6):
if i==j:
print "$",
elif i==1 or j==1 or i==5 or j==5:
print "*",
else:
print " ",
print ""
PYTHON PROGRAMMING
Example-6:
for i in range(1,6):
for j in range(1,4):
if i==1 or j==1 or i==5:
print "*",
else:
print " ",
print ""
Example-7:
for i in range(1,6):
for j in range(1,4):
if i==2 and j==1:
print "*",
elif i==4 and j==3:
print "*",
elif i==1 or i==3 or i==5:
print "*",
else:
print " ",
print ""
Example-8:
for i in range(1,6):
for j in range(1,4):
if i==1 or j==1 or i==3 or i==5:
print "*",
else:
print " ",
print ""
Example-9:
for i in range(1,6):
for c in range(i,6):
print "",
for j in range(1,i+1):
print "*",
print ""
Example-10:
for i in range(1,6):
for j in range(1,i+1):
print (j)
print ("")
PYTHON PROGRAMMING
Example-11:
a=1
for i in range(1,5):
for j in range(1,i+1):
print(a)
a=a+1
print( "")
1) Write a program for print given number is prime number or not,using for loop.
Program: n=int(input("Enter n "))
count=0
for i in range(2,n):
if n%i==0:
count=count+1
break
if count==0:
print("Prime Number")
else:
print ("Not Prime Number")
Output:
Enter n value: 17
Prime Number
2) Write a program print Fibonacci series and sum the even numbers. Fibonacci series
is 1,2,3,5,8,13,21,34,55
n=int(input("Enter n "))
f0=1
f1=2
sum=f1
print (f0,f1)
for i in range(1,n-1):
f2=f0+f1
print(f2)
f0=f1
f1=f2
if f2%2==0:
sum+=f2
print ("\nThe sum of even terms is", sum)
Output:
Enter n value 10
1 2 3 5 8 13 21 34 55 89
The sum of even terms is 44
PYTHON PROGRAMMING
3) Write a program to print n prime numbers and display the sum of prime numbers.
Program:
n=int(input("Enter the range: "))
sum=0
for num in range(1,n+1):
for i in range(2,num):
if (num % i) == 0:
break
else:
print (num)
sum += num
print ("\nSum of primes is",sum)
Output:
Enter the range: 21
1 2 3 5 7 11 13 17 19
Sum of prime numbers is 78
4) Using a for loop, write a program that prints out the decimal equivalents of 1/2, 1/3,
1/4, . . . ,1/10
Program:
for i in range(1,11):
print ("Decimal Equivalent of 1/",i,"is",1/float(i))
Output:
Decimal Equivalent of 1/ 1 is 1.0
Decimal Equivalent of 1/ 2 is 0.5
Decimal Equivalent of 1/ 3 is 0.333333333333
Decimal Equivalent of 1/ 4 is 0.25
Decimal Equivalent of 1/ 5 is 0.2
Decimal Equivalent of 1/ 6 is 0.166666666667
Decimal Equivalent of 1/ 7 is 0.142857142857
Decimal Equivalent of 1/ 8 is 0.125
Decimal Equivalent of 1/ 9 is 0.111111111111
Decimal Equivalent of 1/ 10 is 0.1
PYTHON PROGRAMMING
5) Write a program that takes input from the user until the user enters -1. After display
the sum of numbers.
Program:
sum=0
while True:
n=int(input("Enternumber:") )
if n==-1:
break
else:
sum+=n
print ("The sum is",sum)
Output:
Enter the number: 1
Enter the number: 5
Enter the number: 6
Enter the number: 7
Enter the number: 8
Enter the number: 1
Enter the number: 5
Enter the number: -1
The sum is 33
9) Write a program that takes input string user and display that string if string contains
at least one Uppercase character, one Lowercase character and one digit.
Program:
pwd=input("Enter the password:")
u=False
l=False
d=False
for i in range(0,len(pwd)):
if pwd[i].isupper():
u=True
elif pwd[i].islower():
l=True
elif pwd[i].isdigit():
d=True
if u==True and l==True and d==True:
print pwd.center(20,"*")
else:
print "Invalid Password"
Output-1:
Enter the password:"Mothi556"
******Mothi556******
Output-2:
Enter the password:"mothilal"
Invalid Password
PYTHON PROGRAMMING
Arrays:
An array is an object that stores a group of elements of same datatype.
Arrays can store only one type of data. It means, we can store only integer type elements
or only float type elements into an array. But we cannot store one integer, one float and one
character type element into the same array.
Arrays can increase or decrease their size dynamically. It means, we need not declare the
size of the array. When the elements are added, it will increase its size and when the
elements are removed, it will automatically decrease its size in memory.
Advantages:
Arrays are similar to lists. The main difference is that arrays can store only one type of
elements; whereas, lists can store different types of elements. When dealing with a huge
number of elements, arrays use less memory than lists and they offer faster execution than
lists.
The size of the array is not fixed in python. Hence, we need not specify how many elements
we are going to store into an array in the beginning.
Arrays can grow or shrink in memory dynamically (during runtime).
Arrays are useful to handle a collection of elements like a group of numbers or characters.
Methods that are useful to process the elements of any array are available in „array‟
module.
Creating an array:
Syntax:
arrayname = array(type code, [elements])
The type code „i‟ represents integer type array where we can store integer numbers. If
the type code is „f‟ then it represents float type array where we can store numbers with decimal
point.
Example:
The type code character should be written in single quotes. After that the elements
should be written in inside the square braces [ ] as
a = array ( „i‟, [4,8,-7,1,2,5,9] )
PYTHON PROGRAMMING
Example:
from array import *
a=array('i', [10,20,30,40,50,60,70])
print "length is",len(a)
print " 1st position character", a[1]
print "Characters from 2 to 4", a[2:5]
print "Characters from 2 to end", a[2:]
print "Characters from start to 4", a[:5]
print "Characters from start to end", a[:]
PYTHON PROGRAMMING
a[3]=45
a[4]=55
print "Characters from start to end after modifications ",a[:]
Output:
length is 7
1st position character 20
Characters from 2 to 4 array('i', [30, 40, 50])
Characters from 2 to end array('i', [30, 40, 50, 60, 70])
Characters from start to 4 array('i', [10, 20, 30, 40, 50])
Characters from start to end array('i', [10, 20, 30, 40, 50, 60, 70])
Characters from start to end after modifications array('i', [10, 20, 30, 45, 55, 60, 70])
Array Methods:
Method Description
a.append(x) Adds an element x at the end of the existing array a.
a.count(x) Returns the number of occurrences of x in the array a.
a.extend(x) Appends x at the end of the array a. „x‟ can be another array or
iterable object.
a.fromfile(f,n) Reads n items from from the file object f and appends at the end of
the array a.
a.fromlist(l) Appends items from the l to the end of the array. l can be any list or
iterable object.
a.fromstring(s) Appends items from string s to end of the array a.
a.index(x) Returns the position number of the first occurrence of x in the array.
Raises „ValueError‟ if not found.
a.pop(x) Removes the item x from the array a and returns it.
a.pop( ) Removes last item from the array a
a.remove(x) Removes the first occurrence of x in the array. Raises „ValueError‟
if not found.
a.reverse( ) Reverses the order of elements in the array a.
a.tofile( f ) Writes all elements to the file f.
a.tolist( ) Converts array „a‟ into a list.
a.tostring( ) Converts the array into a string.
PYTHON PROGRAMMING