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

CSC 202 Note

Python is a high-level, object-oriented programming language created by Guido Van Rossum and released in 1991, known for its simplicity and readability. It is widely used in various applications including web development, data science, and automation, with notable organizations like Google and NASA utilizing it. While Python offers many advantages such as extensive libraries and ease of learning, it also has disadvantages including performance issues and memory consumption.

Uploaded by

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

CSC 202 Note

Python is a high-level, object-oriented programming language created by Guido Van Rossum and released in 1991, known for its simplicity and readability. It is widely used in various applications including web development, data science, and automation, with notable organizations like Google and NASA utilizing it. While Python offers many advantages such as extensive libraries and ease of learning, it also has disadvantages including performance issues and memory consumption.

Uploaded by

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

Introduction to Python

Python is a high-level and object-oriented programming language developed by Guido


Van Rossum, when he was working at CWI (Centrum Wiskunde & Informatica) which is
a National Research Institute for Mathematics and Computer Science in Netherlands. The
language was released in 1991. Python got its name from a BBC comedy series from
seventies- "Monty Python’s Flying Circus".

Python is an easy to learn, powerful high-level programming language. It has a simple but
effective approach to object-oriented programming. Python’s graceful semantics and syntax
together with its interpreted nature make it an ideal language for scripting and rapid
application development in many fields.

Some of the salient features of Python are:


 It is a general purpose programming language which can be used for both scientific
and non-scientific programming.
 It is excellent for beginners as the language is interpreted, hence gives immediate
results.
 It implements the concept of exception handling and dynamic binding better than the
other languages of its time.
 The programs written in Python are easily readable and understandable.
 It is a platform independent programming language.
 It is suitable as an extension language for customizable applications.
 It is easy to learn and use.

Major Applications (in Companies):


 In operations of Google search engine, Youtube etc.
 Bit Torrent peer to peer file sharing is written using Python.
 Intel, Cisco, HP, IBM, etc use Python for hardware testing.
 Maya provides a Python scripting API.
 i–Robot uses Python to develop commercial Robot.
 NASA and others use Python for their scientific programming task.

Advantages:

1. Presence of third-party modules


2. Extensive support libraries(NumPy for numerical calculations, Pandas for data
analytics, etc.)
3. Open source and large active community base
4. Versatile, Easy to read, learn and write
5. User-friendly data structures
6. High-level language

1
7. Dynamically typed language(No need to mention data type based on the value
assigned, it takes data type)
8. Object-Oriented and Procedural Programming language
9. Portable and Interactive
10. Ideal for prototypes – provide more functionality with less coding
11. Highly Efficient(Python’s clean object-oriented design provides enhanced process
control, and the language is equipped with excellent text processing and integration
capabilities, as well as its own unit testing framework, which makes it more efficient.)
12. Internet of Things(IoT) Opportunities
13. Interpreted Language
14. Portable across Operating systems

Disadvantages:

1. Performance: Python is an interpreted language, which means that it can be slower


than compiled languages like C or Java. This can be an issue for performance-intensive
tasks.
2. Global Interpreter Lock: The Global Interpreter Lock (GIL) is a mechanism in
Python that prevents multiple threads from executing Python code at once. This can
limit the parallelism and concurrency of some applications.
3. Memory consumption: Python can consume a lot of memory, especially when
working with large datasets or running complex algorithms.
4. Dynamically typed: Python is a dynamically typed language, which means that the
types of variables can change at runtime. This can make it more difficult to catch errors
and can lead to bugs.
5. Packaging and versioning: Python has a large number of packages and libraries,
which can sometimes lead to versioning issues and package conflicts.
6. Lack of strictness: Python’s flexibility can sometimes be a double-edged sword.
While it can be great for rapid development and prototyping, it can also lead to code
that is difficult to read and maintain.
7. Steep learning curve: While Python is generally considered to be a relatively easy
language to learn, it can still have a steep learning curve for beginners, especially if
they have no prior experience with programming.

Applications:

1. GUI-based desktop applications


2. Graphic design, image processing applications, Games, and Scientific/
computational Applications
3. Web frameworks and applications
4. Enterprise and Business applications
5. Operating Systems
6. Education
7. Database Access
8. Language Development
9. Prototyping
10. Software Development

2
11. Data Science and Machine Learning
12. Scripting

Organizations using Python

1. Google(Components of Google spider and Search Engine)


2. Yahoo(Maps)
3. YouTube
4. Mozilla
5. Dropbox
6. Microsoft
7. Cisco
8. Spotify
9. Quora
10. Facebook

Python 3 is a popular high-level programming language used for a wide variety of


applications. Here are some basics of Python 3 that you should know:
1. Variables: In Python 3, variables are created by assigning a value to a name. For
example, x = 5 creates a variable called x and assigns the value 5 to it.
2. Data types: Python 3 supports several built-in data types, including integers, floats,
strings, booleans, lists, tuples, and dictionaries.
3. Operators: Python 3 supports a variety of operators, including arithmetic operators
(+, -, *, /), comparison operators (>, <, ==, !=), and logical operators (and, or, not).
4. Control flow statements: Python 3 supports several control flow statements,
including if-else statements, for loops, and while loops. These statements allow you to
control the flow of execution in your code.
5. Functions: In Python 3, functions are created using the def keyword. For example,
def my_function(x): creates a function called my_function that takes one argument
called x

3
Keywords in Python are reserved words that can not be used as a variable name, function
name, or any other identifier.
List of Keywords in Python

Keyword Description Keyword Description Keyword Description

Represents an
It is a Logical expression that It is a non-
and False nonlocal
Operator will result in local variable
not being true.

It is used to
It is used with It is a Logical
as create an alias finally not
exceptions Operator
name

It is used for It is used to It is a Logical


assert for or
debugging create Loop Operator

pass is used
To import when the user
Break out a
break from specific parts pass doesn’t
Loop
of a module want any code
to execute

raise is used
It is used to
It is used to to raise
class global declare a raise
define a class exceptions or
global variable
errors.

Skip the next To create a return is used


continue iteration of a if Conditional return to end the
loop Statement execution

Represents an
It is used to It is used to
expression
def define the import import a True
that will result
Function module
in true.

It is used to
It is used to
test if two Try is used to
del delete an is try
variables are handle errors
object
equal

elif Conditional in To check if a while While Loop is

4
Keyword Description Keyword Description Keyword Description

used to
statements, value is present
execute a
same as else- in a Tuple,
block of
if List, etc.
statements

It is used in a Used to create with


conditional an anonymous statement is
else statement lambda function with used in
exception
handling

try-except is yield keyword


used to handle is used to
It represents a
except these errors None yield create a
null value
generator
function

Executing first program on Python

1) Let’s start with typing print “Hello Python!” after the prompt.

>>>print("Hello Python!")

Output: Hello Python!

We can also write as:

>>> x=1

>>> y=5

>>> z = x+y

>>> print (z)

Output: 6

Statement, Indentation and Comment in Python

What is Statement in Python

5
A Python statement is an instruction that the Python interpreter can execute. There are
different types of statements in Python language as Assignment statements, Conditional
statements, Looping statements, etc. The token character NEWLINE is used to end a
statement in Python. It signifies that each line of a Python script contains a statement.
These all help the user to get the required output.

Types of statements in Python?

The different types of Python statements are listed below:


 Multi-Line Statements
 Python Conditional and Loop Statements
 Python If-else
 Python for loop
 Python while loop
 Python try-except
 Python with statement
 Python Expression statements
 Python pass statement
 Python del statement
 Python return statement
 Python import statement
 Python continue and
 Python break statement
Example
Statement in Python can be extended to one or more lines using parentheses (), braces {},
square brackets [], semi-colon (;), and continuation character slash (\). When the
programmer needs to do long calculations and cannot fit his statements into one line, one
can make use of these characters.
Declared using Continuation Character (\):
s=1+2+3+\
4+5+6+\
7+8+9

Declared using parentheses () :


n = (1 * 2 * 3 + 7 + 8 + 9)

6
Declared using square brackets [] :
footballer = ['MESSI',
'NEYMAR',
'SUAREZ']

Declared using braces {} :


x = {1 + 2 + 3 + 4 + 5 + 6 +
7 + 8 + 9}

Declared using semicolons(;) :


flag = 2; ropes = 3; pole = 4

What is Indentation in Python

Whitespace is used for indentation in Python. Unlike many other programming languages
which only serve to make the code easier to read, Python indentation is mandatory. One
can understand it better by looking at an example of indentation in Python.
Role of Indentation in Python
A block is a combination of all these statements. Block can be regarded as the grouping of
statements for a specific purpose. Most programming languages like C, C++, and Java use
braces { } to define a block of code for indentation. One of the distinctive roles of Python is
its use of indentation to highlight the blocks of code. All statements with the same distance
to the right belong to the same block of code. If a block has to be more deeply nested, it is
simply indented further to the right.
Example 1:
The lines print(‘Logging on to geeksforgeeks…’) and print(‘retype the URL.’) are two
separate code blocks. The two blocks of code in our example if-statement are both indented
four spaces. The final print(‘All set!’) is not indented, so it does not belong to the else-
block.

 Python3

# Python indentation

site = 'gfg'

7
if site == 'gfg':

print('Logging on to geeksforgeeks...')

else:

print('retype the URL.')

print('All set !')

Output
Logging on to geeksforgeeks...
All set !
Example 2:
To indicate a block of code in Python, you must indent each line of the block by the same
whitespace. The two lines of code in the while loop are both indented four spaces. It is
required for indicating what block of code a statement belongs to. For example, j=1 and
while(j<=5): is not indented, and so it is not within the while block. So, Python code
structures by indentation.

 Python3

j=1

while(j <= 5):

print(j)

j=j+1

Output

1
2
3

8
4
5
What are Comments in Python
Python comments start with the hash symbol # and continue to the end of the
line. Comments in Python are useful information that the developers provide to make the
reader understand the source code. It explains the logic or a part of it used in the code.
Comments in Python are usually helpful to someone maintaining or enhancing your code
when you are no longer around to answer questions about it. These are often cited as useful
programming convention that does not take part in the output of the program but improves
the readability of the whole program.
Comments in Python are identified with a hash symbol, #, and extend to the end of the line.
Types of comments in Python
A comment can be written on a single line, next to the corresponding line of code, or in a
block of multiple lines. Here, we will try to understand examples of comment in Python one
by one:
Single-line comment in Python
Python single-line comment starts with a hash symbol (#) with no white spaces and lasts till
the end of the line. If the comment exceeds one line then put a hashtag on the next line and
continue the comment. Python’s single-line comments are proved useful for supplying short
explanations for variables, function declarations, and expressions. See the following code
snippet demonstrating single line comment:
Example 1:
Python allows comments at the start of lines, and Python will ignore the whole line.

 Python3

# This is a comment

# Print “GeeksforGeeks” to console

print("GeeksforGeeks")

Output
GeeksforGeeks
Example 2:
Python also allows comments at the end of lines, ignoring the previous text.

 Python3

a, b = 1, 3 # Declaring two integers

9
sum = a + b # adding two integers

print(sum) # displaying the output

Output
4
Multiline comment in Python
Use a hash (#) for each extra line to create a multiline comment. In fact, Python multiline
comments are not supported by Python’s syntax. Additionally, we can use Python multi-
line comments by using multiline strings. It is a piece of text enclosed in a delimiter (“””)
on each end of the comment. Again there should be no white space between delimiter (“””).
They are useful when the comment text does not fit into one line; therefore need to span
across lines. Python Multi-line comments or paragraphs serve as documentation for others
reading your code. See the following code snippet demonstrating a multi-line comment:

Variables and Data Types in Python

A Python variable is a reserved memory location to store values. In other words, a variable in
a python program gives data to the computer for processing.

When we create a program, we often like to store values so that it can be used later. We use
objects to capture data, which then can be manipulated by computer to provide information.
By now we know that object/ variable is a name which refers to a value.

Every object has:

A. An Identity - can be known using id (object)


B. A type – can be checked using type (object) and
C. A value

Let us study all these in detail...

A) Identity of the object: It is the object's address in memory and does not change once it
has been created.

B) Type (i.e. Data Type): It is a set of values, and the allowable operations on those values.
It can be one of the following:

1. Number

10
Number data type stores Numerical Values. This data type is immutable i.e. value of its
object cannot be changed (we will talk about this aspect later). These are of three different
types:

i. Integer & Long


ii. Float/floating point
iii. Complex

i) Integers:
Integers are the whole numbers consisting of + or – sign with decimal digits like 100000, -99,
0, 17.

When we want a value to be treated as very long integer value appends L to the value. Such
values are treated as long integers by python.

>>> a = 10
>>> b = 5192L #example of supplying a very long value to a variable
>>> c= 4298114
>>> type(c) # type ( ) is used to check data type of value

ii) Floating Point: Numbers with fractions or decimal point are called floating point
numbers.

A floating point number will consist of sign (+,-) sequence of decimals digits and a dot such
as 0.0, -21.9, 0.98333328, 15.2963.

Example: y= 12.36

iii) Complex: Complex number in python is made up of two floating point values, one each
for real and imaginary part. For accessing different parts of variable (object) x; we will
use x.real and x.image. Imaginary part of the number is represented by j instead of i,
so 1+0j denotes zero imaginary part.

Example:

>>> x = 1+0j
>>> print (x.real,x.imag)
1.0 0.0

11
2. None

This is special data type with single value. It is used to signify the absence of value/false in a
situation. It is represented by None.

3. Sequence

A sequence is an ordered collection of items, indexed by positive integers. It is combination


of mutable and non-mutable data types. Three types of sequence data type available in
Python are Strings, Lists & Tuples.

3.1) String: is an ordered sequence of letters/characters. They are enclosed in single quotes ('
') or double (" "). The quotes are not part of string. They only tell the computer where the
string constant begins and ends.

If we are not sure, what is the data type of a value, Python interpreter can tell us:

>>>type ('Good Morning')


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

3.2) Lists: List is also a sequence of values of any type. Values in the list are called
elements / items. These are mutable and indexed/ordered. List is enclosed in square brackets.

Example: >>>l = ['spam', 20.5,5]

3.3) Tuples:

Tuples are a sequence of values of any type, and are indexed by integers. They are
immutable. Tuples are enclosed in (). We have already seen a tuple, in Example 2 (4, 2).

4. Sets

Set is an unordered collection of values, of any type, with no duplicate entry. Sets are
immutable.

Example:

>>>s = set ([1,2,3,4])


>>>print(s)

{1, 2, 3, 4 }

5. Mapping

12
This data type is unordered and mutable. Dictionaries fall under Mappings.

5.1) Dictionaries: Can store any number of python objects. What they store is a key – value
pairs, which are accessed using key. Dictionary is enclosed in curly brackets.

Example: d = {1:'a',2:'b',3:'c'}

Input and Output Operations with Examples in Python

A Program needs to interact with the user to accomplish the desired task; this is done
using Input-Outputfacility. Input means the data entered by the user of the program. In
python, we have input() and raw_input ( ) function available for Input.

1) input()

Syntax:

input (expression)

If prompt is present, it is displayed on monitor, after which the user can provide data from
keyboard. Input takes whatever is typed from the keyboard and evaluates it. As the input
provided is evaluated, it expects valid python expression. If the input provided is not correct
then either syntax error or exception is raised by python.

Example:

>>>x= input ("Enter data:")


Enter data: 34.78
>>>print(x)

34.78

2) raw_input()

Syntax:

raw_input (expression)

This input method fairly works in older versions (like 2.x).

If prompt is present, it is displayed on the monitor after which user can provide the data from
keyboard. The function takes exactly what is typed from keyboard, convert it to string and
then return it to the variable on LHS of '='.

Example: In interactive mode

>>>x=raw_input ('Enter your name: ')

13
Enter your name: ABC

x is a variable which will get the string (ABC), typed by user during the execution of
program. Typing of data for the raw_input function is terminated by enter key.

We can use raw_input() to enter numeric data also. In that case we typecast, i.e., change the
data type using function, the string data accepted from user to appropriate Numeric type.

Example:

>>>y=int(raw_input("Enter your roll no."))

Enter your roll no. 5

It will convert the accepted string i.e., 5 to integer before assigning it to 'y'.

# Python3 program to get input from user

# accepting integer from the user

# the return type of input() function is string ,

# so we need to convert the input to integer

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

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

num3 = num1 * num2

print("Product is: ", num3)

Output:
Enter num1: 8 Enter num2: 6 ('Product is: ', 48)

14
Comments:
# is used for single line comment in Python
""" this is a comment """ is used for multi line comments

Input and Output


In this section, we will learn how to take input from the user and hence manipulate it or simply
display it. input() function is used to take input from the user.

# Python program to illustrate

# getting input from user

name = input("Enter your name: ")

# user entered the name 'Joy Omoha'

print("My name is", name)

Output:
My name is Joy Omoha

15
Print statement

Syntax:

print (expression/constant/variable)

Print evaluates the expression before printing it on the monitor. Print statement outputs an
entire (complete) line and then goes to next line for subsequent output (s). To print more than
one item on a single line, comma (,) may be used.

Example:

>>> print ("Hello")

Hello

>>> print (5.5)

5.5

>>> print (4+6)

10

Types of Control Flow in Python

In Python programming language , the type of control flow statements is as follows:


1. The if statement
2. The if-else statement
3. The nested-if statement
4. The if-elif-else ladder
Python if statement
The if statement is the most simple decision-making statement. It is used to decide whether a
certain statement or block of statements will be executed or not.
Syntax:
if condition:

16
# Statements to execute if
# condition is true
Here, the condition after evaluation will be either true or false. if the statement accepts
boolean values – if the value is true then it will execute the block of statements below it
otherwise not.
As we know, python uses indentation to identify a block. So the block under an if statement
will be identified as shown in the below example:
if condition:
statement1
statement2

# Here if the condition is true, if block


# will consider only statement1 to be inside
# its block.

# python program to illustrate If statement

i = 10

if (i > 15):

print("10 is less than 15")

print("I am Not in if")

Output:
I am Not in if

Python If-Else Statement


The if statement alone tells us that if a condition is true it will execute a block of statements
and if the condition is false it won’t. But if we want to do something else if the condition is
false, we can use the else statement with if statement to execute a block of code when the if
condition is false.
Syntax:

17
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false

# python program to illustrate If else statement

#!/usr/bin/python

i = 20

if (i < 15):

print("i is smaller than 15")

print("i'm in if Block")

else:

print("i is greater than 15")

print("i'm in else Block")

print("i'm not in if and not in else Block")

18
Output:
i is greater than 15
i'm in else Block
i'm not in if and not in else Block

For Loops in Python


Python For loop is used for sequential traversal i.e. it is used for iterating over an iterable
like String, Tuple, List, Set, or Dictionary.
Note: In Python, for loops only implement the collection-based iteration.

For Loops Syntax

for var in iterable:


# statements

Python For Loop with List

This code uses a for loop to iterate over a list of strings, printing each item in the list on a
new line. The loop assigns each item to the variable I and continues until all items in
the list have been processed.
Python3

# Python program to illustrate

# Iterating over a list

l = ["geeks", "for", "geeks"]

for i in l:

print(i)

19
Output :
geeks
for
geeks

Python For Loop in Python Dictionary

This code uses a for loop to iterate over a dictionary and print each key-value pair on a new
line. The loop assigns each key to the variable i and uses string formatting to print the key
and its corresponding value.
Python3

# Iterating over dictionary

print("Dictionary Iteration")

d = dict()

d['xyz'] = 123

d['abc'] = 345

for i in d:

print("% s % d" % (i, d[i]))

Output:
Dictionary Iteration
xyz 123
abc 345

20
Python For Loop in Python String

This code uses a for loop to iterate over a string and print each character on a new line. The
loop assigns each character to the variable i and continues until all characters in the string
have been processed.
Python3

# Iterating over a String

print("String Iteration")

s = "Geeks"

for i in s:

print(i)

Output:
String Iteration
G
e
e
k
s

21
Python For Loop with a step size

This code uses a for loop in conjunction with the range() function to generate a sequence of
numbers starting from 0, up to (but not including) 10, and with a step size of 2. For each
number in the sequence, the loop prints its value using the print() function. The output will
show the numbers 0, 2, 4, 6, and 8.
Python3

for i in range(0, 10, 2):

print(i)

Output :
0
2
4
6
8

Python For Loop inside a For Loop

This code uses nested for loops to iterate over two ranges of numbers (1 to 3 inclusive) and
prints the value of i and j for each combination of the two loops. The inner loop is executed
for each value of i in the outer loop. The output of this code will print the numbers from 1 to
3 three times, as each value of i is combined with each value of j.

for i in range(1, 4):

for j in range(1, 4):

print(i, j)

Output :
11
12
13

22
21
22
23
31
32
33

Conditional statements in Python

Same as of other programming languages, python also uses conditional Statements like if-
else, break, continue etc. While writing program(s), we almost always need the ability to
check the condition and then change the course of program, the simplest way to do so is
using if statement.

Code:

if x > 0:
print "x is positive"

Here, the Boolean expression written after if is known as condition, and if Condition is
True, then the statement written after, is executed. Let's see the syntax of if statement.

Syntax - 1

if condition:
STATEMENTs- BLOCK 1
[ else: #Statement with in [ ] bracket are optional.
STATEMENTs- BLOCK 2]

Let us understand the syntax, in Syntax 1 - if the condition is True (i.e. satisfied), the
statement(s) written after if (i.e. STATEMENT-BLOCK 1) is executed, and otherwise
statement written after else (i.e. STATEMENT-BLOCK 2) is executed. Remember else
clause is optional. If provided, in any situation, one of the two blocks get executed not both.

Syntax - 2

if condition-1:
STATEMENTs- BLOCK 1
[elif condition-2: #Statement with in [ ] bracket are optional.
STATEMENTs- BLOCK 2

23
else: STATEMENTs- BLOCK N]

We can say that, "if" with "else" provides an alternative execution, as there are two
possibilities and the condition determines which one gets executed. If there are more than two
possibilities then we need to chain the if statement(s). This is done using the 2nd option of if
statement. Here, we have used "elif" clause instead of "else". "elif" combines if else- if else
statements to one if "elif" …else. You may consider "elif" to be an abbreviation of else if.
There is no limit to the number of "elif" clause used.

In the chained conditions, each condition is checked in order if previous is False then next is
checked, and so on. If one of them is True then corresponding block of statement(s) are
executed and the statement ends i.e., control moves out of "if statement". If none is true,
then else block gets executed if provided. If more than one condition is true, then only the
first true option block gets executed.

It is possible to have a condition within another condition. Such conditions are known as
Nested Condition.

Example:

x=5
y=10
if x==y:
print x, "and", y, "are equal"
else:
if x<y:
print x, "is less than", y
else:
print x, "is greater than", y

Output

5 is less than 10

break Statement

break can be used to unconditionally jump out of the loop. It terminates the execution of the
loop. breakcan be used in while loop and for loop. break is mostly required, when because
of some external condition, we need to exit from a loop.

Example:

for letter in "Python":

24
if letter =='h':
break
print (letter)

Output

P
y
t

continue Statement

This statement is used to tell Python to skip the rest of the statements of the current loop
block and to move to next iteration, of the loop. continue will return back the control to the
beginning of the loop. This can also be used with both while and for statement.

Example:

for letter in "Python":


if letter == 'h':
continue
print letter

Output

P
y
t
o
n

Looping constructs in Python

Loops are used to repeatedly execute the same code in a program. Python provides two
types of looping constructs:

1. while statement
2. for statement

1) while statement

Its syntax is:

25
while condition: # condition is Boolean expression returning True or False
STATEMENTs BLOCK 1
[else: # optional part of while
STATEMENTs BLOCK 2]

We can see that while looks like if statement. The statement begins with
keyword while followed by Boolean condition followed by colon (:). What follows next is
block of statement(s).

The statement(s) in BLOCK 1 keeps on executing till condition in while remains True; once
the condition becomes False and if the else clause is written in while, then else will get
executed.

Example: A loop to print nos. from 1 to 10

i=1
while (i <=10):
print i,
i = i+1 #could be written as i+=1

Output

1 2 3 4 5 6 7 8 9 10

In the above example,The first statement initialized the variable (controlling loop) and
then while evaluates the condition, which is True sothe block of statements written next will
be executed.

Last statement in the block ensures that, with every execution of loop, loop control variable
moves near to the termination point. If this does not happen then the loop willkeep on
executing infinitely.

As soon as i becomes 11, condition in while will evaluate to False and this will terminate the
loop.

Note: As there is ',' after print i all the values will be printed in the same line.

2) for statement

Its syntax is:

For TARGET- LIST in EXPRESSION-LIST:


STATEMENT BLOCK 1
[else: # optional block
STATEMENT BLOCK 2]

26
We can see that while looks like if statement. The statement begins with
keyword while followed by Boolean condition followed by colon (:). What follows next is
block of statement(s).

The statement(s) in BLOCK 1 keeps on executing till condition in while remains True; once
the condition becomes False and if the else clause is written in while, then else will get
executed.

Example: A loop to print nos. from 1 to 10

for i in range (1, 11, 1):


print i,

Output

1 2 3 4 5 6 7 8 9 10

Let's understand the flow of execution of the statement:

The statement introduces a function range(), its syntax is: range(start, stop, [step]),
where [step] is optional

range() generates a list of values starting from start till stop-1. Step if given is added to the
value generated, to get next value in the list.

Let's move back to the for statement: i is the variable, which keeps on getting a value
generated by range() function, and the block of statement (s) are worked on for each value
of i. As the last value is assigned to i, the loop block is executed last time and control is
returned to next statement.

Now we can easily understand the result of for statement. range() generates a list from 1, 2,
3, 4, 5, ..., 10 as the step mentioned is 1, i keeps on getting a value at a time, which is then
printed on screen.

Note:Apart from range() i (loop control variable) can take values from string, list,
dictionary, etc.

Example:

for letter in "Python":


print "Current Letter:",letter
else:
print "Coming out of loop"

Output

27
Current Letter: P
Current Letter: y
Current Letter: t
Current Letter: h
Current Letter: o
Current Letter: n
Coming out of loop

By now, you must have realized that, Syntax of for statement is also same as if
statement or while statement.

Let's look at the equivalence of the two looping construct:

28
Functions in Python

A function is named sequence of statement(s) that performs a computation. It contains


line of code(s) that are executed sequentially from top to bottom by Python
interpreter. They are the most important building block for any software in Python. For
working in script mode, we need to write the Python code in functions and save it in the file
having .py extension. Functions can be categorized as belonging to:

1. Modules
2. Built-In
3. User Defined

1) Modules

A module is a file containing Python definitions (i.e. functions) and statements. Standard
library of Python is extended as module(s) to a Programmer. Definitions from the module can
be used into code of Program. To use these modules in a program, programmer needs to
import the module. Once we import a module, we can reference (use) to any of its functions
or variables in our code. There are two ways to import a module in our program, they are:

 import
 from

Import: It is simplest and most common way to use modules in our code.

Syntax:

import modulename1 [, module name 2, ---------]

Example: Input any number and to find square and square root.

import math
x = int(input("Enter any number:"))
y = math.sqrt(x)
a = math.pow(x,2)
print("Square Root value=",y)
print("Square value=",a)

Output

Enter any number:25


Square Root value= 5.0
Square value= 625.0

Ex. 2 num = int(input('Enter a number: '))

29
sum = 0

i=0

while i <= num:

if i % 2 == 0:

print(i)

sum+=i

i+=1

print(f"Sum of all the even numbers is {sum}")

EX. 3 prime_sum = 0

for num in range(1, 11):

if num > 1:

for i in range(2, num):

if (num % i) == 0:

break

else:

prime_sum += num

print(num)

print("Sum of prime numbers:", prime_sum)

Ex.4for num in range(1, 11):

30
if num > 1:

for i in range(2, num):

if (num % i) == 0:

break

else:

print(num)

From statement: It is used to get a specific function in the code instead of complete file. If
we know beforehand which function(s), we will be needing, then we may use 'from'. For
modules having large number of functions, it is recommended to use from instead of import.

Syntax:

>>>from modulename import functionname [, functionname…..]

from modulename import *

Will import everything from the file.

Example: Input any number and to find square and square root.

from math import sqrt,pow


x=int(input("Enter any number:"))
y=sqrt(x) #without using math
a=pow(x,2) #without using math
print ("Square Root value =",y)
print ("Square value =",a)

31
Output

Enter any number:100


Square Root value = 10.0
Square value = 10000.0

The functions available in math module are:

ceil(), floor(),fabs(),exp() ,log(), log10() ,pow(),sqrt(),cos(), sin(), tan() ,degrees(),


radians() ,etc.

Some functions from random module are:

random() ,randint() ,uniform() ,randrange()

2) Built in Function

Built in functions are the function(s) that are built into Python and can be accessed by
Programmer. These are always available and for using them, we don't have to import any
module (file). Python has a small set of built-in functions as most of the functions have been
partitioned to modules. This was done to keep core language precise.

abs(), max(), min(), bin(),divmod(),len(), range(), round(),bool(),chr(), float(),int(), long(),


str(), type(), id( ),tuple( ).

3) User Defined Functions

In Python, it is also possible for programmer to write their own function(s). These functions
can then be combined to form module which can be used in other programs by importing
them. To define a function, keyword 'def' is used. After the keyword, comes an identifier i.e.
name of the function, followed by parenthesized list of parameters and the colon which ends
up the line, followed by the block of statement(s) that are the part of function.

Syntax:
def NAME ([PARAMETER1, PARAMETER2, …..])
#Square brackets include optional part of statement
Example: To find simple interest using function.
def SI(P,R,T):
return((P*R*T)/100)
Output

>>>SI(1000,2,10)
200.0

Lists in python

32
List is a sequence data type. It is mutable as its values in the list can be modified. It is a
collection of ordered set of values enclosed in square brackets []. As it is arranged set of
values, we can use index in square brackets [] to identify a particular value belonging to it.
The set of values that make up a list are called its elements, and they can be of any type.

List is a container that holds a number of elements in a given order. For accessing an
element of the list, indexing is used.

Its syntax is:

variable_name [index]

Here, variable name is name of the list.

It will provide the value at "index+1" in the list. Indices of the lists have to be an integer
value which can be either positive or negative. Positive value of index means counting
forward from beginning of the list and negative value means counting backward from end of
the list.

Let’s look at some example of simple list:

>>>List1 = [1, 2, 3, 4]

# list of 4 integer elements.

>>>List2 = ["Delhi", "Chennai", "Mumbai"]

# list of 3 string elements.

>>>List3 = [ ]

# empty list i.e. list with no element

>>>List4 = ["abc", 10, 20]

# list with different types of elements

>>>List5 = [1, 2, [6, 7, 8], 3]

# A list containing another list known as nested list

Example:

>>>print List1 # let's get the values of list before change


[1, 2, 3, 4]
>>> List1 [1] = 7
>>>print List1 # modified list

33
[1, 7, 3, 4]

Here, 2nd element of the list (accessed using index value 1) is given a new value, so instead
of 2 it will be 7.

Note: An index can have a negative value, in that case counting happens from the end of the
list.

Creating a list

List can be created in many ways:

1. By enclosing elements in [ ] (as we have done in above examples.)


2. Using other lists

Example:

List5=List1 [:]
Here List5 is created as a copy of List1.
>>>print List5
List6 = List1 [0:2]
>>>print List6

Will create List6 having first two elements of List1.

List comprehension

Example:

>>>A= [i**2 for i in range (10)]


>>>printA
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

In mathematical terms, A can be defined as A = {i2for: i in (0.....9)}. So, we can say that list
comprehension is short-hand for creating list.

Let’s create a list of even numbers belonging to 'A' list:

>>> A= [i**2 for i in range (10)]


>>>B = [i for i in A if i % 2 = = 0]
>>>print B
[0, 4, 16, 36, 64]

34
Using built-in object

List = list ( ) will create an empty list

Example:

>>>List = list ( )
>>>print List
[ ] # empty list

Or

List = list (sequence)

Example:

>>>List = list("String")
>>>print List
['S', 't', 'r', 'i', 'n', 'g']

List Operations in Python - I


1) Accessing an element of list

For accessing an element, we use index.Let’s access elements of a list.

>>> List =[1,2,3,[6,7,8],4]

>>>List[0]

>>>print List [3]

[6, 7, 8]

To access an element of list containing another list, we use pair of index. Also a sub-list of
list can be accessed using list slice.

As the 4th element of this List is another list. To access elements of/from this sub-list, we will
use...

>>>print List [2] [0]

35
6

>>>print List [2] [2]

List Slices

Slice operator works on list also. We know that a slice of a list is its sub-list. For creating a
list slice, we use [l:r] operator. This will inclusive for l th element but exclusive for rth element
(including the first element but excluding the last element). So the resultant list will have m-n
elements in it.

>>>List1=[1,2,3,4,5]

>>> List1 [1:2]

will give

[2]

Slices are treated as boundaries, and the result will contain all the elements between
boundaries.

Its Syntax is:

seq = L [start: stop: step]

Where start, stop & step- all three are optional. If you omit first index, slice starts from "0"
and omitting of stop will take it to end. Default value of step is 1.

Example

For list L2 containing ["Gwalior", "Bhopal", "Indore"]

>>>L2 [0:2]

["Gwalior", "Bhopal"]

Example

>>>list = [11,12, 13, 14, 15, 16]

>>>list [::2] # produce a list with every alternate element


[11, 13, 15]
>>>list [4:] # will produce a list containing all the elements from 5th positiontill end[15, 16]
>>>list [:3]

36
[11, 12, 13]
>>>list [:]
[11, 12, 13, 14, 15, 16]
>>>list [-1] # "-1" refers to last elements of list
16

2) Traversing a List

Let us visit each element (traverse the list) of the list to display them on screen. This can be
done in many ways:

>>>List=[2,4,6,8,10]

i) for i in List

print i

will produce following output


2 4 6 8 10

ii) i= 0

L = len (List)

while i < L :

print List [i],

i+=1

will produce the same output.

(iii) for i in range ( len (List))print List [i]

will produce the same output.

Using 2nd way for transversal, we are only able to access the list, but other ways can
alsobe used to update or write the element to the list.

3) Appending in the list

Appending a listmeans adding more elements at the end of the list. To add new elements at
the end of the list, Python provides:

i) append ( )

append () method add a new element at the end of the list.

37
Its Syntax is:

List.append (item)

Example:

>>>List=[1,2,3,4]
>>>List.append(5) # this will add 5 to the list at the end
>>>print List
>>>print len(List) # print length of the list List

will produce following output

[1, 2, 3, 4, 5]
5

38

You might also like