0% found this document useful (0 votes)
22 views

Unit - II - Notes Pyth

sdafsdafsdf

Uploaded by

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

Unit - II - Notes Pyth

sdafsdafsdf

Uploaded by

santo nino
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 44

UNIT - II - DATA, EXPRESSIONS, STATEMENTS AND CONTROL FLOW

2.1 PYTHON – INTRODUCTION

Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is


designed to be highly readable. Python uses English keywords frequently where as other languages use
punctuation, and it has fewer syntactical constructions than other languages

 Python is interpreted: Python is processed at runtime by the interpreter. You do not need to
compile your program before executing it. This is similar to PERL and PHP.
 Python is Interactive: You can actually sit at a Python prompt and interact with the interpreter
directly to write your programs
 Python is Object-Oriented: Python supports Object-Oriented style or technique of
programming that encapsulates code within objects
 Python is a Beginner's Language: Python is a great language for the beginner-level
programmers and supports the development of a wide range of applications from simple
text processing to WWW browsers to games.

2.1.1 FEATURES OF PYTHON

 Easy-to-learn: Python has few keywords, simple structure, and a clearly defined syntax.
This allows the student to pick up the language quickly.
 Easy-to-read: Python code is more clearly defined and visible to the eyes.
 Easy-to-maintain: Python's source code is fairly easy-to-maintain
 A broad standard library: Python's bulk of the library is very portable and cross-
platform compatible on UNIX, Windows, and Macintosh.
 Interactive Mode: Python has support for an interactive mode which allows
interactive testing and debugging of snippets of code.
 Portable: Python can run on a wide variety of hardware platforms and has the same interface on
all platforms.
 Extendable: You can add low-level modules to the Python interpreter. These modules enable
programmers to add to or customize their tools to be more efficient.
 Databases: Python provides interfaces to all major commercial databases.
 GUI Programming: Python supports GUI applications that can be created and ported to many
system calls, libraries, and windows systems, such as Windows MFC, Macintosh, and the
X Window system of UNIX
 Scalable: Python provides a better structure and support for large programs than shell
scripting.

1 Department of Computer Science and Engineering, Rajalakshmi Engineering College


Interpreter

 Python is an interpreted language they are executed by an interpreter. Interpreter take high level
language as input, processes the program in minimum amount of a time and displays the
output.

Compiler

 Compiler reads the entire program and translates into machine readable form called object code
or executable code before the program starts running.

Difference between Compiler and Interpreter

Compiler Interpreter
Compiler Takes Entire program as input Interpreter Takes Single instruction as input .
Intermediate Object Code is Generated No Intermediate Object Code is Generated

Memory Requirement is More Memory Requirement is Less


It takes large amount of time to analyze the It takes less amount of time to analyze the
source code but the overall execution time source code but the overall execution time
is comparatively faster. is slower

Errors are displayed after entire program is Errors are displayed for every
checked instruction interpreted

Programming language like Python, Ruby Programming language like Python, Ruby
use interpreters use interpreters

2.1.2 WHAT IS A PROGRAM?

A program is a sequence of instructions that specifies how to perform a computation. The


computation might be something mathematical, such as solving a system of equations or finding the
roots of a polynomial, but it can also be a symbolic computation, such as searching and
replacing text in a document or something graphical, like processing an image
or playing a video.

2 Department of Computer Science and Engineering, Rajalakshmi Engineering College


The details look different in different languages, but a few basic instructions appear in just about every
language:

input: - Get data from the keyboard, a file, the network, or some other device. output: -

Display data on the screen, save it in a file, send it over the network, etc. math: - Perform

basic mathematical operations like addition and multiplication. conditional execution: -

Check for certain conditions and run the appropriate code. repetition: - Perform some

action repeatedly, usually with some variation.

Believe it or not, that’s pretty much all there is to it. Every program you’ve ever used, no
matter how complicated, is made up of instructions that look pretty much like these. So you can think
of programming as the process of breaking a large, complex task into smaller and smaller subtasks
until the subtasks are simple enough to be performed with one of these basic instructions.

2.1.3 WHAT IS DEBUGGING?

Programmers make mistakes. For whimsical reasons, programming errors are called bugs and the
process of tracking them down is called debugging.

Three kinds of errors can occur in a program: syntax errors, runtime errors, and semantic
errors.

Syntax Errors

Python can only execute a program if the syntax is correct; otherwise, the interpreter displays an error
message. Syntax refers to the structure of a program and the rules about that structure. For
example, parentheses have to come in matching pairs, so (1 + 2) is legal, but 8) is a syntax error.

Runtime Errors

The second type of error is a runtime error, so called because the error does not appear until after the
program has started running. These errors are also called exceptions because they
usually indicate that something exceptional (and bad) has happened.

3 Department of Computer Science and Engineering, Rajalakshmi Engineering College


Semantic Errors

The third type of error is the semantic error. If there is a semantic error in your program, it will run
successfully in the sense that the computer will not generate any error messages, but it will not do the
right thing. It will do something else. Specifically, it will do what you told it to do.

The problem is that the program you wrote is not the program you wanted to write. The
meaning of the program (its semantics) is wrong. Identifying semantic errors can be tricky because it
requires you to work backward by looking at the output of the program and trying to figure out what it
is doing.

2.1.4 RUNNING PYTHON

There are two versions of Python, called Python 2 and Python 3. They are very similar, so if you learn
one, it is easy to switch to the other. In fact, there are only a few differences you will encounter as a
beginner.

The Python interpreter is a program that reads and executes Python code. Depending on your
environment, you might start the interpreter by clicking on an icon, or by typing python on a command
line. When it starts, you should see output like this:

Python 3.4.0 (default, Jun 19 2015, 14:20:21)

[GCC 4.8.2] on linux

Type "help", "copyright", "credits" or "license" for more information.

>>
>

The first three lines contain information about the interpreter and the operating system it’s running on,
so it might be different for you. But you should check that the version number, which is 3.4.0 in this
example, begins with 3, which indicates that you are running Python 3. If it begins with 2, you are
running (you guessed it) Python 2.

The last line is a prompt that indicates that the interpreter is ready for you to enter code. If you type a
line of code and hit Enter, the interpreter displays the result:
>>> 1+
1
2

Now you’re ready to get started. From here on, I assume that you know how to start the
Python interpreter and run code.
4 Department of Computer Science and Engineering, Rajalakshmi Engineering College
2.1.5 SCRIPT MODE

So far we have run Python in interactive mode, which means that you interact directly with the
interpreter. Interactive mode is a good way to get started, but if you are working with more than a
few lines of code, it can be clumsy.

The alternative is to save code in a file called a script and then run the interpreter in script mode to
execute the script. By convention, Python scripts have names that end with .py.

Because Python provides both modes, you can test bits of code in interactive mode before you put
them in a script. But there are differences between interactive mode and script mode that can be
confusing.

For example, if you are using Python as a calculator, you might type:

>>> miles = 26.2


>>> miles * 1.61 42.182

The first line assigns a value to miles, but it has no visible effect. The second line is an
expression, so the interpreter evaluates it and displays the result. It turns out that a marathon is about 42
kilometers.

But if you type the same code into a script and run it, you get no output at all. In script mode an
expression, all by itself, has no visible effect. Python actually evaluates the expression, but it doesn’t
display the value unless you tell it to:

miles = 26.2
print(miles * 1.61)

This behavior can be confusing at first.

A script usually contains a sequence of statements. If there is more than one statement, the results
appear one at a time as the statements execute.

For example, the script


print(1)
x=2
print(x)

produces the output


1
2
5 Department of Computer Science and Engineering, Rajalakshmi Engineering College
The assignment statement produces no output.

To check your understanding, type the following statements in the Python interpreter and see
what they do:

5
x=5
x+1

Now put the same statements in a script and run it. What is the output? Modify the script by
transforming each expression into a print statement and then run it again.

2.1.6 THE FIRST PROGRAM

Traditionally, the first program you write in a new language is called “Hello, World!”
because all it does is display the words “Hello, World!” In Python, it looks like this:

>>> print('Hello, World!')

This is an example of a print statement, although it doesn’t actually print anything on paper.
It displays a result on the screen. In this case, the result is the words

Hello, World!

The quotation marks in the program mark the beginning and end of the text to be displayed;
they don’t appear in the result.

The parentheses indicate that print is a function.

In Python 2, the print statement is slightly different; it is not a function, so it doesn’t use
parentheses.

>>> print 'Hello, World!'

2.2 VALUES AND TYPES

A value is one of the basic things a program works with, like a letter or a number. Some
values we have seen so far are 2, 42.0, and 'Hello, World!'

These values belong to different types: 2 is an integer, 42.0 is a floating-point number, and
'Hello, World!' is a string, so-called because the letters it contains are strung together.

6 Department of Computer Science and Engineering, Rajalakshmi Engineering College


If you are not sure what type a value has, the interpreter can tell you:

>>> type(2) <class 'int'>


>>> type(42.0) <class 'float'>
>>> type('Hello, World!') <class 'str'>

In these results, the word “class” is used in the sense of a category; a type is a category of
values.

Not surprisingly, integers belong to the type int, strings belong to str, and floating-point
numbers belong to float.

What about values like '2' and '42.0'? They look like numbers, but they are in quotation marks like
strings:

>>> type('2') <class 'str'>


>>> type('42.0')
<class 'str'>

They’re strings.

When you type a large integer, you might be tempted to use commas between groups of
digits, as in 1,000,000. This is not a legal integer in Python, but it is legal:

>>> 1,000,000 (1, 0, 0)

That’s not what we expected at all! Python interprets 1,000,000 as a comma-separated sequence
of integers.

2.3 STANDARD DATA TYPES

Python has various standard data types that are used to define the operations possible on them
and the storage method for each of them.

Python has five standard data types:

 Numbers
 String
 List
 Tuple
 Dictionary

7 Department of Computer Science and Engineering, Rajalakshmi Engineering College


2.3.1 Python Numbers

Number data types store numeric values. Number objects are created when you assign a
value to them.

var1 = 1
var2 = 10

Python supports four different numerical types:

 int (signed integers)


 long (long integers, they can also be represented in octal and hexadecimal)
 float (floating point real values)
 complex (complex numbers)

Int Long Float complex


10 51924361L 0.0 3.14j
100 - 0x19323L 15.20 -.6545+0J
-786 0xDEFABCECBDAECBFBAEl 32.3+e18 9.322e-36j

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

Example:

str = 'Hello World!'


print (str) # Prints complete string
print (str[0]) # Prints first character of the string
print (str[2:5]) # Prints characters starting from 3rd to 5th print
(str[2:]) # Prints string starting from 3rd character print (str *
2) # Prints string two times
print (str + "TEST") # Prints concatenated string

8 Department of Computer Science and Engineering, Rajalakshmi Engineering College


Output:

Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST

2.3.3 Python Lists

 Lists are the most versatile of Python's compound data types.


 A list contains items separated by commas and enclosed within square brackets ([]).
 To some extent, lists are similar to arrays in C. One difference between them is that all the items
belonging to a list can be of different data type.
 The values stored in a list can be accessed using the slice operator ([ ] and [:]) with
indexes starting at 0 in the beginning of the list and working their way to end -1.
 The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator.

Example:

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]


tinylist = [123, 'john']
print (list) # Prints complete list
print (list[0]) # Prints first element of the list
print (list[1:3]) # Prints elements starting from 2nd till 3rd print
(list[2:]) # Prints elements starting from 3rd element print
(tinylist * 2) # Prints list two times
print (list + tinylist) # Prints concatenated lists

Output:

['abcd', 786, 2.23, 'john', 70.2]


abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']

9 Department of Computer Science and Engineering, Rajalakshmi Engineering College


2.3.4 Python Tuples

 A tuple is another sequence data type that is similar to the list.


 A tuple consists of a number of values separated by commas.
 Unlike lists, however, tuples are enclosed within parentheses.
 The main differences between lists and tuples are: Lists are enclosed in brackets
 ( [ ] ) and their elements and size can be changed, while tuples are enclosed in
parentheses ( ( ) ) and cannot be updated.
 Tuples can be thought of as read only lists.

Example:

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )


tinytuple = (123, 'john')
print (tuple) # Prints complete list
print (tuple[0]) # Prints first element of the list
print (tuple[1:3]) # Prints elements starting from 2nd till 3rd print
(tuple[2:]) # Prints elements starting from 3rd element print
(tinytuple * 2) # Prints list two times
print (tuple + tinytuple) # Prints concatenated lists

Output:

('abcd', 786, 2.23, 'john', 70.2)


abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')

The following code is invalid with tuple, because we attempted to update a tuple, which is not
allowed? Similar case is possible with lists:

Example:

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]


print (list)

Output:
['abcd', 786, 2.23, 'john', 70.2]

10 Department of Computer Science and Engineering, Rajalakshmi Engineering College


Example:

list[2] = 1000
print (list)

Output:
['abcd', 786, 1000, 'john', 70.2]

Example:

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )


print (tuple)

Output:
('abcd', 786, 2.23, 'john', 70.2)

Example:

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )


print (tuple)
tuple[2] = 1000
print (tuple)

Output:
Shows an Error Message

2.3.5 Python Dictionary

 Python's dictionaries are kind of hash table type.


 They work like associative arrays or hashes found in Perl and consist of key-value pairs.
 A dictionary key can be almost any Python type, but are usually numbers or strings.
 Values, on the other hand, can be any arbitrary Python object.
 Dictionaries are enclosed by curly braces ({ }) and values can be assigned and
 accessed using square braces ([]).

Example:

dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
11 Department of Computer Science and Engineering, Rajalakshmi Engineering College
print (dict['one']) # Prints value for 'one' key
print (dict[2]) # Prints value for 2 key
print (tinydict) # Prints complete dictionary print
(tinydict.keys()) # Prints all the keys print
(tinydict.values()) # Prints all the values

Output:

This is one
This is two
{'name': 'john', 'code': 6734, 'dept': 'sales'}
dict_keys(['name', 'code', 'dept'])
dict_values(['john', 6734, 'sales'])

2.4 VARIABLES

One of the most powerful features of a programming language is the ability to manipulate variables. A
variable is a name that refers to a value.

2.4.1 ASSIGNMENT STATEMENTS

An assignment statement creates a new variable and gives it a value:

>>> message = 'And now for something completely different'


>>> n = 17
>>> pi = 3.141592653589793

This example makes three assignments. The first assigns a string to a new variable named
message; the second gives the integer 17 to n; the third assigns the (approximate) value of π to pi.

2.4.2 Multiple Assignments

Python allows you to assign a single value to several variables simultaneously a = b =


c=1
a, b, c = 1, 2, "john"

A common way to represent variables on paper is to write the name with an arrow pointing to its value.
This kind of figure is called a state diagram because it shows what state each of the variables is in
(think of it as the variable’s state of mind). Figure 2-1 shows the result of
the previous example.

12 Department of Computer Science and Engineering, Rajalakshmi Engineering College


2.4.3 VARIABLE NAMES

A variable is basically a name that represents (or refers to) some value. Variable are reserved memory
locations to store values.

Programmers generally choose names for their variables that are meaningful - they
document what the variable is used for.
Variable names can be as long as you like. They can contain both letters and numbers, but
they can’t begin with a number. It is legal to use uppercase letters, but it is conventional to use only
lowercase for variables names.

The underscore character, _, can appear in a name. It is often used in names with multiple words, such
as your_name or airspeed_of_unladen_swallow.

If you give a variable an illegal name, you get a syntax error:

>>> 76trombones = 'big parade' SyntaxError: invalid syntax


>>> more@ = 1000000 SyntaxError: invalid syntax
>>> class = 'Advanced Theoretical Zymurgy' SyntaxError: invalid syntax

76trombones is illegal because it begins with a number. more@ is illegal because it contains
an illegal character, @. But what’s wrong with class?

It turns out that class is one of Python’s keywords. The interpreter uses keywords to
recognize the structure of the program, and they cannot be used as variable names.

2.5 KEYWORDS

Keywords are the reserved words in Python. We cannot use keywords as variable name,
function name or any other identifier. They are used to define the syntax and structure of the
Python language. In Python, keywords are case sensitive.

13 Department of Computer Science and Engineering, Rajalakshmi Engineering College


Python 3 has these keywords:

and def exec global lambda print while


assert del False if None raise with
break elif finally import not return yield
class else for in or True
continue except from is pass try

You don’t have to memorize this list. In most development environments, keywords are
displayed in a different color; if you try to use one as a variable name, you’ll know.

2.6 EXPRESSIONS AND STATEMENTS

An expression is a combination of values, variables, and operators. A value all by itself is


considered an expression, and so is a variable, so the following are all legal expressions:

>>> 42
42
>>> n
17
>>> n + 25
42

When you type an expression at the prompt, the interpreter evaluates it, which means that it finds the
value of the expression. In this example, n has the value 17 and n + 25 has the value
42.

A statement is a unit of code that has an effect, like creating a variable or displaying a value.

>>> n = 17
>>> print(n)

The first line is an assignment statement that gives a value to n. The second line is a print statement
that displays the value of n.

When you type a statement, the interpreter executes it, which means that it does whatever
the statement says. In general, statements don’t have values.

14 Department of Computer Science and Engineering, Rajalakshmi Engineering College


2.7 PYTHON I/O

2.7.1 Python Input

 The value of variables were defined or hard coded into the source code.
 To allow flexibility we might want to take the input from the user.
 In Python, we have the input() function to allow this.
 The syntax for input() is

input([prompt])

Example:

data_type(input("Enter the Value"))

Output:
Enter the Value

2.7.2 Python Output Using print() function

 We use the print() function to output data to the standard output device (screen).
 The actual syntax of the print() function is print(*objects,

sep=' ', end='\n', file=sys.stdout, flush=False)

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 – Addition of two numbers

fn = input("Enter First Number:")


sn = input("Enter Second Number:")
sum = int(fn)+int(sn)
print('The sum of {0} and {1} is {2}'.format(fn,sn,sum))

Output:
Enter First Number:25
Enter Second Number:50
The sum of 25 and 50 is 75

15 Department of Computer Science and Engineering, Rajalakshmi Engineering College


2.8 PYTHON OPERATORS

Operators are the constructs which can manipulate the value of operands

Types of Operators
1) Arithmetic Operators
2) Comparison (Relational) Operators
3) Assignment Operators
4) Logical Operators
5) Bitwise Operators
6) Membership Operators
7) Identity Operators

2.8.1 Python Arithmetic Operators

Operator Description Example


+ Addition Adds values on either side of the operator a + b = 30
- Subtraction Subtracts right hand operand from left hand a – b = -10
operand
* Multiplication Multiplies values on either side of the operator a * b = 200
/ Division Divides left hand operand by right hand b/a=2
operand
% Modulus Divides left hand operand by right hand b%a=0
operand and returns remainder
** Exponent Performs exponential (power) calculation on a**b =10 to
operators the power 20
//Floor Division Floor Division - The division of operands where the result 9//2 = 4 and
is the quotient in which the digits after the 9.0//2.0 = 4.0
decimal point are removed.

Example:

num1 = int(input("Enter Number1:")) num2 =


int(input("Enter Number2:")) print("Addition of 2
Number is:",num1+num2) print("Difference of 2 Number
is:",num1-num2) print("Multiplication of 2 Number
is:",num1*num2) print("Division of 2 Number
is:",num1/num2) print("Floor Division of 2 Number
is:",num1//num2)
print("Modulo Division of 2 Number is:",num1%num2)
print("Exponentiation of 2 Number is:",num1**num2)

16 Department of Computer Science and Engineering, Rajalakshmi Engineering College


Output:
Enter Number1:10
Enter Number2:6
Addition of 2 Number is: 16
Difference of 2 Number is: 4
Multiplication of 2 Number is: 60
Division of 2 Number is: 1.6666666666666667
Floor Division of 2 Number is: 1
Modulo Division of 2 Number is: 4
Exponentiation of 2 Number is: 1000000

2.8.2 Python Comparison 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 condition (a == b)
becomes true.
!= If values of two operands are not equal, then condition (a != b)
becomes true
> If the value of left operand is greater than the value of right (a > b)
operand, then condition becomes true.
< If the value of left operand is less than the value of right (a < b)
operand, then condition becomes true
>= If the value of left operand is greater than or equal to the value (a >= b)
of right operand, then condition becomes true
<= If the value of left operand is less than or equal to the value (a <= b)
of right operand, then condition becomes true

Example:

age = int(input("Enter Person Age:"))


if (age >= 13 and age <= 18):
print("The Person Falls into Teenage")
else:
print("The Person does not Falls into Teenage")

Output:
Enter Person Age:15
The Person Falls into Teenage

Enter Person Age:12


The Person does not Falls into Teenage
17 Department of Computer Science and Engineering, Rajalakshmi Engineering College
2.8.3 PYTHON ASSIGNMENT OPERATORS

Operator Description Example


= Assigns values from right side operands to left side c = a + b assigns
operand value of a + b into c
+= It adds right operand to the left operand and c += a is equivalent
Add AND assign the result to left operand to c = c + a
-= It subtracts right operand from the left operand and c -= a is equivalent
Subtract AND assign the result to left operand to c = c - a
*= It multiplies right operand with the left operand and c *= a is equivalent
Multiply AND assign the result to left to c = c * a
operand
/= It divides left operand with the right operand and c /= a is equivalent
Divide AND assign the result to left operand to c = c / a
%= It takes modulus using two operands and assign the c %= a is equivalent
Modulus result to left operand to c = c
AND %a
**= Performs exponential (power) calculation on c **= a is
Exponent operators and assign value to the left operand equivalent to c = c
AND It performs floor division on operators and assign ** a
//= value to the left operand c //= a is equivalent
Floor Division to c = c
// a

Example:

n1 = int(input("Enter Number1:")) n2
= int(input("Enter Number2:")) n3 =
0
n3 = n1 + n2
print ("Addition of 2 Number is ", n3)
n3 += n1
print ("Add AND of 2 Number is ", n3)
n3 *= n1
print ("Multiplication AND of 2 Number is ", n3)
n3 /= n1
print ("Division AND of 2 Number is ", n3)
n3 %= n1
print ("Modulo Division AND of 2 Number is ", n3)

18 Department of Computer Science and Engineering, Rajalakshmi Engineering College


Output:
Enter Number1:25
Enter Number2:10
Addition of 2 Number is 35
Add AND of 2 Number is 60
Multiplication AND of 2 Number is 1500
Division AND of 2 Number is 60.0
Modulo Division AND of 2 Number is 10.0

2.8.4 PYTHON BITWISE OPERATORS

Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60;
and b = 13; Now in binary format they will be as follows a =
0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011

There are following Bitwise operators supported by Python language


Operator Description Example
& Operator copies a bit to the result if it exists in (a & b) = 12 (means 0000
Binary AND both operands 1100)
| Binary OR It copies a bit if it exists in either operand (a | b) = 61 (means 0011
1101)
^ Binary XOR It copies the bit if it is set in one operand but not (a ^ b) = 49 (means 0011
both 0001)
~ It is unary and has the effect of 'flipping' bits (~a ) = -61 (means 1100 0011 in 2's
Binary Ones complement form due
Complement to a signed binary number.
<< The left operands value is moved left by the a << 2 = 240 (means 1111
Binary Left number of bits specified by the right operand 0000)
Shift The left operands value is moved right by the
>> number of bits specified by the right a >> 2 = 15 (means 0000
Binary Right operand 1111)
Shift

19 Department of Computer Science and Engineering, Rajalakshmi Engineering College


Example:

n1 = int(input("Enter Number 1:")) n2


= int(input("Enter Number 2:"))
binand = n1&n2
binor = n1|n2
binxor = n1^n2
binones = ~n1
binltst = n1<<2
binrtst = n1>>2
print("Binary AND Value is:",binand)
print("Binary OR Value is:",binor)
print("Binary XOR Value is:",binxor)
print("Binary Ones Complement Value is:",binones)
print("Binary Left Shift Value is:",binltst) print("Binary
Right Shift Value is:",binrtst)

Output:
Enter Number 1:60
Enter Number 2:13
Binary AND Value is: 12
Binary OR Value is: 61
Binary XOR Value is: 49
Binary Ones Complement Value is: -61
Binary Left Shift Value is: 240
Binary Right Shift Value is: 15

2.8.5 PYTHON LOGICAL OPERATORS

There are following logical operators supported by Python language

Operator Description Example


and If both the operands are true then condition (a and b) is true
Logical AND becomes true
or If any of the two operands are non-zero (a or b) is true
Logical OR then condition becomes true
not Used to reverse the logical state of its Not (a and b) is false
Logical NOT operand

20 Department of Computer Science and Engineering, Rajalakshmi Engineering College


Example:
char = input("Enter a Character : ")
if (char >='A' and char <= 'Z')or (char >='a' and char <= 'z'):
print("%s is a Alphabet" %char)
elif (char >='0' and char <= '9'):
print("%s is a Digit" %char)
else:
print("%s is a Special Character" %char)

Output:
Enter a Character : g g
is a Alphabet

Enter a Character : M
M is a Alphabet

Enter a Character : 5
5 is a Digit

Enter a Character : @
@ is a Special Character

2.8.6 PYTHON MEMBERSHIP OPERATORS

Python’s membership operators test for membership in a sequence, such as strings, lists, or
tuples.

Operator Description Example


in Evaluates to true if it finds a variable in the x in y, here in results in a 1 if x
specified sequence and false otherwise is a member of sequence y
not in Evaluates to true if it does not finds a
variable in the specified sequence and x not in y, here not in results in
false otherwise. a 1 if x is not a member of
sequence y
Example:
char = input("Input a letter of the alphabet: ")
if char in ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'):
print("%s is a vowel." %char)
else:
print("%s is a consonant." %char)

Output:
Input a letter of the alphabet: M M
is a consonant.

21 Department of Computer Science and Engineering, Rajalakshmi Engineering College


Input a letter of the alphabet: g g
is a consonant.

Input a letter of the alphabet: E E


is a vowel.

Input a letter of the alphabet: u u


is a vowel.

2.8.7 PYTHON IDENTITY OPERATORS

Identity operators compare the memory locations of two objects.

Operator Description Example


is Evaluates to true if the variables on either x is y, here is results
side of the operator point to the same in 1 if id(x) equals
object and false otherwise id(y)
is not Evaluates to false if the variables on x is not y, here is
either side of the operator point to the not results in 1 if id(x)
same object and true otherwise is not equal to id(y)

Example:

n1 = int(input("Enter the Number1:")) n2


= int(input("Enter the Number2:")) if(n1
is n2):
print("Number1 and Number2 have same identity")
else:
print("Number1 and Number2 have not same identity")

Output:
Enter the Number1:20
Enter the Number2:20
Number1 and Number2 have same identity

Enter the Number1:20


Enter the Number2:30
Number1 and Number2 have not same identity

22 Department of Computer Science and Engineering, Rajalakshmi Engineering College


2.9 PYTHON OPERATORS PRECEDENCE

The following table lists all operators from highest precedence to lowest

Operator Description
** Exponentiation (raise to the power)
~
Ccomplement, unary plus and minus (method names for the
+ last two are +@ and -@)
-
*
/
Multiply, divide, modulo and floor division
%
//
+
Addition and subtraction
-
>>
Right and left bitwise shift
<<
& Bitwise 'AND’
^
Bitwise exclusive `OR' and regular `OR'
|
<=
<> Comparison operators
>=
==
!= Equality operators
=
%=
/= /
/=
Assignment operators
-=
+=
*=
**
=
is is not Identity operators
in not in Membership operators not
or and Logical operators

23 Department of Computer Science and Engineering, Rajalakshmi Engineering College


Example:

n1 = int(input("Enter Number1:")) n2
= int(input("Enter Number2:")) n3 =
int(input("Enter Number3:")) n4 =
int(input("Enter Number4:")) res = 0
res = (n1+n2)*n3/n4
print("First Result = ",res) res
= ((n1+n2)*n3)/n4
print("Second Result = ",res)
res = (n1+n2)*(n3/n4)
print("Third Result = ",res) res
= n1+(n2*n3)/n4 print("Fourth
Result = ",res)

Output:
Enter Number1:20
Enter Number2:10
Enter Number3:15
Enter Number4:5
First Result = 90.0
Second Result = 90.0
Third Result = 90.0
Fourth Result = 50.0

2.10 Comments in Python

 A hash sign (#) that is not inside a string literal begins a comment.
 All characters after the # and up to the end of the physical line are part of the comment and the
Python interpreter ignores them

Example:
# First comment
print "Hello, Python!"; # second comment name
= "Madisetti" # This is again comment

2.10.1 Lines and Indentation


 Python provides no braces to indicate blocks of code for class and function definitions or flow
control.
 Blocks of code are denoted by line indentation, which is rigidly enforced.

24 Department of Computer Science and Engineering, Rajalakshmi Engineering College


 The number of spaces in the indentation is variable, but all statements within the block must be
indented the same amount

Example:

if True:
print "True"
else:
print "False"

2.10.2 Multi-Line Statements

 Statements in Python typically end with a new line.


 Python does, however, allow the use of the line continuation character (\) to denote that the line
should continue.

Example:
total = item_one + \
item_two + \
item_three

Statements contained within the [], {}, or () brackets do not need to use the line continuation character.

Example:
days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']

2.10.3 Multiple Statements on a Single Line

The semicolon ( ; ) allows multiple statements on the single line given that neither statement starts a
new code block.

Example:
import sys; x = 'foo'; sys.stdout.write(x + '\n')

2.10.4 Quotation in Python

Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long
as the same type of quote starts and ends the string. The triple quotes are used to span
the string across multiple lines

25 Department of Computer Science and Engineering, Rajalakshmi Engineering College


Example:

word = 'word'
sentence = "This is a sentence." paragraph =
"""This is a paragraph. It is made up of multiple
lines and sentences."""

2.11 PYTHON – CONDITIONALS

 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

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)

2.11.1 conditional (if)

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(test-expression):
statement-block(s)
statement-x

If the boolean expression evaluates to TRUE, then the block of statement(s) inside the if
statement is executed. If boolean expression evaluates to FALSE, then the first set of code
after the end of the if statement(s) is executed.

26 Department of Computer Science and Engineering, Rajalakshmi Engineering College


The simplest form is the if statement:
if x > 0:
print('x is positive')

The boolean expression after if is called the condition. If it is true, the indented statement
runs. If not, nothing happens.

if statements have the same structure as function definitions: a header followed by an indented
body. Statements like this are called compound statements.

2.11.2 alternative (if…else)

A second form of the if statement is “alternative execution”, in which there are two
possibilities and the condition determines which one runs.
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(test-expression):
true-block-statement(s)
else:
false-block-statement(s)
statement-x

27 Department of Computer Science and Engineering, Rajalakshmi Engineering College


For example:

if x % 2 == 0:
print('x is even')
else:
print('x is odd')

If the remainder when x is divided by 2 is 0, then we know that x is even, and the program displays an
appropriate message. If the condition is false, the second set of statements runs. Since the condition
must be true or false, exactly one of the alternatives will run. The alternatives are called
branches, because they are branches in the flow of execution

2.11.3 The elif Statement

 Sometimes there are more than two possibilities and we need more than two branches.
One way to express a computation like that is a chained conditional.
 The elif statement allows you to check multiple expressions for TRUE and execute a block of
code as soon as one of the conditions evaluates to TRUE.
 Similar to the else, the elif statement is optional. However, unlike else, for which there
can be at most one statement, there can be an arbitrary number of elif statements
following an if.
 Core Python does not provide switch or case statements as in other languages, but we can use
if..elif...statements to simulate switch case

Syntax

if(test-condition-1):
statement-1
elif(test-condition-2):
statement-2
. . .
. . .
elif(test-condition-n):
28 Department of Computer Science and Engineering, Rajalakshmi Engineering College
statement-n
else:
default-statement
statement-x

For example:

if x < y:
print('x is less than y')
elif x > y:
print('x is greater than y')
else:
print('x and y are equal')

elif is an abbreviation of “else if”. Again, exactly one branch will run. There is no limit on the number
of elif statements. If there is an else clause, it has to be at the end, but there doesn’t have to be one.

if choice == 'a':
draw_a()
elif choice == 'b':
draw_b()
elif choice == 'c':
draw_c()

29 Department of Computer Science and Engineering, Rajalakshmi Engineering College


Each condition is checked in order. If the first is false, the next is checked, and so on. If one of them is
true, the corresponding branch runs and the statement ends. Even if more than one condition is true,
only the first true branch runs.

2.11.4 NESTED CONDITIONALS (nested if...else STATEMENT)

One conditional can also be nested within another.

Syntax

if(test-condition-1):
if(test-condition-2):
statement-1
else:
statement-2
else:
statement-3
statement-x

2.12 PYTHON ITERATION

Iteration - is the ability to run a block of statements repeatedly.

2.12.1 REASSIGNMENT

As you may have discovered, it is legal to make more than one assignment to the same
variable. A new assignment makes an existing variable refer to a new value (and stop referring
to the old value).

>>> x=
5

30 Department of Computer Science and Engineering, Rajalakshmi Engineering College


>>>
x
5

>>> x=
7
>>>
x
7

The first time we display x, its value is 5; the second time, its value is 7.

Python uses the equal sign (=) for assignment, it is tempting to interpret a statement like a = b as a
mathematical proposition of equality; that is, the claim that a and b are equal. But this interpretation is
wrong.

First, equality is a symmetric relationship and assignment is not. For example, in


mathematics, if a=7 then 7=a. But in Python, the statement a = 7 is legal and 7 = a is not.

Also, in mathematics, a proposition of equality is either true or false for all time. If a=b now, then a
will always equal b. In Python, an assignment statement can make two variables equal, but they
don’t have to stay that way:

>>> a=
5
>>> b = a # a and b are now equal
>>> a = 3 # a and b are no longer equal

>>> b
5

The third line changes the value of a but does not change the value of b, so they are no longer equal.

Reassigning variables is often useful, but you should use it with caution. If the values of
variables change frequently, it can make the code difficult to read and debug.

31 Department of Computer Science and Engineering, Rajalakshmi Engineering College


2.12.2 UPDATING VARIABLES

A common kind of reassignment is an update, where the new value of the variable depends on the old.

>>> x = x + 1

This means “get the current value of x, add one, and then update x with the new value.”
If you try to update a variable that doesn’t exist, you get an error, because Python evaluates
the right side before it assigns a value to x:

>>> x = x + 1
NameError: name 'x' is not defined

Before you can update a variable, you have to initialize it, usually with a simple assignment:

>>> x=0
>>> x=x+1

Updating a variable by adding 1 is called an increment; subtracting 1 is called a decrement.

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

Python programming language provides following types of loops to handle looping


requirements

Loop Type Description


while loop Repeats a statement or group of statements while a given
condition is TRUE. It tests the condition before executing the loop body
for loop Executes a sequence of statements multiple times and abbreviates the
code that manages the loop variable
nested loops You can use one or more loop inside any another while, for loop.

32 Department of Computer Science and Engineering, Rajalakshmi Engineering College


2.12.3 While Loop

A while loop statement in Python programming language repeatedly executes a target statement
as long as a given condition is true.

Syntax

while(test-condition):
body of the loop
statement-x

 Here, statement(s) may be a single statement or a block of statements.


 The condition may be any expression, and true is any non-zero value. The loop iterates
while the condition is true.
 When the condition becomes false, program control passes to the line immediately
following the loop.
 In Python, all the statements indented by the same number of character spaces after a
programming construct are considered to be part of a single block of code. Python uses
indentation as its method of grouping statement.

Here is a version of countdown that uses a while statement:

while n > 0:
print(n)
n=n-1
print('Blastoff!')

33 Department of Computer Science and Engineering, Rajalakshmi Engineering College


You can almost read the while statement as if it were English. It means, “While n is greater than 0,
display the value of n and then decrement n. When you get to 0, display the word Blastoff!”

More formally, here is the flow of execution for a while statement:

1. Determine whether the condition is true or false.


2. If false, exit the while statement and continue execution at the next statement.
3. If the condition is true, run the body and then go back to step 1.

This type of flow is called a loop because the third step loops back around to the top.

The body of the loop should change the value of one or more variables so that the condition becomes
false eventually and the loop terminates. Otherwise the loop will repeat forever, which is called
an infinite loop.

In the case of countdown, we can prove that the loop terminates: if n is zero or negative, the loop never
runs. Otherwise, n gets smaller each time through the loop, so eventually we have to get to 0.

For some other loops, it is not so easy to tell. For example:

while n != 1:
print(n)
if n % 2 == 0: # n is even
n=n/2
else: # n is odd
n = n*3 + 1

The condition for this loop is n != 1, so the loop will continue until n is 1, which makes the condition
false.

Each time through the loop, the program outputs the value of n and then checks whether it is even or
odd. If it is even, n is divided by 2. If it is odd, the value of n is replaced with n*3 + 1. For example, if
the argument passed to n is 3, the resulting values of n are 3, 10, 5, 16, 8, 4, 2,
1.

Since n sometimes increases and sometimes decreases, there is no obvious proof that n will ever reach
1, or that the program terminates. For some particular values of n, we can prove termination. For
example, if the starting value is a power of two, n will be even every time through the loop until it
reaches 1. The previous example ends with such a sequence, starting
with 16.
34 Department of Computer Science and Engineering, Rajalakshmi Engineering College
2.12.4 THE for STATEMENT

A for statement is also called a loop because the flow of execution runs through the body and then
loops back to the top.

Computers are often used to automate repetitive tasks. Repeating identical or similar tasks without
making errors is something that computers do well and people do poorly. In a computer
program, repetition is also called iteration.

The syntax of a for statement has a header that ends with a colon and an indented body. The body can
contain any number of statements.

Syntax

for variable in sequence:


body of the loop;
statement-x;

For example:

for i in range(4):
print('Hello!')
You should see something like this:
Hello!
Hello!
Hello!
Hello!

This is the simplest use of the for statement. In this case, it runs the body four times.

35 Department of Computer Science and Engineering, Rajalakshmi Engineering College


2.12.5 break STATEMENT

Sometimes you don’t know it’s time to end a loop until you get halfway through the body. In that case
you can use the break statement to jump out of the loop. break is used to break out of the innermost
loop.

For example, suppose you want to take input from the user until they type done. You could write:

while True:
line = input('> ')
if line == 'done':
break
print(line)
print('Done!')

The loop condition is True, which is always true, so the loop runs until it hits the break
statement.

Each time through, it prompts the user with an angle bracket. If the user types done, the break
statement exits the loop. Otherwise the program echoes whatever the user types and goes back to the
top of the loop. Here’s a sample run:

>not done
not done
>done
Done!

This way of writing while loops is common because you can check the condition anywhere in the loop
(not just at the top) and you can express the stop condition affirmatively (“stop when this
happens”) rather than negatively (“keep going until that happens”).

The while loop to print the squares of all the odd numbers below 10, can be modified using the break
statement, as follows

i=1
while True:
print (i * i)
i=i+2
if(i > 10):
break

36 Department of Computer Science and Engineering, Rajalakshmi Engineering College


produces the output
1
9
25
49
81

2.12.6 continue STATEMENT

continue is used to skip execution of the rest of the loop on this iteration and continue to the end of this
iteration.

For example we wish to print the squares of all the odd numbers below 10, which are not multiples
of 3, we would modify the for loop as follows.

for n in range(1, 10, 2):


if n % 3 == 0:
continue
print (n * n)

produces the output


1
25
49

2.12.7 pass STATEMENT

There is no limit on the number of statements that can appear in the body, but there has to be at least
one. Occasionally, it is useful to have a body with no statements (usually as a place keeper for code you
haven’t written yet). In that case, you can use the pass statement, which does nothing.

if x < 0:
pass # TODO: need to handle negative values!

“pass” statement acts as a place holder for the block of code. It is equivalent to a null
operation. It literally does nothing. It can used as a place holder when the actual code
implementation for a particular block of code is not known yet but has to be filled up later.

37 Department of Computer Science and Engineering, Rajalakshmi Engineering College


Review Questions

Part – B

1) Differentiate compiler and interpreter.

An interpreter reads a high-level program and executes it, meaning that it does what the
program says. It processes the program a little at a time, alternately reading lines and performing
computations.
A compiler reads the program and translates it completely before the program starts running. In this
context, the high-level program is called the source code, and the translated program is called the object code or
the executable. Once a program is compiled, you can execute it repeatedly without further translation.

2) List some of the features of Python.

 Simple and easy to learn


 Portable
 Interactive mode
 Broad standard library
 Extendable
 Databases
 GUI Programming
 Scalable

3) Differentiate interactive and script mode. (or) How can you run Python?

In interactive mode, you type Python programs and the interpreter displays the result:
>>> 1 + 1
2
The chevron, >>>, is the prompt the interpreter uses to indicate that it is ready. If you type 1 +
1, the interpreter replies 2.Alternatively, you can store code in a file and use the interpreter to execute the
contents of the file, which is called a script. By convention, Python scripts have names that end with .py.

4) What are values and types in Python?

A value is one of the basic things a program works with, like a letter or a number. Some
values we have seen so far are 2, 42.0, and 'Hello, World!'These values belong to different types: 2 is an integer,
42.0 is a floating-point number, and 'Hello, World!' is a string, so-called because the letters
it contains are strung together.

38 Department of Computer Science and Engineering, Rajalakshmi Engineering College


5) How can you give comments in Python? Give example.

These notes are called comments, and they start with the #symbol:
Eg: # compute the percentage of the hour that has elapsed percentage = (minute * 100) / 60
In this case, the comment appears on a line by itself. You can also put comments at the end of a line:
percentage = (minute * 100) / 6 # percentage of an hour
Everything from the # to the end of the line is ignored - it has no effect on the execution of the program.

6) Define variable.

A variable is basically a name that represents (or refers to) some value. Variable are reserved
memory locations to store values.

7) Give the rules for naming a variable in Python.

 They can contain both letters and numbers, but they can’t begin with a number.
 It is legal to use uppercase letters, but it is conventional to use only lowercase for variables names.
 The underscore character, _, can appear in a name. It is often used in names with multiple words,
such as your_name or airspeed_of_unladen_swallow.
 The interpreter uses keywords to recognize the structure of the program, and they cannot be used as
variable names.

8) Define keywords.

Keywords are the reserved words in Python. We cannot use keywords as variable name,
function name or any other identifier. They are used to define the syntax and structure of the
Python language. In Python, keywords are case sensitive.

9) Define identifiers.

An identifier is a name which is used to identify a variable, function, class, module or any other
object.

10) Give the rules for naming an identifier in Python.

 They can contain both letters and numbers, but they can’t begin with a number.
 The underscore character, _, can appear in an identifier. It is often used in names with multiple
words, such as your_name or airspeed_of_unladen_swallow.
 The interpreter uses keywords to recognize the structure of the program, and theycannot be
used as identifier names.

39 Department of Computer Science and Engineering, Rajalakshmi Engineering College


11) List the types of operators in Python.

 Arithmetic operators
 Relational or comparison operators
 Assignment operators
 Bitwise operators
 Logical operators
 Membership operators
 Identity operators

12) What is the purpose of floor division? Give example. (or) What is the purpose of //
operator? Give example.

The floor division operator, //, divides two numbers and rounds down to an integer. For
example, suppose the run time of a movie is 105 minutes. You might want to know how long that is in
hours. Floor division returns the integer number of hours, dropping the fraction part:
>>> minutes = 105
>>> hours = minutes // 60
>>> hours
1

13) What is the purpose of modulus operator? Give example.

The modulus operator, %, which divides two numbers and returns the remainder:
>>> remainder = minutes % 60
>>> remainder
45
The modulus operator is more useful than it seems. For example, you can check whether one number is
divisible by another - if x % y is zero, then x is divisible by y.

14) List out the controls for decision making statements.

 if statement (conditional)
 if...else statement (alternative)
 if...elif...else statement (chained conditional)
 Nested if...else statement (nested conditional)

15) Write the syntax and draw the flow chart for if statement in Python.

Syntax:
if(test-expression):
statement-block(s)
statement-x

40 Department of Computer Science and Engineering, Rajalakshmi Engineering College


Flowchart

16) Write the syntax and draw the flow chart for if...else statement in Python.

Syntax
if(test-expression):
true-block-statement(s)
else:
false-block-statement(s)
statement-x

Flowchart

17) Write the syntax and draw the flow chart for if...elis...else statement in Python.

Syntax
if(test-condition-1):
statement-1
elif(test-condition-2):
statement-2
...
elif(test-condition-n):
statement-n
else:
default-statement

41 Department of Computer Science and Engineering, Rajalakshmi Engineering College


statement-x

Flowchart

18) Write the syntax and draw the flow chart for nested if...else statement in Python.

Syntax
if(test-condition-1):
if(test-condition-2):
statement-1
else:
statement-2
else:
statement-3
statement-x

Flowchart

42 Department of Computer Science and Engineering, Rajalakshmi Engineering College


19) List out the operator precedence in Python.

Parentheses have the highest precedence and can be used to force an expression to evaluate in the order
you want. Since expressions in parentheses are evaluated first, 2 * (3-1)is 4, and (1+1)**(5-2) is 8.
You can also use parentheses to make an expression easier to read, as in (minute
* 100) / 60, even if it doesn’t change the result.
Exponentiation has the next highest precedence, so 1 + 2**3 is 9, not 27, and 2 * 3**2 is18, not
36.
Multiplication and Division have higher precedence than Addition and Subtraction. So 2*3-1
is 5, not 4, and 6+4/2 is 8, not 5.
Operators with the same precedence are evaluated from left to right (except
exponentiation). So in the expression degrees / 2 * pi, the division happens first and the result is
multiplied by pi. To divide by , you can use parentheses or write degrees / 2 / pi.

Part – C

1) Explain in detail about different operators in python with suitable example


2) Explain in detail about python conditions with suitable example
3) Explain in detail about python iteration with suitable example

SEQUENCE PROGRAMS

1) Python Program to Add Two Numbers


2) Python Program to find Area and Circumference of Circle
3) Python Program to calculate average of two numbers. Print their deviation
4) Python Program to perform arithmetic operations
5) Python Program to Find the Square Root of a number
6) Python Program to interchange the Values of Two Numbers Using a 3rd Variable
7) Python Program to interchange the Values of Two Numbers without Using a 3rd
Variable
8) Python Program to Convert Celsius to Fahrenheit
9) Python Program to Convert Fahrenheit to Celsius
10) Python Program to Compute Simple Interest
11) Python Program to Compute Compound Interest
12) Python Program to calculate the total and average of 5 Subject Marks
13) Python Program to Find ASCII Value of Character

SELECTION PROGRAMS

1) Python Program to check if a Number is odd or even


2) Python Program to find the biggest of 2 numbers
3) Python Program to Check whether the person is eligible to vote or not
4) Python Program to Check whether the person is eligible to get driving licence
43 Department of Computer Science and Engineering, Rajalakshmi Engineering College
5) Python Program to Check whether the person age is in teenage or not
6) Python Program to check if a number is positive, negative or zero
7) Python Program to Check Leap Year using all conditions
8) Python Program to Find the Largest Among Three distinct Numbers
9) Python Program to Check Whether a Character is Vowel or consonant
10) Python Program to Check Whether a Character is Alphabet, Digit or Special
Characters
11) Python Program to find all Roots of a Quadratic equation
12) Python Program to Take in the Marks of 6 Subjects and Display the Student Grades
13) Python Program to enter the month number as input and displays output as month name
14) Python Program to calculate Electricity Bill for Domestic Consumers

ITERATION PROGRAMS

1) Python Program to Find the Sum of Natural Numbers


2) Python Program to Display the multiplication Table
3) Python Program to Check the given number is Armstrong Number or not.
4) Python Program to Find Armstrong Number in a given Interval
5) Python Program to Print the Fibonacci sequence
6) Python Program to Check the given number is Prime Number or not.
7) Python Program to print all Prime Numbers in a given Interval
8) Python Program to Find the Factorial of a Number
9) Python Program to Find the GCD of Two Numbers
10) Python Program to Make a Simple Calculator
11) Python Program to reverse the given number
12) Python Program to check the given number is palindrome number or not.
13) Python Program to Find the Sum of Digits in a Number
14) Python Program to Count the Number of Digits in a Number
15) Python Program to Find the largest Digit of a Number
16) Python Program to Find Those Numbers which are Divisible by 7 and Multiple of 5 in a Given
Range of Numbers
17) Python Program to Print all Integers that Aren't Divisible by Either 2 or 3 and Lie
between 1 and 50
18) Python Program to Print all Numbers in a Range Divisible by a Given Number
19) Python program to find the given number is perfect number or not
20) Python program to find the value of xn
21) Python program to print the numbers that are divisible by a given number
22) Python Program that displays all leap years from the year 1900 to 2100
23) Python Program to Find Factors of Number

44 Department of Computer Science and Engineering, Rajalakshmi Engineering College

You might also like