Python - Unit II & Basic Programs
Python - Unit II & Basic Programs
Python Operators:
1. Arithmetic operators
2. Relational or Comparison operators
3. Logical Operators
4. Assignment Operators
5. Unary Operators
6. Bitwise Operators
7. Membership operators
8. Identity operators
1. Arithmetic operators
Note:
•
In Python 2.7(version), the “/” operator works as a floor division for integer
values. However, the operator / returns a float value if one of the value is a
float.
• In Python 3(Version), ‘/’ operator does floating point division for both int and
float values.
Example
x = 15
y=4
print('x + y =',x+y)
print('x - y =',x-y)
print('x * y =',x*y)
print('x / y =',x/y)
print('x % y =',x%y)
print('x // y =',x//y)
print('x ** y =',x**y)
Comparison operators are used to compare values. It either returns True or False
according to the condition.
For example, assume a=100 and b = 200, we can use the comparison operators on
them.
>>> 7<10<15
True
>>>7<10 and
10<15
True
>>>7>5 >>>”Hello”> “Goodbye” True
> Greater than: True >>>'Goodbye'> 'Hello'
True if left >>>10<10 False
operand is False
greater than the
right
>>> 2<=5 >>>”Hello”<= “Goodbye”
<= Less than or True False
equal to: True if >>> 7<=4 >>>'Goodbye' <= 'Hello'
left operand is False True
less than or
equal to the right
>>>10>=10 >>>‟Hello”>= “Goodbye”
>= Greater than or True True
equal to: True if >>>10>=12 >>>'Goodbye' >= 'Hello'
left operand is False False
greater than or
equal to the right
>>>10!=11 >>>‟Hello”!= “HELLO”
!= Not equal to - True True
True if operands >>>10!=10 >>> “Hello” != “Hello”
are not equal False False
>>>10==10 >>>”Hello” == “Hello”
== Equal to: True if True True
both operands >>>10==11 >>>‟Hello” == “Good Bye”
are equal False False
Example
a = 13
b = 33
print(a > b)
print(a < b)
print(a == b)
print(a != b)
print(a >= b)
print(a <= b)
3. Logical Operators
Python supports three logical operators logical and, logical or and logical not. Normally,
the logical expressions are evaluated from left to right. Logical operators returns results
as either True or False.
Symb Descri
ol ption
If both the operands are true, then the condition becomes true.
and (&)
Ex: x and y
If any one of the operand is true, then the condition becomes true.
or (|)
Ex: x or y
True if operand is false (complements the operand)
Not (!)
Ex: not x
Example
x = True
y = False
print('x and y is',x and y)
print('x or y is',x or y)
print('not x is',not x)
a,b=20,30
print("(a>b) and (b>a)",(a>b) and (b>a))
print("(a>b) or (b>a)",(a>b) or (b>a))
print("not(a>b) and (b>a)",not(a>b) and (b>a))
4. Assignment Operators
Assignment operators are used in Python to assign values to variables or operands. It
is also known as shortcut operators that includes +=, -=, *=, /=, %=, //= and **= etc.
Assigned values
= from right side x=12 c=a, assigns value of
operands to left a to the variable c
variable
added and assign
+= back the result x+=2 x+=2 is same as x=x+2
to left operand
subtracted and
-= assign back the x-=2 x-=2 is same as x=x-2
result to left
operand
multiplied and
*= assign back the x*=2 x*=2 is same as x=x*2
result to left
operand
divided and assign
/= back the x/=2 x/=2 is same as x=x/2
result to left
operand
taken modulus
using two operands
%= and assign the x%=2 x%=2 is same as
result x=x%2
to left operand
performed
exponential
**= (power) x**=2 x**=2 is same as
calculation on x=x**2
operators and
assign value to
the
left operand
performed floor
division on
//= operators and x / /= 2 x//=2 is same as x=x//2
assign value to
the left operand
5. Unary Operators
Unary operators act on single operands. Python supports Unary minus operator.
An operand is preceded by a minus sign, the unary operator negates its value.
For example, if a number is positive, it becomes negative when preceded with a unary
minus operator. Similarly, if the number is negative, it becomes positive after applying
the unary minus operator.
Ex: b=10
a = - (b)
The result of the expression is a = -10, because variable b has a positive value. After
applying unary minus operator (-) on the operand b, the value becomes -10, which
indicates it as a negative value.
6. Bitwise Operators
Bitwise operators perform operations at the bit level. These operators include bitwise
AND, bitwise OR, bitwise XOR, and shift operators.
A B A&B
0 0 0
0 1 0
1 0 0
1 1 1
In the following example, we have two integer values 1 and 3 and we will perform
bitwise AND operation and display the result.
Example:
Bitwise OR
Bitwise OR | will give 0 only if both the operands are 0 otherwise, 1.
The truth table for bitwise OR.
A B A|B
0 0 0
0 1 1
1 0 1
1 1 1
In the following example we have two integer values 1 and 2 and we will perform
bitwise OR operation and display the result.
Example:
Bitwise XOR
A B A^B
0 0 0
0 1 1
1 0 1
1 1 0
In the following example we have two integer values 2 and 7 and we will perform bitwise
XOR operation and display the result.
Example
Shift Operators:
Python supports two bitwise shift operators. They are shift left (<<) and shift right
(>>). These operations are used to shift bits to the left or to the right.
• << Binary Left Shift: The left operands value is moved left by the number of
bits specified by the right operand.
Example:
a=60
a << 2
output: 240
• >> Binary Right Shift: The left operands value is moved right by the number of
bits specified by the right operand.
Example:
a=60
a >> 2
output: 15
Bitwise Operators Example
a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
c = a & b; # 12 = 0000 1100
print ("a & b ", c)
c = a | b; # 61 = 0011 1101
print ("a | b ", c)
c = a ^ b; # 49 = 0011 0001
print ("a ^ b ", c)
c = a << 2; # 240 = 1111 0000
print ("a << 2 ", c)
c = a >> 2; # 15 = 0000 1111
print ("a >> 2 ", c)
Output
a & b 12
a | b 61
a ^ b 49
a << 2 240
a >> 2 15
7. Membership operators
in and not in are the membership operators in Python. They are used to test
whether a value or variable is found in a sequence (string, list, tuple, set and
dictionary).
In a dictionary we can only test for presence of key, not the value.
Example:
x = 'Hello world'
y = {1:'a',2:'b'}
# Output: True
print('H' in x)
# Output: True
print('hello' not in x)
# Output: True
print(1 in y)
# Output: False
print('a' in y)
• Identity operators
Python supports two types of identity operators. These operators compare the
memory locations of two objects.
is and is not are the identity operators in Python. They are used to check if
two values (or variables) are located on the same part of the memory. Two
variables that are equal does not imply that they are identical.
Example
x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
x3 = [1,2,3]
y3 = [1,2,3]
# Output: False
# Output: True
print(x2 is y2)
# Output: False
print(x3 is y3)
Here, we see that x1 and y1 are integers of same values, so they are equal as
well as identical. Same is the case with x2 and y2 (strings).
But x3 and y3 are list. They are equal but not identical. It is because interpreter
locates them separately in memory although they are equal.
Operator Description
This is because * has higher precedence than +, so it first multiplies 30 and 5 and
then adds 10.
>>>(10+30)*5
Output: 200
Output
Enter first number: 4
Enter second number: 55
concatenation of two strings: 455
By default input function takes user's input as a string. When i perform + operation
on a and b in the above example it results as string concatenation.
Example
Output
Print Statement
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.
Example:
x = 5; y = 10
print('The value of x is {} and y is {}'.format(x,y))
Output:- 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
it is printed by using numbers (tuple index).
Example
print('I love {0} and {1}'.format('bread','butter'))
# Output: I love bread and butter
print('I love {1} and {0}'.format('bread','butter'))
# Output: I love butter and bread
We can even format strings using % operator. It is similar to the printf() statement in
C programming language.
x = 12.3456789
print('The value of x is %3.2f' %x)
Output: The value of x is 12.35
print('The value of x is %3.4f' %x)
Output: The value of x is 12.3457
Type Conversion or Type Casting:
Convert a value from one data type to another data type known as type conversion or
type casting.
The basic difference between type casting from type conversion is that type
casting is conversion of one type to another, done by the programmer(explicitly). On
the other hand, the type conversion is conversion of one type to another, done by the
compiler(implicitly) while compiling.
The list of conversion built-in functions has given below.
Functio Descriptio
n n
int(x) Converts x to an integer
Example
a=9
print("Data Type of a is : ",type(a))
b=float(a)
print("Data Type of b is : ",type(b))
print("value of b is : ",b)
c=str(a)
print("Data Type of c is : ",type(c))
print("value of c is : ",c)
d=int(b)
print("Data Type of d is : ",type(d))
print("value of d is : ",d)
s="hello"
print("Data Type of s is : ",type(s))
mytuple=tuple(s)
print("Data Type of mytuple is : ",type(mytuple))
print("value of mytuple : ",mytuple)
mylist=list(s)
print("Data Type of mylist : ",type(mylist))
print("value of mylist : ",mylist)
myset=set(s)
print("Data Type of myset : ",type(myset))
print("value of myset : ",myset)
mychar='A'
print("ordinal value of A is",ord(mychar))
mynum=98
print("convert integer into char",chr(mynum))
print("convert integer into octal",oct(mynum))
print("convert integer into hexa",hex(mynum))
The most common reason of an error in a Python program is when a certain statement
is not in accordance with the prescribed usage. The Python interpreter immediately
reports it, usually along with the reason.
Syntax errors
Syntax errors are the most basic type of error. They arise when the Python parser is
unable to understand a line of code. In IDLE, it will highlight where the syntax error is.
Most syntax errors are typos, incorrect indentation, or incorrect arguments
Example
print "Gee golly"
we forget to use the parenthesis that are required by print(...). Python does not
understand what you are trying to do.
Run-Time Error
A syntax error happens when Python can't understand what you are saying. A run-time
error happens when Python understands what you are saying, but runs into trouble
when following your instructions.
Example
print(greeting)
we forget to define the greeting variable. Python knows what you want it to do, but since
no greeting has been defined, an error occurs.
Semantic errors
Semantic errors are problems with a program that runs without producing error
messages but doesn't do the right thing. Example: An expression may not be evaluated
in the order you expect, yielding an incorrect result.
Example
i=10;
i++; // the variable i is not initialized
Exercise
1. Write a program that asks two people for their names; stores the names in
variables called name1 and name2; says hello to both of them.
name1=input("Enter your name")
name2=input("Enter your name")
print("hello ",name1)
print("hello ",name2)
2. Write a Python program which accepts the radius of a circle from the user and
compute the area.
Sample Output :
r = 1.1
Area = 3.8013271108436504
r=float(input("Enter radius of a circle "))
area=3.14*(r * r)
print(" Area of circle : %.2f"%area)
3. Write a Python program which accepts the user's first and last name and
print them in reverse order with a space between them.
6. Write a program to enter two integers and then perform all arithmetic operations
on them.
x=int(input("Enter the first number"))
y=int(input("Enter the second number"))
print('x + y =',x+y)
print('x - y =',x-y)
print('x * y =',x*y)
print('x / y =',x/y)
print('x % y =',x%y)
print('x // y =',x//y)
print('x ** y =',x**y)
11. Write a program that prompts users to enter two integers x and y. The
program then calculates and display xy.
print("x ** y",x ** y)
13. Write a program to calculate salary of an employee given his basic pay(to
be entered by the user), HRA=10 percent of basic pay, TA=5 percent of
basic pay. Define HRA and TA as constants and use them to calculate
the salary of the employee.
HRA=basic*10/100
TA=basic*5/100
15. Write a program to calculate average of two numbers. Print their deviation.
import math
a=1
b=2
print(abs(a-b)/2)
16. Write a program to covert a floating point number into the corresponding integer.
n=float(input("Enter any float number"))
print("conversion of float value into integer",int(n))
17. Write a program to convert a integer into the corresponding floating point
number.
n=int(input("Enter any float number"))
print("conversion of integer value into float",float(n))
import math
s=(a+b+c)/2
area=math.sqrt(s*(s-a)*(s-b)*(s-c))
2.What is the type conversion or type casting? Explain type casting function along
with examples?