Python Programming UNIT 1
Python Programming UNIT 1
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:
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.
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.
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
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.
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!.
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.
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–
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 −
>>>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.
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.
Function Description
float(x) Converts x to a floating-point number.
2.3.2 AssignmentStatements
Programmers generally choose names for their variables that are meaningful
The Rules
The interpreter uses keywords to recognize the structure of the program, and
they cannot be used as variable names.
Python 3 has these keywords:
except in raise
>>>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.
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
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.
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.
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.
In Table 2.6: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)
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.
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
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).
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.
>>> 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.
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
We can see in the above table that more than one operator exists in the same
group. These operators have the same precedence.
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.
>>> 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.
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:
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:
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.
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.
ifstatement
The elifStatement
if...elif...else
Nested ifstatements
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.
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.
Here is an example:
mark = 102
if mark >= 100:
print(mark, " is a Not a valid mark.")
print("This is always printed.")
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
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.
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")
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.
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.
if TEST EXPRESSION1:
if TEST EXPRESSION2:
STATEMENTS_B
else:
STATEMENTS_C
else:
if TEST EXPRESSION3:
STATEMENTS_D
else:
STATEMENTS_E
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
Updating variables
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.
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.
Python interprets any non-zero value as True. None and 0 are interpreted
as False.
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.
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.
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)
Sum is190
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!"
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.
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.
digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")
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
Syntax of pass:
Pass
We generally use it as aplaceholder.
Example
sequence = {'p', 'a', 's', 's'}
forval in sequence:
pass
We can do the same thing in an empty function
def function(args):
pass