Python - Unit II & Basic Programs

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 20

Unit-II

Python Operators:

Operator is a symbol that tells interpreter to perform specific mathematical, relational


or logical operation and produce final result. Operators when applied on operands
form an expression.
Operand: The value that the operator operates on is called the operand.
Expression: An expression is a combination of variables constants and operators

Python supports different types of operators which are as follows:

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

Arithmetic operators are used to perform mathematical operations like addition,


subtraction, multiplication etc.

Symbol/Operator Description Example 1 Example 2

>>>55+45 >>> “Good” + Morning”


+ It is used to
100 GoodMorning
add two
operands
>>>55-45 >>>30-80
- It is used to 10 -50
subtract the
second
operand from
the first
operand. If the
first operand is
less than the
second
operand, the
value result
negative.
>>>55*45 >>> “Good”* 3
* It is used to
2475 GoodGoodGood
multiply one
operand
with the
other.
>>>17/5 >>>27/3
/ It returns 3.4 9.0
the quotient
after
dividing the
first
operand by
the second
operand.
It returns >>>17%5 >>> 23%2
%(modulo)
the 2 1
reminder
after
dividing
the first
operand
by the
second
operand.
>>>2**3 >>>2**8
** It is an 8 256
exponent >>>16**.5
operator 4.0
represented
as it
calculates
the first
operand
power to
second
operand.
// It gives the >>>7.0//2 >>>3/ / 2
floor value 3.0 1
(integer)of
the quotient
produced
by dividing
the two
operands.

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)

2. Relational or Comparison operators

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.

Symbol/Operator Description Example 1 Example 2

>>>7<10 >>>”Hello‟< ‟Goodbye‟


< Less than: True if True False
>>> 7<5 >>>'Goodbye'< 'Hello'
left operand is False True

less than the right

>>> 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.

Symbol/Operator Description Example 1 Example 2

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.

Bitwise AND (&)


Bitwise AND & will give 1 only if both the operands are 1 otherwise, 0.
The truth table for bitwise AND.

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

Bitwise XOR ^ will give 1 for odd number of 1s otherwise, 0.


The truth table for 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.

Symbol/Opera Descr Exa


tor iption mpl
e
>>>x=[1,2, 4,5,7,9]
in True if value/variable is found in the
>>>5 in x
sequence
True
>>>x=[1,2, 4,5,7,9]
True if value/variable is not found in
not in >>>10 not in x
the sequence
True

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.

Symbol/Operat Descri Exam


or ption ple
>>>x=5
is True if the operands/values >>>y=5
point(refer) to the same object >>>x is y
True
>>>a=[1,2, 4,5,7,9]
is not True if the operands/values do not >>>b=[1,2, 4,5,7,9]
point(refer) to the same object >>> x is not y
True

Example

x1 = 5

y1 = 5

x2 = 'Hello'

y2 = 'Hello'

x3 = [1,2,3]

y3 = [1,2,3]

# Output: False

print(x1 is not y1)

# 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.

Operators Precedence and Associativity


When an expression has more than one operator, then it is the relative priorities of the
operators with respect to each other that determine the order in which the expression
will be evaluated. The given table shows the lists of all operators from highest
precedence to lowest.

Operator Description

** Exponentiation (raise to the power)

+,- unary plus and minus

* , /, %, // Multiply, divide, modulo and floor division

+,- Addition and subtraction

>>,<< Right and Left bitwise shift operators

& Bitwise AND

<, <=, >, Comparison operators


>=
==, != Equality operators
% =, / =, // =
Assignment operators
,
- =, + =, * =

is, is not Identity operators

in, not in Membership operators

not, and, Logical operators


or
Operator precedence table is important as it affects how an expression is evaluated.
Example
>>> 10+30*5
Output: 160

This is because * has higher precedence than +, so it first multiplies 30 and 5 and
then adds 10.

>>>(10+30)*5
Output: 200

This is because parentheses () has higher precedence.

Input and Output:


Input Operation: The input() function prompts the user to provide(ask) some
information on which the program can work and give the result. Always, the input
function takes user’s input as a string. So whether input a number or string, it is
treated as a string only.
Example

a=input("Enter first number: ")


b=input("Enter second number: ")
print("concatenation of two strings: ",a+b)

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.

Type conversion is compulsory to add two numbers using input function.

Example

a=int(input("Enter first number: "))


b=int(input("Enter second number: "))
print("concatenation of two strings: ",a+b)

Output

Enter first number: 4


Enter second number: 55
concatenation of two strings: 59

Print Statement

Syntax: print expression/constant/variable


Print evaluates the expression before printing it on the monitor. Print statement
outputs an entire (complete) line and then goes to next line for subsequent output
(s). To print more than one item on a single line, comma (,) may be used.
Example
a=10
b=20
print(a,b)

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

float(x) Converts x to a floating point number

str(x) Converts x to a string

tuple(x) Converts x to a tuple

list(x) Converts x to a list

set(x) Converts x to a set

ord(x) Converts a single character to its integer value

oct(x) Converts an integer to an octal string

hex(x) Converts an integer to a hexadecimal string

chr(x) Converts an integer to a character

dict(x) Creates a dictionary if x forms a (key-value) pair

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))

Python - Error Types

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.

firstname=input("Enter your first name")

lastname=input("Enter your last name")

print(lastname + " " + firstname)

4. Write a Python program to solve (x + y) * (x + y).


Test Data : x = 4, y = 3
Expected Output : (4 + 3) ^ 2) = 49
x=int(input("Enter x value"))
y=int(input("Enter y value"))
print((x+y)*(x+y))
5. Write a Python program to swap two variables.
x=int(input("Enter the first number"))
y=int(input("Enter the second number"))
print("before swapping x value is {} \ny value is {}".format(x,y))
z=x
x=y
y=z
print("After swapping x value is {} \ny value is {}".format(x,y))

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)

7. Write a program to perform string concatenation.


firstname=input("Enter your first name")
lastname=input("Enter your last name")
print(lastname + " " + firstname)

8. Write a program to print the ASCII value of a character.


n=input("Enter any character")
print("ASCII value of given character: ",ord(n))

9. Write a program to swap two numbers without using temporary variable.


x=int(input("Enter the first number"))
y=int(input("Enter the second number"))
print("before swapping x value is {} \ny value is {}".format(x,y))
x=x+y
y=x-y
x=x-y
print("After swapping x value is {} \ny value is {}".format(x,y))

10. Write a program to calculate simple interest.

P = float(input("Enter the principal amount : "))


T = float(input("Enter the number of years : "))
R = float(input("Enter the rate of interest : "))
SI = (P * T * R)/100
print("Simple interest : {}".format(SI))

11. Write a program that prompts users to enter two integers x and y. The
program then calculates and display xy.

x=int(input("Enter the x value"))

y=int(input("Enter the y value"))

print("x ** y",x ** y)

12. Write a program that calculates numbers of seconds in a day.

n=int(input("Enter nuymber of days"))


print("number of seconds per {} days {}".format(n,n*24*60*60))

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.

basic=float(input("Enter basic pay of an Employee"))

HRA=basic*10/100

TA=basic*5/100

print("Employee total salary : ",basic+HRA+TA)


14. Write a program to print the digit at one’s place of Number.

n=int(input("Enter any number"))


print("the digit at one’s place of Number",n%10)

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))

18. Write a program to calculate area of triangle using Heron’s formula. (


Hint: Heron’s formula is : area = sqrt(s*(s-a)*(s-b)*(s-c))

import math

a=int(input("Enter first side: "))

b=int(input("Enter second side: "))

c=int(input("Enter third side: "))

s=(a+b+c)/2

area=math.sqrt(s*(s-a)*(s-b)*(s-c))

print("Area of the triangle is: ",round(area,2))


#print('The area of the triangle is %0.2f' %area)
Theory Questions:

1.What is an operator? Explain all the operators available in python?

2.What is the type conversion or type casting? Explain type casting function along
with examples?

3.Explain about Operators Precedence and Associativity with an example.

4.Explain python error types(Syntax, runtime, Semantic) with examples.

You might also like