Unit - II - Notes Pyth
Unit - II - Notes Pyth
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.
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.
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.
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
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
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
Check for certain conditions and run the appropriate code. repetition: - Perform some
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.
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.
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.
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:
>>
>
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:
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)
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.
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.
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:
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.
In Python 2, the print statement is slightly different; it is not a function, so it doesn’t use
parentheses.
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.
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:
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:
That’s not what we expected at all! Python interprets 1,000,000 as a comma-separated sequence
of integers.
Python has various standard data types that are used to define the operations possible on them
and the storage method for each of them.
Numbers
String
List
Tuple
Dictionary
Number data types store numeric values. Number objects are created when you assign a
value to them.
var1 = 1
var2 = 10
Example:
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
Example:
Output:
Example:
Output:
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:
Output:
['abcd', 786, 2.23, 'john', 70.2]
list[2] = 1000
print (list)
Output:
['abcd', 786, 1000, 'john', 70.2]
Example:
Output:
('abcd', 786, 2.23, 'john', 70.2)
Example:
Output:
Shows an Error Message
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.
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.
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.
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.
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.
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.
>>> 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.
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:
Output:
Enter the Value
We use the print() function to output data to the standard output device (screen).
The actual syntax of the print() function is print(*objects,
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.
Output:
Enter First Number:25
Enter Second Number:50
The sum of 25 and 50 is 75
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
Example:
These operators compare the values on either sides of them and decide the relation among
them. They are also called Relational operators.
Example:
Output:
Enter Person Age:15
The Person Falls into Teenage
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)
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
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
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
Python’s membership operators test for membership in a sequence, such as strings, lists, or
tuples.
Output:
Input a letter of the alphabet: M M
is a consonant.
Example:
Output:
Enter the Number1:20
Enter the Number2:20
Number1 and Number2 have same identity
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
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
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
Example:
if True:
print "True"
else:
print "False"
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']
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')
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
word = 'word'
sentence = "This is a sentence." paragraph =
"""This is a paragraph. It is made up of multiple
lines and sentences."""
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)
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.
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.
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
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
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()
Syntax
if(test-condition-1):
if(test-condition-2):
statement-1
else:
statement-2
else:
statement-3
statement-x
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
>>> 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.
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.
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
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
while n > 0:
print(n)
n=n-1
print('Blastoff!')
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.
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 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.
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
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.
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.
Part – B
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.
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.
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.
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.
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.
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.
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
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.
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
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
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
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
SEQUENCE PROGRAMS
SELECTION PROGRAMS
ITERATION PROGRAMS