Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
19 views

Module 1

Uploaded by

Tanvi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Module 1

Uploaded by

Tanvi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

Python Programming-21EC643

Module 1
Python Basics
Python Basics, Python language features, History , Entering Expressions into the Interactive Shell, The
Integer, Floating-Point, and String Data Types, String Concatenation and Replication, Storing Values in
Variables, Your First Program, Dissecting Your Program, Flow control, Boolean Values, Comparison
Operators, Boolean Operators, Mixing Boolean and Comparison Operators, Elements of Flow Control,
Program Execution, Flow Control Statements, Importing Modules, Ending a Program Early with
sys.exit(), Functions, def Statements with Parameters, Return Values and return Statements, The None

in
Value, Keyword Arguments and print(), Local and Global Scope, The global Statement, Exception
Handling, A Short Program: Guess the Number

Python is a high-level, general-purpose programming language that is widely used for a


variety of tasks, such as web development, data analysis, machine learning, and

.
artificial intelligence. Python is a dynamic, high-level, free open source, and interpreted

ud
programming language. It supports object- oriented programming as well as
procedural-oriented programming. In Python, we don’t need to declare the type of
variable because it is a dynamically typed language. For example, x = 10 Here, x can
be anything such as String, int, etc.
Salient features of Python:
1. Free and Open Source
lo
Python language is freely available at the official website and you can download it from
the given download link below click on the Download Python keyword. Download
Python Since it is open- source, this means that source code is also available to the
public. So you can download it, use it as well as share it.
uc

2. Easy to code
Python is a high-level programming language. Python is very easy to learn the language
as compared to other languages like C, C#, Javascript, Java, etc. It is very easy to code
in the Python language and anybody can learn Python basics in a few hours or days. It
is also a developer-friendly language.
3. Object-Oriented Language
vt

One of the key features of Python is Object-Oriented programming. Python supports


object-oriented language and concepts of classes, object encapsulation, etc.
4. GUI Programming Support
Graphical User interfaces can be made using a module such as PyQt5, PyQt4,
wxPython, or Tk in python. PyQt5 is the most popular option for creating graphical
apps with Python.
5. Extensible feature
Python is an Extensible language. We can write some Python code into C or C++

Page 1
Python Programming-21EC643

language and also we can compile that code in C/C++ language.


6. Python is a Portable language
Python language is also a portable language. For example, if we have Python code for
windows and if we want to run this code on other platforms such as Linux, Unix, and
Mac then we do not need to change it, we can run this code on any platform.
7. Python is an Integrated language
Python is also an Integrated language because we can easily integrate Python with
other languages like C, C++, etc.
8. Interpreted Language:

in
Python is an Interpreted Language because Python code is executed line by line at a
time. like other languages C, C++, Java, etc. there is no need to compile Python code
this makes it easier to debug our code. The source code of Python is converted into an
immediate form called bytecode.

.
9. Large Standard Library

ud
Python has a large standard library that provides a rich set of modules and functions
so you do not have to write your own code for every single thing. There are many
libraries present in Python such as regular expressions, unit-testing, web browsers,
etc.
10. Dynamically Typed Language
Python is a dynamically-typed language. That means the type (for example- int,
lo
double, long, etc.) for a variable is decided at run time not in advance because of this
feature we don’t need to specify the type of variable.
uc

Entering expressions into the interactive shell


 A window with the >>> prompt should appear; that‘s the interactive shell.

 Enter 2 + 2 at the prompt to have Python do some simple math.

 In Python, 2 + 2 is called an expression.


vt

 Expressions consist of values (such as 2) and operators (such as +), and they can
always evaluate (that is, reduce) down to a single value.

 A single value with no operators is also considered an expression, though it


evaluates only to itself, as shown here:

 >>>2
2

Page 2
Python Programming-21EC643

Math Operators from Highest to Lowest Precedence

. in
ud
lo
 The order of operations (also called precedence) of Python math operators is similar
to that of mathematics.

 The ** operator is evaluated first; the *, /, //, and % operators are evaluated next,
from left to right; and the + and - operators are evaluated last (also from left to right).
uc

 You can use parentheses to override the usual precedence if you need to.
Whitespace in between the operators and values doesn’t matter for Python.

Exercise: Try the following in interactive shell


vt

>>> 2+3*6 >>> 23 // 7


>>> (2 + 3) * 6 >>> 23 % 7
>>> 45 * 5/5 >>> 2+2**2-1
>>> 2 ** 8 >>> (5 - 1) * ((7 + 1) / (3 - 1))
>>> 23 / 7
The Integer, Floating-Point, and String Data Types
 A data type is a category for values, and every value belongs to exactly one data
type.

Page 3
Python Programming-21EC643

 The most common data types in Python are:

in
 The integer (or int) data type indicates values that are whole numbers.

.
 Numbers with a decimal point, such as 3.14, are called floating-point
numbers (or floats).

ud
 Python programs can also have text values called strings, or strs always
surrounded in single quote (').

 You can even have a string with no characters in it, '', called a blank string or
an empty string.
lo
String Concatenation and Replication
 The meaning of an operator may change based on the data types of the values next
to it. For example, + is the addition operator when it operates on two integers or
uc

floating-point values. However, when + is used on two string values, it joins the strings
as the string concatenation operator. Enter the following into the interactive shell:

 Example: >>> 'Alice' + 'Bob'


'AliceBob'
vt

 However, if you try to use the + operator on a string and an integer value, Python
will not know how to handle this, and it will display an error message.

 >>> 'Alice' + 42
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
'Alice' + 42
TypeError: can only concatenate str (not "int") to str

Page 4
Python Programming-21EC643

 The * operator multiplies two integer or floating-point values. But when


the * operator is used on one string value and one integer value, it becomes the string
replication operator. Enter a string multiplied by a number into the interactive shell to
see this in action.

 >>> 'Alice' * 5
'AliceAliceAliceAliceAlice‘

 The * operator can be used with only two numeric values (for multiplication), or one
string value and one integer value (for string replication).

in
 >>> 'Alice' * 'Bob'
Traceback (most recent call last):
File "<pyshell#32>", line 1, in <module>

.
'Alice' * 'Bob'
TypeError: can't multiply sequence by non-int of type 'str'
>>> 'Alice' * 5.0

ud
Traceback (most recent call last):
File "<pyshell#33>", line 1, in <module>
'Alice' * 5.0
TypeError: can't multiply sequence by non-int of type 'float'
lo
Storing Values in Variables
Variable is a named placeholder to hold any type of data which the program can use
to assign and modify during the course of execution. Variables should be valid
identifiers. An identifier is a name given to a variable, function, class or module.
uc

Identifiers may be one or more characters in the following format:


 Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z)
or digits (0 to 9) or an underscore (_). Names like myCountry, other_1 and
good_morning, all are valid examples. A Python identifier can begin with an alphabet
(A – Z and a – z and _).
vt

 An identifier cannot start with a digit but is allowed everywhere else. 1plus is
invalid, but plus1 is perfectly fine.
 Keywords cannot be used as identifiers. Keywords are a list of reserved words that
have predefined meaning. Keywords are special vocabulary and cannot be used by
programmers as identifiers for variables, functions, constants or with any identifier
name.
 Spaces and special symbols like !, @, #, $, % etc. as identifiers.
 Identifier can be of any length.

Page 5
Python Programming-21EC643

in
Assignment Statements

.
 An assignment statement consists of a variable name, an equal sign (called

value 42 stored in it.


>>> spam = 40
>>> spam
40
ud
the assignment operator), and the value to be stored. If you enter the assignment
statement spam = 42, then a variable named spam will have the integer
lo
>>> eggs = 2
>>> spam + eggs
42
>>> spam + eggs + spam
82
uc

>>> spam = spam + 2


>>> spam
42
>>> spam = 'Hello'
>>> spam
vt

'Hello'
>>> spam = 'Goodbye'
>>> spam
'Goodbye'

Built-in functions with examples in Python

In Python, built-in functions are pre-defined functions that are part of the
programming language and are available for use without the need to define

Page 6
Python Programming-21EC643

them. They can be used to perform various tasks such as input/output, data
type conversions, mathematical calculations, etc. Here are some examples of
commonly used built-in functions in Python:

print(): This function is used to output data to the screen. It takes one or more
arguments, which can be strings, numbers, or variables, and prints them to the
screen.

 print('Hello,world!')

in
print('What is your name?') # ask for their name.
 The line print('Hello, world!') means “Print out the text in the string 'Hello,
world!'.”

.
input(): This function is used to take input from the user. It takes a string as an
argument, which is used as a prompt for the user, and returns the input as a
string.

ud
name = input("What's your name? ")
print("Hello, " + name + "!")

The len() Function


lo
 You can pass the len() function a string value (or a variable containing a string),
and the function evaluates to the integer value of the number of characters in that
string.
 Example:
uc

myName=input()
print('The length of your name is:')
print(len(myName))

range(): This function is used to generate a range of numbers. It takes up to three


arguments: start, stop, and step.
vt

for i in range(5):
print(i)

These are just a few examples of the many built-in functions that are available in
Python. Some other commonly used built-in functions include abs(), pow(), round(),
sorted(), type(), etc. With the help of documentation, you can explore more built-in
functions and their usage.

Page 7
Python Programming-21EC643

Exercise:

Write a Python program for the following:

1. to print your name.


2. to read and print your name.
3. to read, print and find the length of your name.
4. to display name, college, USN.
5. to add 2 numbers.
6. to swap 2 numbers.

in
7. to find area and perimeter of a circle.

Check if the below statement gets executed.

1. print('I am ' + 29 + ' years old.')

.
2. print('hello world ' +int(100)+ ' how are you')
FLOW CONTROL

which conditions.
ud
 Flow control statements can decide which Python instructions to execute under

 In a flowchart, there is usually more than one way to go from the start to the end.

 The same is true for lines of code in a computer program.


lo
 Flowcharts represent these branching points with diamonds, while the other steps
are represented with rectangles.

 The starting and ending steps are represented with rounded rectangles.
uc
vt

Page 8
Python Programming-21EC643

Boolean Values
 While the integer, floating-point, and string data types have an unlimited number of
possible values, the Boolean data type has only two values: True and False.

 When entered as Python code, the Boolean values True and False lack the quotes
you place around strings, and they always start with a capital T or F, with the rest of
the word in lowercase.

>>> spam=True

in
>>> spam

True

.
>>> spam=true

ud
Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError:
name 'true' is not defined. Did you mean: 'True'?

>>> True=2+2

File "<stdin>", line 1 True=2+2 ^^^^ SyntaxError: cannot assign to True


lo
Comparison Operators

 Comparison operators, also called relational operators, compare two


values and evaluate down to a single Boolean value. Table lists the
comparison operators. These operators evaluate
uc

to True or False depending on the values you give them.


vt

Page 9
Python Programming-21EC643

. in
ud
lo
uc

Assignment Operators
 Assignment operators are used for assigning the values generated after evaluating
the right operand to the left operand.
vt

 Assignment operation always works from right to left. Assignment operators are
either simple assignment operator or compound assignment operators.

 Simple assignment is done with the equal sign (=) and simply assigns the value of
its right operand to the variable on the left.

 For example, the statement x = x + 1 can be written in a compactly form as shown


below. x += 1

Page 10
Python Programming-21EC643

in
.
ud
lo
Solve:

3/2*4+3+(10/4)**3-3
uc

= 3/2*4+3+(2.5)**3-3

= 3/2*4+3+2.5**3-3

= 3/2*4+3+ 15.625-3
vt

= 1.5*4+3+ 15.625-3

= 6.0+3+ 15.625-3

= 9.0+ 15.625-3

= 24.625-3

= 21.625

Page 11
Python Programming-21EC643

. in
Boolean Operators
ud
The three Boolean operators (and, or, and not) are used to compare Boolean values.
Like comparison operators, they evaluate these expressions down to a Boolean value.
Let’s explore these operators in detail.
lo
Binary Boolean Operators:
 The and and or operators always take two Boolean values (or expressions), so
they’re considered binary operators.
uc

 The and operator evaluates an expression to True if both Boolean values are True;
otherwise, it evaluates to False.

>>> True and True


True
vt

>>> True and False


False

>>> False or True


False

>>> False or False


False

Page 12
Python Programming-21EC643

 A truth table shows every possible result of a Boolean operator. Table is the truth
table for the and operator.

in
 On the other hand, the or operator evaluates an expression to True if either of the
two Boolean values is True. If both are False, it evaluates to False.

.
>>> False or True
True

>>> False or False


False ud
lo
uc

The not Operator

 Unlike and and or, the not operator operates on only one Boolean value (or
vt

expression). This makes it a unary operator. The not operator simply evaluates to the
opposite Boolean value.

>>> not True


False

>>> not not not not True


True

Page 13
Python Programming-21EC643

Examples:

>>> (4 < 5) and (5 < 6)


True

in
>>> (4 < 5) and (9 < 6)
False

>>> (1 == 2) or (2 == 2)
True

.
>>> 2 + 2 == 4 and not 2 + 2 == 5 and 2 * 2 == 2 + 2
True

ud
Write a Python program to illustrate the Comparison operators

print("Enter the value of a: ")

a=input()
lo
print("Enter the value of b: ")

b=input()

c=int(a)==int(b)
uc

print(c)

c=int(a)!=int(b)

print(c)
vt

c=int(a)<int(b)

print(c)

c=int(a)>int(b)

print(c)

c=int(a)<=int(b)

Page 14
Python Programming-21EC643

print(c)

c=int(a)>=int(b)

print(c)

Write a Python program to show the Boolean operators and comparison


operators.

print("Enter the value of a: ")

in
a=input()

print("Enter the value of b: ")

b=input()

.
c=(int(a)==int(b)) and (int(a)!=int(b))

print(c)

ud
c=(int(a)==int(b)) or (int(a)!=int(b))

print(c)
lo
c=not (int(a)==int(b))

print(c)

Flow control statements/conditional statements available in Python


uc

Decision-making is as important in any programming language as it is in life.


Decision-making in a programming language is automated using conditional
statements, in which Python evaluates the code to see if it meets the specified
conditions. The conditions are evaluated and processed as true or false. If this is
found to be true, the program is run as needed. If the condition is found to be false,
vt

the statement following the If condition is executed. Conditional Statement in Python


performs different computations or actions depending on whether a specific Boolean
constraint evaluates to true or false. Conditional statements are handled by IF
statements in Python.
Python has 3 key Conditional Statements:

a. if statement

b. if else statement

Page 15
Python Programming-21EC643

c. if elif statement

a. if statement:

The if statement is a conditional statement in python, that is used to determine


whether a block of code will be executed or not. Meaning if the program finds
the condition defined in the if statement to be true, it will go ahead and execute
the code block inside the if statement.
Syntax:
if condition:

in
# execute code block
Example:
If i % 2 ==0:
print(“Number is Even”)

.
If i%2==1:

Flowchart:

ud
print(“Number is Odd”)
lo
uc
vt

Exercise:

1. WAP to check if given number if even.

2. WAP to check if age of a person is eligible to vote.

Page 16
Python Programming-21EC643

b. if else statement
The if statement executes the code block when the condition is true. Similarly, the else
statement works in conjuncture with the if statement to execute a code block when the
defined if condition is false.

Syntax

if condition:

# execute code if condition is true

in
else:

# execute code if condition if False

.
Flowchart

ud
lo
uc
vt

Example:
If a>b:
print(“A is big”)
else:
print(“B is big”)

Page 17
Python Programming-21EC643

Exercise:

1. WAP to check if the given number is even or odd.

2. WAP to find largest of 2 numbers.

3. WAP to check if the given number is positive or negative.

c. If elif statement:

in
The elif statement is used to check for multiple conditions and execute the code
block within if any of the conditions evaluate to be true.
The elif statement is similar to the else statement in the context that it is optional

.
but unlike the else statement, there can be multiple elif statements in a code
block following an if statement.
Syntax:

if condition1: ud
# execute this statement
elif condition2:
# execute this statement
lo
.
.
else:
# if non of the above conditions
uc

# evaluate to True
# execute this statement

Example:
num = int(input(‘Enter a number’))
if num > 0:
vt

print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")

Page 18
Python Programming-21EC643

Flowchart

. in
Exercise: ud
1. WAP to check if the number is positive, negative or equal to zero.
lo
2. WAP to check the greatest of 3 numbers.

3. Write a program to read two integers and perform arithmetic


operations on them (addition, subtraction, multiplication and
division)
uc

4.

In Python, break and continue are loop control statements executed inside a loop.
These statements either skip according to the conditions inside the loop or terminate
the loop execution at some point.
vt

Break Statement
The break statement is used to terminate the loop immediately when it is
encountered. The syntax of the break statement is:
break

A break statement is used inside both the while and for loops. It terminates the loop
immediately and transfers execution to the new statement after the loop. For
example, have a look at the code and its output below:
Page 19
Python Programming-21EC643

count = 0
while count <= 100:
print (count)
count += 1
if count == 3:
break

Program output:
0
1

in
2

In the above example loop, we want to print the values between 0 and 100, but there
is a condition here that the loop will terminate when the variable count becomes
equal to 3.

.
ud
lo
uc
vt

Continue Statement
The continue statement causes the loop to skip its current execution at some point
and move on to the next iteration. Instead of terminating the loop like a break
statement, it moves on to the subsequent execution. The continue statement is used
to skip the current iteration of the loop and the control flow of the program goes to
the next iteration.
for i in range(0, 5):
if i == 3:
continue

Page 20
Python Programming-21EC643

print(i)

Program output:
0
1
2
4

In the above example loop, we want to print the values between 0 and 5, but there is

in
a condition that the loop execution skips when the variable count becomes equal to
3.

.
ud
lo
uc
vt

An example for continue statement:


while True:
print('Who are you?')
name = input()
if name != 'Joe':
continue
print('Hello, Joe. What is the password? (It is a fish.)')

Page 21
Python Programming-21EC643

password = input()
if password == 'swordfish':
print('Access granted.')
break

. in
ud
lo
uc

Difference between break and continue in python


vt

The main Difference between break and continue in python is loop terminate. In this
tutorial, we will explain the use of break and the continue statements in the python
language. The break statement will exist in python to get exit or break for and while
conditional loop. The break and continue can alter flow of normal loops and iterate
over the block of code until test expression is false.

Page 22
Python Programming-21EC643

Basis for
break continue
comparison

It will terminate only the


It eliminates the execution of
Task current
remaining iteration of loop
iteration of loop.

in
The ‘continue’ will
‘break’ will resume control of resume the control of the
Control after
program to the end of loop program to next iteration
break/continue
enclosing that ‘break’. of that loop enclosing

.
‘continue'

causes ud
It early terminates the loop.
It causes the early
execution of
the next iteration.
lo
The ‘continue’ does not
The ‘break ‘stop the continuation stop the continuation of
continuation
of the loop. loop and it stops the
current.
uc

while loop statements:

Syntax of Python While Loop


vt

while conditional_expression:
#Code block of while

The given condition, i.e., conditional_expression, is evaluated initially in the Python


while loop. Then, if the conditional expression gives a boolean value True, the while
loop statements are executed. The conditional expression is verified again when the
complete code block is executed. This procedure repeatedly occurs until the
conditional expression returns the boolean value False.

Page 23
Python Programming-21EC643

The statements of the Python while loop are dictated by indentation.


The code block begins when a statement is indented & ends with the very first
unindented statement. Any non-zero number in Python is interpreted as boolean
True. False is interpreted as None and 0.

. in
Python While Loop Example
ud
Here we will sum of squares of the first 15 natural numbers using a while loop.
lo
Code
num = 15
summation = 0
c=1
uc

while c <= num:


summation = c**2 + summation
c=c+1
print("The sum of squares is", summation)

Output:
vt

The sum of squares is 1240

Annoying while loop

name = ''

while name != 'your name':

print('Please type your name.')

Page 24
Python Programming-21EC643

name = input()

print('Thank you!')

. in
ud
lo
Alternative way
uc

name = ''

while name != 'your name':

print('Please type your name.')


vt

name = input()

if name =='your name':

break

print('Thank you!')

Page 25
Python Programming-21EC643

. in
ud
lo
for Loops and the range() Function:
The for loop is used to run a block of code for a certain number of times. It is used to
iterate over any sequences such as list, tuple, string, etc.
uc

The syntax of the for loop is:


for val in sequence:
# statement(s)

Here, val accesses each item of sequence on each iteration. Loop continues until we
reach the last item in the sequence.
vt

In code, a for statement looks something like

for i in range(5):

and includes the following:

• The for keyword

• A variable name

Page 26
Python Programming-21EC643

• The in keyword

• A call to the range() method with up to three integers passed to it

• A colon

• Starting on the next line, an indented block of code (called the for clause)

Flowchart:

. in
ud
lo
Example:

digits = [0, 1, 5,6]


uc

for i in digits:

print(i)

else:
vt

print("No items left.")

WAP to print Jimmy five times.

print('My name is')

for i in range(5):

print('Jimmy Five Times (' + str(i) + ')')

Page 27
Python Programming-21EC643

The Starting, Stopping, and Stepping Arguments to range()

Some functions can be called with multiple arguments separated by a comma,


and range() is one of them. This lets you change the integer passed to range() to follow
any sequence of integers, including starting at a number other than zero.

for i in range(12, 16):

print(i)

in
Output:

12

13

.
14

15
ud
The range() function can also be called with three arguments. The first two
arguments will be the start and stop values, and the third will be the step argument.
The step is the amount that the variable is increased by after each iteration.
lo
for i in range(0, 10, 2):

print(i)
uc

Output:

2
vt

The range() function is flexible in the sequence of numbers it produces


for for loops. For example, you can even use a negative number for the step argument
to make the for loop count down instead of up.

Page 28
Python Programming-21EC643

for i in range(5, -1, -1):

print(i)

Output:

in
3

.
0

Exercise:
ud
Write a Python program for the following:

1. To print n natural numbers.


lo
2. To print n whole numbers.
3. To print even numbers starting from 0.
4. to print odd numbers starting from 0
5. To print multiples of 4 until 40.
uc

Binary left shift and binary right shift operators:


Shift Operators
These operators are used to shift the bits of a number left or right thereby multiplying
or dividing the number by two respectively. They can be used when we have to
multiply or divide a number by two.
vt

Bitwise right shift: Shifts the bits of the number to the right and fills 0 on voids left(
fills 1 in the case of a negative number) as a result. Similar effect as of dividing the
number with some power of two.

Example 1:
a = 10 = 0000 1010 (Binary)
a >> 1 = 0000 0101 = 5

Page 29
Python Programming-21EC643

Example 2:
a = -10 = 1111 0110 (Binary)
a >> 1 = 1111 1011 = -5

Bitwise left shift: Shifts the bits of the number to the left and fills 0 on voids right as
a result. Similar effect as of multiplying the number with some power of two.
Example 1:
a = 5 = 0000 0101 (Binary)

in
a << 1 = 0000 1010 = 10
a << 2 = 0001 0100 = 20
Example 2:
b = -10 = 1111 0110 (Binary)

.
b << 1 = 1110 1100 = -20
b << 2 = 1101 1000 = -40

ud
Precedence and associatively of operators:
Operator precedence determines the way in which operators are parsed with respect
to each other. Operators with higher precedence become the operands of operators
with lower precedence. Associativity determines the way in which operators of the
lo
same precedence are parsed.
uc
vt

Page 30
Python Programming-21EC643

Example:
In the expression: 10 + 20 * 30

. in
ud
Operator Associativity: If an expression contains two or more operators with the
same precedence then Operator Associativity is used to determine. It can either be Left
to Right or from Right to Left. Example: ‘*’ and ‘/’ have the same precedence and
their associativity is Left to Right, so the expression “100 / 10 * 10” is treated as
“(100 / 10) * 10”.
lo
Operator Description Associativit
y
() Parentheses left-to-right
uc

** Exponent right-to-left
* / % Multiplication/division/modulus left-to-right
+ – Addition/subtraction left-to-right
<< >> Relational less than/less than or equal to left-to-right
< <= Relational greater than/greater than or equal to left-to-right
> >= Bitwise shift left, Bitwise shift right
== != Relational is equal to/is not equal to left-to-right
vt

is, is not Identity left-to-right


in, not in Membership operators
& Bitwise AND left-to-right
^ Bitwise exclusive OR left-to-right
| Bitwise inclusive OR left-to-right
not Logical NOT right-to-left
and Logical AND left-to-right
or Logical OR left-to-right

Nisha S K, Assistant Professor, SVIT Page 31


Python Programming-21EC643

= Assignment Addition/subtraction right-to-left


+= -= assignment
*= /= Multiplication/division assignment
%= &= Modulus/bitwise AND assignment
^= |= Bitwise exclusive/inclusive OR assignment
<<= >>= Bitwise shift left/right assignment

Type conversion in Python


Python defines type conversion functions to directly convert one data type to another
which is useful in day-to-day and competitive programming. This article is aimed at

in
providing information about certain conversion functions.
There are two types of Type Conversion in Python:
 Implicit Type Conversion
 Explicit Type Conversion

.
Implicit Type Conversion

ud
In Implicit type conversion of data types in Python, the Python interpreter
automatically converts one data type to another without any user involvement.
Example:
x = 10
print("x is of type:",type(x)) y = 10.6
lo
print("y is of type:",type(y)) z = x + y
print(z)
print("z is of type:",type(z))
Output:
x is of type: <class 'int'>
uc

y is of type: <class 'float'> 20.6


z is of type: <class 'float'>
As we can see the data type of ‘z’ got automatically changed to the “float” type while
one variable x is of integer type while the other variable y is of float type. The reason
for the float value not being converted into an integer instead is due to type
vt

promotion that allows performing operations by converting data into a wider-sized


data type without any loss of information. This is a simple case of Implicit type
conversion in python.

Explicit Type Conversion


In Explicit Type Conversion in Python, the data type is manually changed by the user
as per their requirement. With explicit type conversion, there is a risk of data loss
since we are forcing an expression to be changed in some specific data type. Various
forms of explicit type conversion are explained below:

Page 32
Python Programming-21EC643

1. int(a, base): This function converts any data type to integer. ‘Base’ specifies the
base in which string is if the data type is a string.
2. float(): This function is used to convert any data type to a floating-point number.

3. ord() : This function is used to convert a character to integer.


4. hex() : This function is to convert integer to hexadecimal string.
5. oct() : This function is to convert integer to octal string.
6. tuple() : This function is used to convert to a tuple.
7. set() : This function returns the type after converting to set.

in
8. list() : This function is used to convert any data type to a list type.
9. dict() : This function is used to convert a tuple of order (key,value) into a
dictionary.
10. str() : Used to convert integer into a string.

.
11. complex(real,imag) : This function converts real numbers to complex(real,imag)
number.

corresponding ASCII character.

Example:

s = "10010"
ud
12. chr(number): This function converts number to its
lo
c = int(s,2)
print ("After converting to integer base 2 : ", end="")
print (c)
e = float(s)
uc

print ("After converting to float : ", end="")


print (e)

Output:
After converting to integer base 2 : 18
After converting to float : 10010.0
vt

Data types in Python


Data types are the classification or categorization of data items. It represents the kind
of value that tells what operations can be performed on a particular data. Since
everything is an object in Python programming, data types are actually classes and
variables are instance (object) of these classes.
Following are the standard or built-in data type of Python:
 Numeric

Page 33
Python Programming-21EC643

 Sequence Type
 Boolean
 Set
 Dictionary

. in
1. Numeric Data Type
ud
In Python, numeric data type represent the data which has numeric value. Numeric
value can be integer, floating number or even complex numbers. These values are
defined as int, float and complex class in Python.
lo
Integers – This value is represented by int class. It contains positive or negative
whole numbers (without fraction or decimal). In Python there is no limit to how long
an integer value can be.
uc

Float – This value is represented by float class. It is a real number with floating point
representation. It is specified by a decimal point. Optionally, the character e or E
followed by a positive or negative integer may be appended to specify scientific
notation.

Complex Numbers – Complex number is represented by complex class. It is specified


vt

as (real part) + (imaginary part)j. For example – 2+3j

2. In Python, sequence is the ordered collection of similar or different data types.


Sequences allows to store multiple values in an organized and efficient fashion. There
are several sequence types in Python –
 String
 List
 Tuple

Page 34
Python Programming-21EC643

3. Boolean data tupe


Data type with one of the two built-in values, True or False. Boolean objects that are
equal to True are truthy (true), and those equal to False are falsy (false). But non-
Boolean objects can be evaluated in Boolean context as well and determined to be
true or false. It is denoted by the class bool.
4. Set
In Python, Set is an unordered collection of data type that is iterable, mutable and
has no duplicate elements. The order of elements in a set is undefined though it may

in
consist of various elements.
e. Dictionary
Dictionary in Python is an unordered collection of data values, used to store data
values like a map, which unlike other Data Types that hold only single value as an
element, Dictionary holds key:value pair. Key-value is provided in the dictionary to

.
make it more optimized. Each key-value pair in a Dictionary is separated by a colon :,

Examples: ud
whereas each key is separated by a ‘comma’.

1. Write a program to read the marks of three subjects and find the average of
them.
lo
m1= int(input("Enter Marks of 1 Subject:"))
m2= int(input("Enter Marks of 2 Subject:"))
m3= int(input("Enter Marks of 3 Subject:"))
uc

average = (m1+m2+m3)/3
print("Average Marks = {}".format(average))

2. Write a program to convert temperature from centigrade (read it as float


value) to Fahrenheit.
vt

c = float(input("Enter temperature in Centigrade :"))

f = 9/5 * c + 32

print("{:.2f} degree Celcius = {:.2f} Fahrenheit".format(c,f))

3. Write a program to calculate and print the Electricity bill of a given

Page 35
Python Programming-21EC643

customer. Units consumed by the user should be taken from the keyboard and
display the total amount to be pay by the customer. The charges are as follows:
Unit Charge/unit
upto 199 @1.20
200 and above but less than 400 @1.50
400 and above but less than 600 @1.80
600 and above @2.00
If the bill exceeds Rs. 400 then a surcharge of 15% will be charged. If the bill is

in
less than Rs. 400 then a minimum surcharge amount should be Rs. 100/-.

units = int(input('Enter number of units consumed: '))

.
if units<=199:

bill=units*1.20

elif units<400:

bill=units*1.50
ud
lo
elif units<600:

bill = units*1.80
uc

elif units>=600:

bill = units*2.00

surcharge=0
vt

if bill>400:

surcharge=bill*0.15

if bill<400:

surcharge=100

bill=bill+surcharge

print("Bill Amount : ",bill)


Page 36
Python Programming-21EC643

Write a program that uses a while loop to display all the even numbers between
100 and 130

for i in range(100, 131):

if i%2==0:

print(i)

in
Write a program that uses a while loop to add up all the even numbers between
100 and 200

.
sum =0

for i in range(100, 201):

if i%2==0:

sum=sum+i
ud
print("Sum of all even numbers between 100 and 200 is : ", sum)
lo
Write a program to find factorial of a number using for loop.
uc

n=int(input('Enter number to find the factorial: '))

fact=1

if n>0:

for i in range(1,n+1):
vt

fact=fact*I

print('Factorial of the given number is',fact)

Page 37
Python Programming-21EC643

Write a program to print the sum of the following series.

a. 1 + ½ + 1/3 +. …. + 1/n

b. 1/1 + 22/2 + 33/3 + ……. + nn/n

. in
ud
lo
uc
vt

Page 38
Python Programming-21EC643

Write a program to generate Fibonacci series.

. in
ud
lo
uc
vt

Page 39

You might also like