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

Python Programming UNIT 1

Python is a versatile programming language created by Guido van Rossum in 1991, used for web development, software development, and data handling. It features a simple syntax, is cross-platform, and supports various data types including numbers, strings, lists, and dictionaries. The document also covers installation, running scripts, and the basics of variables and expressions.

Uploaded by

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

Python Programming UNIT 1

Python is a versatile programming language created by Guido van Rossum in 1991, used for web development, software development, and data handling. It features a simple syntax, is cross-platform, and supports various data types including numbers, strings, lists, and dictionaries. The document also covers installation, running scripts, and the basics of variables and expressions.

Uploaded by

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

PYTHON PROGRAMMING

UNIT 1
What is Python?

Python is a popular programming language. It was created by Guido van Rossum, and released in
1991.

It is used for:

 web development (server-side),


 software development,
 mathematics,
 System scripting.

What can Python do?

 Python can be used on a server to create web applications.


 Python can be used alongside software to create workflows.
 Python can connect to database systems. It can also read and modify files.
 Python can be used to handle big data and perform complex mathematics.
 Python can be used for rapid prototyping, or for production-ready software development.

Why Python?

 Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
 Python has a simple syntax similar to the English language.
 Python has syntax that allows developers to write programs with fewer lines than some other
programming languages.

Debugging:

A debugger is a program that can help you find out what is going on in a computer program.

You can stop the execution at any prescribed line number, print out variables, continue
execution, stop again, execute statements one by one, and repeat such actions until you have
tracked down abnormal behavior and found bugs.

Formal and Natural Language:

Natural languages are full of ambiguity, which people deal with by using contextual clues and
other information.

Formal languages are designed to be nearly or completely unambiguous, which means that
any statement has exactly one meaning, regardless of context.

Python Features:

 Easy to Code. Python is a very high-level programming language, yet it is effortless to learn. ...
 Easy to Read. Python code looks like simple English words. ...
 Free and Open-Source. ...
 Robust Standard Library. ...
 Interpreted. ...
 Portable. ...
 Object-Oriented and Procedure-Oriented. ...
 Extensible.

2.1 THE PYTHONINTERPRETER


Python is a cross-platform programming language, meaning, it runs on multiple
platforms like Windows, Mac OS X, Linux, Unix and has even been ported to the Java and
.NET virtual machines. It is free and open source.
Python Installing:
Step 1 — Downloading the Python Installer.
Step 2 — Running the Executable Installer.
Step 3 — Adding Python to the Environment Variables (optional)
Step 4 — Verify the Python Installation.
Python Running:

The most basic and easy way to run a Python script is by using the python command.
You need to open a command line and type the word python followed by the path to your script file like
this: python first_script.py Hello World! Then you hit the ENTER button from the keyboard, and that's it

2.1.1 Starting the INTERPRETER:


The Python interpreter is a program that reads and executes Python code.Even
though most of today‘s Linux and Mac have Python preinstalled in it, the version might be out-
of-date. So, it is always a good idea to install the most current version.

After installation, the python interpreter lives in the installed directory.

Now there are two ways to start Python.

Python
Mode

Script Interactive
Mode Mode
Figure 2.1 Modes of Python Interpreter
2.1.2 INTERACTIVE MODE:
Typing python in the command line will invoke the interpreter in interactive mode.
When it starts, you should see output like this:

This prompt can be used as a calculator. To exit this mode type exit() or quit() and press
enter.

2.1.3 ScriptMode
This mode is used to execute Python program written in a file. Such a file is called a
script. Scripts can be saved to disk for future use. Python scripts have the extension .py,
meaning that the filename ends with.py.

For example:helloWorld.py
To execute this file in script mode we simply write python helloWorld.py at the command
prompt.

2.1.4 Integrated Development Environment (IDE)

We can use any text editing software to write a Python script file.

We just need to save it with the .py extension. But using an IDE can make our life a lot easier.
IDE is a piece of software that provides useful features like code hinting, syntax highlighting
and checking, file explorers etc. to the programmer for application development.

Using an IDE can get rid of redundant tasks and significantly decrease the time required for
application development.

IDEL is a graphical user interface (GUI) that can be installed along with the Python
programming language and is available from the official website.

We can also use other commercial or free IDE according to our preference .Py Scripter IDE
is one of the Open source IDE.
2.1.5 Hello WorldExample
Now that we have Python up and running, we can continue on to write our first Python
program.

Type the following code in any text editor or an IDE and save it as helloWorld.py

print("Helloworld!")

Now at the command window, go to the loaction of this file. You can use the cd command to
change directory.

To run the script, type, python helloWorld.py in the command window. We should be able to
see the output as follows:

Helloworld!

If you are using PyScripter, there is a green arrow button on top. Press that button or
press Ctrl+F9 on your keyboard to run the program.

In this program we have used the built-in function print(), to print out a string to the
screen. String is the value inside the quotation marks, i.e. Helloworld!.

2.2 VALUES AND TYPES:


A value is one of the basic things a program works with, like a letter or a number. Some
example values are 5, 83.0, and 'Hello, World!'.These values belong to different types: 5 is an
integer, 83.0 is a floating-point number, and'Hello, World!' is a string, so-called because the
letters it contains are strung together.If you are not sure what type a value has, the interpreter
can tellyou:
>>>type(5)
<class'int'>
>>>type(83.0)
<class 'float'>
>>>type('Hello, World!')
<class 'str'>

That‘s not what we expected at all! Python interprets 1,000,000 as a comma- separated
sequence of integers. We‘ll learn more about this kind of sequence later.

2.2.2 Standard DataTypes


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 −
2.2.2.1 Numbers
2.2.2.2 String
2.2.2.3 List
2.2.2.4 Tuple
2.2.2.5 Dictionary
2.2.1.1 PythonNumbers
Number data types store numeric values. Number objects are created when you assign
a value to them. For example –
var1 =1
var2 =10
You can also delete the reference to a number object by using the del statement. The
syntax of the del statement is −
delvar1[,var2[,var3[ ..... ,varN]]]]
You can delete a single object or multiple objects by using the del statement. For
example −
delvar
delvar_a,var_b
Python supports four different numerical types −
 int (signedintegers)
 long (long integers, they can also be represented in octal andhexadecimal)
 float (floating point realvalues)
 complex (complexnumbers)

Python allows you to use a lowercase l with long, but it is recommended that you use
only an uppercase L to avoid confusion with the number 1. Python displays long integers with an
uppercase L.
 A complex number consists of an ordered pair of real floating-point numbers denoted
by x + yj, where x and y are the real numbers and j is the imaginaryunit.
2.2.1.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 theend.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the
repetition operator. For example–

str = 'Python Programming'


printstr # Prints complete string
printstr[0] # Prints first character of the string
printstr[-1] # Prints last character of the string
printstr[2:5] # Prints characters starting from 3rd to 5th
printstr[2:] # Prints string starting from 3rd character
printstr * 2 # Prints string two times
printstr + " Course" # Prints concatenated string
This will produce the following result –

Python Programming
P
g
tho
thon Programming
Python ProgrammingPython Programming
Python Programming Course
2.2.1.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 datatype.

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. For
example −

list = [ 'Hai', 123 , 1.75, 'vinu', 100.25]


smalllist = [251, 'vinu']
print list # Prints complete list
print list[0] # Prints first element of the list
print list[-1] # Prints last element of the list
print list[1:3] # Prints elements starting from 2nd till 3rd
print list[2:] # Prints elements starting from 3rd element
printsmalllist * 2 # Prints list two times
print list + smalllist # Prints concatenated lists
This produces the following result –

['Hai', 123, 1.75, 'vinu', 100.25]


Hai
100.25
[123, 1.75]
[1.75, 'vinu', 100.25]
[251, 'vinu', 251, 'vinu']
['Hai', 123, 1.75, 'vinu', 100.25, 251, 'vinu']
2.2.1.4 Python BOOLEAN:
A Boolean type was added to Python 2.3. Two new constants were added
tothebuiltinmodule, True and False. True and False are simply set to integer values of 1 and
0 and aren't a differenttype.
The type object for this new type is named bool; the constructor for it takes any Python value
and converts it to True or False.

>>>bool(1)
True
>>>bool(0)
False
Python's Booleans were added with the primary goal of making code clearer.
For example, if you're reading a function and encounter the statement return 1, you might
wonder whether the 1 represents a Boolean truth value, an index, or a coefficient that multiplies
some other quantity. If the statement is return True, however, the meaning of the return value
is quite clear.

We will discuss about data types like Tuple, Dictionary in Unit IV.

2.2.3 Data Type Conversion

Sometimes, you may need to perform conversions between the built-in types.
To convert between types, you simply use the type name as a function.

There are several built-in functions to perform conversion from one data type
to another. These functions return a new object representing the converted value.

Table 2.2: Data Type Conversion

Function Description
float(x) Converts x to a floating-point number.

complex(real Creates a complex number.


[,imag])

str(x) Converts object x to a string representation.

repr(x) Converts object x to an expression string.

eval(str) Evaluates a string and returns an object.

list(s) Converts s to a list.

chr(x) Converts an integer to a character.

unichr(x) Converts an integer to a Unicode character.

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

hex(x) Converts an integer to a hexadecimal string.

oct(x) Converts an integer to an octal string.


2.3 VARIABLES:

A variable is a name that refers to a value.


Variable reserved memory locations to store values. This means that when you
create a variable you reserve some space in memory.
Based on the data type of a variable, the interpreter allocates memory and
decides what can be stored in the reserved memory.

2.3.2 AssignmentStatements

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

>>>message = 'Introducing Python Variable'


>>>num = 15
>>>radius = 5.4
This example makes three assignments.
The first assigns a string to a new variable named message; the second gives
the integer 15 to num; the third assigns floating point value 5.4 to variable radius.

2.3.3 Variable Names

Programmers generally choose names for their variables that are meaningful

The Rules

2.3.3.1 Variables names must start with a letter or an underscore, suchas:


2.3.3.1.1 _mark
2.3.3.1.2 mark_
2.3.3.2 The remainder of your variable name may consist of letters, numbers
andunderscores.
2.3.3.2.1 subject1
2.3.3.2.2 my2ndsubject
2.3.3.2.3 un_der_scores
2.3.3.3 Names are casesensitive.
2.3.3.3.1 case_sensitive, CASE_SENSITIVE, and Case_Sensitive are
each a different variable.
2.3.3.4 Can be any (reasonable)length
2.3.3.5 There are some reserved (KeyWords)words which you cannot use as a
variable name because Python uses them for otherthings.

The interpreter uses keywords to recognize the structure of the program, and
they cannot be used as variable names.
Python 3 has these keywords:

False class finally is return None

continue for lambda try True def

from nonlocal while and del global

not with as elif if or

yield assert else import pass break

except in raise

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.

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

>>>1book = 'python'
SyntaxError: invalidsyntax
>>>more@ = 1000000
SyntaxError: invalidsyntax
>>>class = 'Fundamentals of programming'
SyntaxError: invalid syntax
1book is illegal because it begins with a number. more@ is illegal because it
contains an illegal character, @. class is illegal because it is a keyword.
Good Variable Name

2.3.3.6 Choose meaningful name instead of short name. roll_no is better thanrn.
2.3.3.7 Maintain the length of a variable name. Roll_no_of_a_student is toolong?
2.3.3.8 Be consistent; roll_no ororRollNo
2.3.3.9 Begin a variable name with an underscore(_) character for a specialcase.
2.4 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:
>>> 50
50
>>> 10<5
False
>>> 50+20
70
When you type an expression at the prompt, the interpreter evaluates it, which
means that it finds the value of the expression.
A statement is a unit of code that has an effect, like creating a variable or
displaying a value.

>>> n = 25

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

2.4.2 Difference Between a Statement and anExpression


A statement is a complete line of code that performs some action, while an
expression is any section of the code that evaluates to a value. Expressions can be combined
―horizontally‖into larger expressionsusing operators, while statementscan only becombined
―vertically‖by writing one after another, or with block constructs. Every expression can be
used as a statement, but most statements cannot be used asexpressions.
2.5 OPERATORS:
In this section, you'll learn everything about different types of operators in
Python, their syntax and how to use them with examples.

Operators are special symbols in Python that carry out computation. The value
that the operator operates on is called the operand.

For example:

>>>10+5
15

Here, + is the operator that performs addition. 10 and 5 are the operands and 15 is the output
of the operation. Python has a number of operators which are classified below.

 Arithmeticoperators
 Comparison (Relational) operators
 Logical (Boolean)operators
 Bitwiseoperators
 Assignmentoperators
 Specialoperators

2.5.2 ArithmeticOperators
Arithmetic operators are used to perform mathematical operations like addition, subtraction,
multiplication etc.
Table 2.3: Arithmetic operators in Python

Operator Meaning Example


+ Add two operands or unary plus x + y
+2
- Subtract right operand from the left or unary minus x - y
-2
* Multiply two operands x*y
/ Divide left operand by the right one (always results into x/y
float)
% Modulus - remainder of the division of left operand by the x % y(remainder
right of x/y)
// Floor division - division that results into whole number x // y
adjusted to the left in the number line
** Exponent - left operand raised to the power of right x**y (x to the
power y)

Example
x =7
y =3
print('x + y =',x+y)
print('x - y =',x-y)
print('x * y =',x*y)
print('x / y =',x/y)
print('x // y =',x//y)
print('x % y =',x%y)
print('x ** y =',x**y)
When you run the program, the output will be:
x + y = 10
x-y=4
x * y =21
x / y = 2.3333333333333335
x // y = 2
x%y=1
x ** y = 343
2.5.3 Comparison or RelationalOperators
Comparison operators are used to compare values. It either
returns True or False according to thecondition.

Table 2.4:Comparison Operators in Python

Operator Meaning Example


> Greater that - True if left operand is greater than the right x>y
< Less that - True if left operand is less than the right x<y
== Equal to - True if both operands are equal x == y
!= Not equal to - True if operands are not equal x != y
>= Greater than or equal to - True if left operand is greater than or equal x >= y
to the right
<= Less than or equal to - True if left operand is less than or equal to the x <= y
right

Example
x =5
y =7
print('x > y is',x>y)
print('x < y is',x<y)
print('x == y is',x==y)
print('x != y is',x!=y)
print('x >= y is',x>=y)
print('x <= y is',x<=y)
When you run the program, the output will be:
x >y is False
x <y is True
x == y is False
x != y is True
x >= y is False
x <= y is True
2.5.4 Logical Operators
Logical operators are the and, or, not operators.

Table 2.5: Logical operators in Python

Operator Meaning Example


and True if both the operands are true x and y
or True if either of the operands is true x or y
not True if operand is false (complements the operand) not x

Example
x = True
y = False
print('x and y is',x and y)
print('x or y is',x or y)
print('not x is',not x)
When you run the program, the output will be:
x and y is False
x or y is True
not x is False
2.5.5 BitwiseOperators
Bitwise operators act on operands as if they were string of binary digits.
Itoperates bit by bit, hence the name.

For example, 2 is 10 in binary and 7 is 111.

In Table 2.6: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)

Table 2.6: Bitwise operators in Python

Operator Meaning Example


& Bitwise AND x& y = 0 (0000 0000)
| Bitwise OR x | y = 14 (0000 1110)
~ Bitwise NOT ~x = -11 (1111 0101)
^ Bitwise XOR x ^ y = 14 (0000 1110)
>> Bitwise right shift x>> 2 = 2 (0000 0010)
<< Bitwise left shift x<< 2 = 40 (0010 1000)

Example
x=10
y=4
print('x& y=',x&y)
print('x | y=',x | y)
print('~x=',~x)
print('x ^ y=',x ^ y)
print('x>> 2=',x>> 2)
print('x<< 2=',x<<2)
When you run the program, the output will be:
x&y= 0
x | y=14
~x= -11
x ^ y= 14
x>> 2=2
x<< 2= 40
2.5.6 AssignmentOperators
Assignment operators are used in Python to assign values to variables.

a = 10 is a simple assignment operator that assigns the value 10 on the right to


the variable a on the left.

There are various compound operators in Python like a += 10 that adds to the
variable and later assigns the same. It is equivalent to a = a + 10.
Table 2.7: Assignment operators in Python

Operator Example Equivatent to


= x=5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x-5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x%5
//= x //= 5 x = x // 5
**= x **= 5 x = x ** 5
&= x &= 5 x=x&5
|= x |= 5 x=x|5
^= x ^= 5 x=x^5
>>= x >>= 5 x = x >> 5
<<= x <<= 5 x = x << 5
2.5.7 Special Operators
Python language offers some special type of operators like the identity
operator or the membership operator. They are described below withexamples.

2.5.6.1 Identity Operators


is and is not are the identity operators in Python. They are used to check if two values (or
variables) are located on the same part of the memory. Two variables that are equal does not
imply that they are identical.

Table 2.8: Identity operators in Python

Operator Meaning Example


is True if the operands are identical (refer to the same object) x is True
is not True if the operands are not identical (do not refer to the same x is not
object) True

Example
x1 =7
y1 =7
x2 = 'Welcome'
y2 = 'Welcome'
x3 =[1,2,3]
y3 =[1,2,3]
print(x1 is not y1)
print(x2 is y2)
print(x3 is y3)
When you run the program, the output will be:
False
True
False

Here, we see that x1 and y1 are integers of same values, so they are equal as
well as identical. Same is the case with x2 and y2 (strings).But x3 and y3 are list. They are equal
but not identical. Since list are mutable (can be changed), interpreter locates them separately in
memory although they are equal.

2.5.6.2 MembershipOperators
in and not in are the membership operators in Python. They are used to test whether a value
or variable is found in a sequence (string,list, tuple, set and dictionary).

Table 2.9: Membership operators in Python

Operator Meaning Example


in True if value/variable is found in the sequence 5 in x
not in True if value/variable is not found in the sequence 5 not in x

Example
x = 'Python Programming'
print('Program' not in x)
print('Program' in x)
print('program' in x)
When you run the program, the output will be:
False
True
False
Here, ' Program ' is in x but ' program' is not present in x, since Python is case
sensitive.
2.6 PRECEDENCE OF PYTHON OPERATORS:
The combination of values, variables,operators and function calls is termed as
an expression. Python interpreter can evaluate a valid expression. When an expression contains
more than one operator, the order of evaluation dependson the Precedence of operations.

For example, multiplication has higher precedence than subtraction.

>>> 20 – 5*3
5
But we can change this order using parentheses () as it has higher precedence.
>>> (20 - 5) *3
45
The operator precedence in Python are listed in the following table. It is in
descending order, upper group has higher precedence than the lower ones.

Table 2.10: Operator precedence rule in Python

Operators Meaning
() Parentheses
** Exponent
+x, -x, ~x Unary plus, Unary minus, Bitwise NOT
*, /, //, % Multiplication, Division, Floor division, Modulus
+, - Addition, Subtraction
<<, >> Bitwise shift operators
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
==, !=, >, >=, <, <=, is, is not, in, not in Comparisions, Identity, Membership operators
not Logical NOT
and Logical AND
or Logical OR

2.7 ASSOCIATIVITY OF PYTHON OPERATORS

We can see in the above table that more than one operator exists in the same
group. These operators have the same precedence.

When two operators have the same precedence, associativity helps to


determine which the order of operations.

Associativity is the order in which an expression is evaluated that has multiple


operator of the same precedence. Almost all the operators have left-to-right associativity.

For example, multiplication and floor division have the same precedence.
Hence, if both of them are present in an expression, left one is evaluates first.

>>> 10 * 7 // 3
23
>>> 10 * (7//3)
20
>>> (10 * 7)//3
23
We can see that 10 * 7 // 3is equivalent to (10 * 7)//3.

Exponent operator ** has right-to-left associativity in Python.

>>> 5 ** 2 ** 3
390625
>>> (5** 2) **3
15625
>>> 5 **(2 **3)
390625
We can see that 2 ** 3 ** 2 is equivalent to 2 ** (3 **2).
2.7.1 Non AssociativeOperators

Some operators like assignment operators and comparison operators do not have
associativity in Python. There are separate rules for sequences of this kind of operator and
cannot be expressed as associativity.

For example, x < y < z neither means (x < y) < z nor x < (y < z). x < y < z is equivalent to x
< y and y < z, and is evaluates from left-to-right.

Furthermore, while chaining of assignments like x = y = z is perfectly valid, x = y += zwill


result into error.

2.8 TUPLE ASSIGNMENT:


It is often useful to swap the values of two variables. With conventional
assignments, you have to use a temporary variable. For example, to swap a and b:
>>>temp = a
>>> a = b
>>> b = temp
This solution is cumbersome; tuple assignment is more elegant:
>>>a, b =b, a
Theleftsideisatupleofvariables;therightsideisatupleofexpressions.
Eachvalueisassignedtoitsrespectivevariable.Alltheexpressionsontherightsideare
evaluated before any of the assignments. The number of variables on the left and the number
of values on the right have to be the
same:
>>>a, b = 1, 2, 3
ValueError: too many values to unpack
More generally, the right side can be any kind of sequence (string, list or
tuple). For example, to split an email address into a user name and a domain, you couldwrite:
>>>addr = '[email protected]'
>>>uname, domain = addr.split('@')
2.9 COMMENTS:
As programs get bigger and more complicated, they get more difficult to read.
Formal languages are dense, and it is often difficult to look at a piece of code and figure out
what it is doing, or why. For this reason, it is a good idea to add notes to your programs to
explain in natural language what the program is doing. These notes are called comments, and
they start with the # symbol:
# computeArea of a triangle using Base and Height
area= (base*height)/2
In this case, the comment appears on a line by itself. You can also put
comments at the endof a line:
area= (base*height)/2 # Area of a triangle using BaseandHeight
Everythingfromthe#totheendofthelineisignored—ithasnoeffectonthe
execution ofthe program.Comments are most useful when they document non-obvious
features of the code. It isreasonable to assume that the reader can figure out what the code
does; it is more useful toexplain why.
This comment is redundant with the code and useless:
base= 5 # assign 5tobase
This comment contains useful information that is not in thecode:
base = 5 # base is incentimetre.
Good variable names can reduce the need for comments, but long names can
make complexexpressions hard to read, so there is a tradeoff.

If we have comments that extend multiple lines, one way of doing it is to use
hash (#) in the beginning of each line. For example:

#This is a long comment


#and it extends
#to multiple lines

Another way of doing this is to use triple quotes, either ''' or """.

These triple quotes are generally used for multi-line strings. But they can be used as multi-
line comment as well. Unless they are not docstrings, they do not generate any extra code.

"""This is also a
perfect example of
multi-line comments"""

3.1 CONDITIONALS
Flow of execution of instruction can be controlled using conditional statements.
Conditional statements have some Boolean expression. Boolean expression can have relational
operators or logical operators or both.

3.1.1 BooleanExpressions
A boolean expression is an expression it‘s result is either true or false. The
following examples use the operator ==, which compares two operands and produces True if
they are equal and False otherwise:

>>> 9 == 9
True
>>> 9 == 6
False
True and False are special values that belong to the type bool; they are not strings:

>>>type(True)
<class 'bool'>
>>>type(False)
<class 'bool'>
Boolean expression can have relational operators or logical operators.The ==
operator is one of the relational operators; the others are:

x==y #x is equal toy


x!=y # x is not equal toy
x>y # x is greater thany
x<y # x is less thany
x>=y # x is greater than or equal to y
x<=y # x is less than or equal toy
More explanation can found in 2.5.2.Although these operations are probably
familiar to you, the Python symbols are different from the mathematical symbols. A common
error is to use a single equal sign (=) instead of a double equal sign (==). Remember that = is
an assignment operator and == is a relational operator. There is no such thing as =< or =>.

3.1.2 Logicaloperators
There are three logical operators: and, or, and not. The semantics (meaning) of
these operators is similar to their meaning in English. This was explained in 2.5.3

For example:
x> 0 and x < 10 is true only if x is greater than 0 and less than 10.

n%2 == 0 or n%3 == 0 is true if either or both of the conditions is true, that is, if the
number is divisible by 2 or 3.

not operator negates a boolean expression, so not (x > y) is true if x > y is false, that
is, if x is less than or equal toy.

Note:- Any nonzero number is interpreted as True

>>>95 and True


True
>>>mark=95
>>>mark>0 and mark<=100
True
>>>mark=102
>>>mark>0 and mark<=100
False
3.2 SELECTION:

In Unit I, you were introduced to the concept of flow of control: the sequence
of statements that the computer executes. In procedurally written code, the computer usually
executes instructions in the order that they appear. However, this is not always the case. One
of the ways in which programmers can change the flow of control is the use of selection control
statements.

Now we will learn about selection statements, which allow a program to choose
when to execute certain instructions. For example, a program might choose how to proceed on
the basis of the user‘s input. As you will be able to see, such statements make a program more
versatile.

In python selection can be achieved through

 ifstatement
 The elifStatement
 if...elif...else
 Nested ifstatements

3.2.1 Conditional Execution- (if ):


In order to write useful programs, we almost always need the ability to check
conditions and change the behaviour of the program accordingly. Selection or Conditional
statements give us this ability. The simplest form is the if statement:

General Syntax of if statement is


if TESTEXPRESSION:
STATEMENT(S) # executed if condition evaluates to True

Here, the program evaluates the TEST EXPRESSION and will execute
statement(s) only if the text expression is True.If the text expression is False, the statement(s)
is not executed.

A few important things to note about if statements:

1. The colon (:) is significant and required. It separates the header of the compound
statement from thebody.
2. Theline afterthecolonmustbeindented.ItisstandardinPython tousefourspacesfor
indenting.
3. All lines indented the same amount after the colon will be executed whenever the
BOOLEAN_EXPRESSION istrue.
4. Python interprets non-zero values as True. None and 0 are interpreted asFalse.

Figure 3.1 if Statement Flowchart

Here is an example:

mark = 102
if mark >= 100:
print(mark, " is a Not a valid mark.")
print("This is always printed.")

Output will be:

102 is a Not a valid mark.


This is always printed.
The boolean expression after the if statement (here mark>=100)is called
the condition. If it is true, then all the indented statements get executed.
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!
3.2.2 Alternative execution-(if –else):
Asecond form of the if statement is ―alternative execution‖, in which there are
two possibilities and the condition determines which one runs. In other words ,It is frequently
the case that you want one thing to happen when a condition it true, and something else to
happen when it is false. For that we have if else statement. The syntax looks like this:
General Syntax of if ..elsestatement is

if TEST EXPRESSION:
STATEMENTS_1 # executed if condition evaluates to True
else:
STATEMENTS_2 # executed if condition evaluates to False

Each statement inside the if block of an if else statement is executed in order if


the test expression evaluates to True. The entire block of statements is skipped if the test
expression evaluates to False, and instead all the statements under the else clause are executed.

Figure 3.2if..else Flowchart


There is no limit on the number of statements that can appear under the two
clauses of an if else statement, but there has to be at least one statement in each block.
Occasionally, it is useful to have a section with no statements, for code you haven‘t written yet.
In that case, you can use the passstatement, which does nothing except act as a placeholder.

ifTrue: # This is alwaystrue


pass # so this is always executed, but it doesnothing
else:
pass
Here is an example:
age=21 #age=17
if age >= 18:
print("Eligible to vote")
else:
print("Not Eligible to vote")

Output will be:

Eligible tovote

In the above example, when age is greater than 18, the test expression is true
and body of if is executed and body of else is skipped.If age is less than 18, the test expression
is false and body of else is executed and body of if is skipped.If age is equal to 18, the test
expression is true and body of if is executed and body of else isskipped.

3.2.3 Chained Conditionals-(if-elif-else):


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 syntax
looks like this:
General Syntax of if..elif...else statement is

if TEST EXPRESSION1:
STATEMENTS_A
elif TESTEXPRESSION2:
STATEMENTS_B
else:
STATEMENTS_C

The elif is short for else if. It allows us to check for multiple expressions.If the
condition for if is False, it checks the condition of the next elif block and so on.If all the
conditions are False, body of else is executed.Only one block among the several
if...elif...else blocks is executed according to the condition.The if block can have only one else
block. But it can have multiple elif blocks.
Figure 3.3 Flowchart of if...elif...else

Each condition is checked in order. If the first is false, the next is checked, and
soon.Ifoneofthemistrue,thecorrespondingbranchexecutes,andthestatementends.Evenif more
than one condition is true, onlythe first true branch executes.

Here is an example:
time=17 #time=10, time=13, time=17, time=22
if time<12:
print("Good Morning")
eliftime<15:
print("Good Afternoon")
eliftime<20:
print("Good Evening")
else:
print("Good Night")

Output will be:


Good Evening

When variable time is less than 12, Good Morning is printed.If time is less than
15, Good Afternoon is printed.If time is less than 20, Good Evening is printed. If all above
conditions fails Good Night isprinted.

3.2.4 Nested Conditionals:

One conditional can also be nested within another. ie, We can have a
if...elif...else statement inside another if...elif...else statement. This is called nesting in
computerprogramming.
Any number of these statements can be nested inside one another. Indentation
is the only way to figure out the level of nesting.

General Syntax of Nested if..else statement is

if TEST EXPRESSION1:
if TEST EXPRESSION2:
STATEMENTS_B
else:
STATEMENTS_C
else:
if TEST EXPRESSION3:
STATEMENTS_D
else:
STATEMENTS_E

Figure 3.4Flowchart of Nested if..else

The outer conditional contains two branches. Those two branches contain
another if… else statement, which has two branches of its own. Those two branches could
contain conditional statements as well.

Here is an example:
a=10
b=20
c=5
if a>b:
if a>c:
print("Greatest number is ",a)
else:
print("Greatest number is ",c)
else:
if b>c:
print("Greatest number is ",b)
else:
print("Greatest number is ",c)
Output will be :
Greatest number is 20
Although the indentation of the statements makes the structure apparent, nested
conditionals very quickly become difficult to read. In general, it is a good idea to avoid them
when you can.
Logical operators often provide a way to simplify nested conditional
statements.Forexample,wecanrewritetheabovecodeusingsingleif…elif….elsestatement:
a=10
b=20
c=5
if a>b and a>c:
print("Greatest number is ",a)
elif b>a and b>c:
print("Greatest number is ",b)
else:
print("Greatest number is ",c)
Anotherexample,wecanrewritethefollowingcodeusingasingleconditional:
if 0 < x:
if x < 10:
print('x is a positive single-digit number. ')
The print statement runs only if we make it pass both conditionals, so we can
get the same effect with the and operator:
if 0 < x and x < 10:
print('x is a positive single-digit number. ')
For this kind of condition, Python provides a more concise option:
if 0 < x < 10:
print('x is a positive single-digit number. ')
3.3 ITERATION:
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.
Repeated execution of a set of statements is called iteration. Python has two
statements for iteration
 forstatement
 whilestatement
Before we look at those, we need to review a few ideas.
Reassignmnent

As we saw back in the variable section, 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).
age = 26
print(age)
age = 17
print(age)
The output of this program is
26
17
because the first time age is printed, its value is 26, and the second time, its
value is 17.
Here is what reassignment looks like in a state snapshot:

26

age 17

Figure 3.5 State Diagram for Reassignment


With reassignment it is especially important to distinguish between an assignment
statement and a boolean expression that tests for equality. Because Python uses the equal token
(=) for assignment, it is tempting to interpret a statement like a = b as a boolean test. Unlike
mathematics, Remember that the Python token for the equality operator is ==.
Note too that an equality test is symmetric, but assignment is not. For example,
if a == 7 then 7 == a. But in Python, the statement a = 7 is legal and 7 = a is not.
Furthermore, in mathematics, a statement of equality is always true. If
a == b now, then a will always equal b. In Python, an assignment statement can make two
variablesequal,butbecauseofthepossibilityofreassignment,theydon‘thavetostaythatway:
a=5
b=a # after executing this line, a and b are now equal
a=3 # after executing this line, a and b are no longer equal
The third line changes the value of a but does not change the value of b, sothey
are no longerequal.

Updating variables

When an assignment statement is executed, the right-hand-side expression (i.e.


the expression that comes after the assignment token) is evaluated first. Then the result of that
evaluation is written into the variable on the left hand side, thereby changing it.
One of the most common forms of reassignment is an update, where the new
value of the variable depends on its old value.
n=5
n=3*n+1
Thesecondlinemeans―getthecurrentvalueofn,multiplyitbythreeandadd one, and
put the answer back into n as its new value‖. So after executing the two lines above, n will have
the value16.
If you try to get the value of a variable that doesn‘t exist yet, you‘ll get an error:
>>> x = x + 1
Traceback (most recent call last):
File "<interactive input>", line 1, in
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
This second statement — updating a variable by adding 1 to it. It is very
common. It is called an increment of the variable; subtracting 1 is called a decrement.
3.3.1 The WHILE statement:

The while loop in Python is used to iterate over a block of code as long as the
test expression (condition) is true.We generally use this loop when we don't know beforehand,
the number of times toiterate.

The general syntax for the while statement :


while TEST_EXPRESSION:
STATEMENTS

In while loop, test expression is checked first. The body of the loop is entered
only if the TEST_EXPRESSION evaluates to True. After one iteration, the test expression is
checked again. This process continues until the TEST_EXPRESSION evaluates to False.

In Python, the body of the while loop is determined through indentation.Body


starts with indentation and the first unindented line marks the end.

Python interprets any non-zero value as True. None and 0 are interpreted
as False.
Flowchart of while Loop

Figure 3.6 Flowchart of while Loop

Example:
Python program to find sum of first n numbers using while loop
n = 20
sum = 0 # initialize sum and counter
i=1
while i <= n:
sum = sum + i
i = i+1 # update counter
print("The sum is", sum) # print the sum
When you run the program, the output will be:
The sum is210

In the above program, the test expression will be True as long as our counter
variable i is less than or equal to n (20 in our program).

We need to increase the value of counter variable in the body of the loop. This
is very important (and mostly forgotten). Failing to do so will result in an infinite loop (never
ending loop).Finally the result isdisplayed.

3.3.2 The FOR statement:


The for loop in Python is used to iterate over a sequence (list, tuple, string) or
other iterable objects. Iterating over a sequence is called traversal.
The general syntax for the while statement:
for LOOP_VARIABLE in SEQUENCE:
STATEMENTS

Here, LOOP_VARIABLE is the variable that takes the value of the item
inside the sequence on eachiteration.

Loop continues until we reach the last item in the sequence. The body of for
loop is separated from the rest of the code using indentation.

Figure 3.7Flowchart of for Loop

Example
marks = [95,98,89,93,86]
total = 0
forsubject_mark in marks:
total = total+subject_mark
print("Total Mark is ", total)
when you run the program, the output will be:
Total Markis461

Wecanusetherange()functioninforloopstoiteratethroughasequenceof
numbers.
Example:
sum=0
for i in range(20):
sum=sum+i
print("Sum is ", sum)

Output will be:

Sum is190

3.3.3 BREAK, CONTINUE,PASS:


You might face a situation in which you need to exit a loop completely when an
external condition is triggered or there may also be a situation when you want to skip a part of
the loop and start nextexecution.

Python provides break and continue statements to handle such situations and
to have good control on your loop.This section will discuss the break, continue
and pass statements available inPython.
3.3.3.1 The BREAK Statement:
The break statement in Python terminates the current loop and resumes
execution at the next statement. The most common use for break is when some external
condition is triggered requiring a hasty exit from a loop. The break statement can be used in
both while and for loops.

Example:
for letter in 'Welcome': # First Example
if letter == 'c':
break
print('Current Letter :', letter)
var = 10 # Second Example
whilevar> 0:
print('Current variable value :', var)
var = var -1
ifvar == 5:
break
print "End!"

This will produce the following output:


Current Letter : W
Current Letter : e
Current Letter : l
Current variable value : 10
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
End!

3.3.3.2 The CONTINUE Statement:


The continue statement in Python returns the control to the beginning of the
while loop. The continue statement rejects all the remaining statements in the current iteration
of the loop and moves the control back to the top of the loop.The continue statement can be
used in both while and forloops.
Example:

for letter in 'Welcome': # First Example


if letter == 'c':
continue
print('Current Letter :', letter)
var = 10 # Second Example
whilevar> 0:
print('Current variable value :', var)
var = var -1
ifvar == 5:
continue
print "End!"

This will produce the following output:


Current Letter : W
Current Letter : e
Current Letter : l
Current Letter : o
Current Letter : m
Current Letter : e
Current variable value : 10
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
Current variable value : 5
Current variable value : 4
Current variable value : 3
Current variable value : 2
Current variable value : 1
End!
3.3.3.3 The else Statement Used withLoops
Python supports to have an else statement associated with a loop statements.
 If the else statement is used with a for loop, the else statement is executed when the
loop has exhausted iterating thelist.
 If the else statement is used with a while loop, the else statement is executed when the
condition becomesfalse.

while loop with else


We can have an optional else block with while loop as well.The else part is executed if the
condition in the while loop evaluates to False. The while loop can be terminated with a
breakstatement.In such case, the else part is ignored. Hence, a while loop's else part runs if no
break occurs and the condition isfalse.

Here is an example to illustrate this.

counter = 0
while counter < 3:
print("Inside loop")
counter = counter + 1
else:
print("Inside else")

Output

Inside loop
Inside loop
Inside loop
Inside else
Here, we use a counter variable to print the string Inside loop three times.On
the forth iteration, the condition in while becomes False. Hence, the else part is executed.

for loop with else

A for loop can have an optional else block as well. The else part is executed if the items in the
sequence used in for loop exhausts.break statement can be used to stop a for loop. In such case,
the else part is ignored.Hence, a for loop's else part runs if no breakoccurs.

Here is an example to illustrate this.

digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")

When you run the program, the output will be:

0
1
5
No items left.

Here, the for loop prints items of the list until the loop exhausts. When the for
loop exhausts, it executes the block of code in the else and prints

3.3.3.4 The PASS Statement:

In Python programming, pass is a null statement. The difference between a


comment and pass statement in Python is that, while the interpreter ignores a comment
entirely, pass is not ignored.However, nothing happens when pass is executed. It results into
no operation(NOP).

Syntax of pass:
Pass
We generally use it as aplaceholder.

Suppose we have a loop or a function that is not implemented yet,


but we want to implement it in the future. They cannot have an empty body. The
interpreter would complain. So, we use the pass statement to construct a body that
does nothing.

Example
sequence = {'p', 'a', 's', 's'}
forval in sequence:
pass
We can do the same thing in an empty function

def function(args):
pass

You might also like