0% found this document useful (0 votes)
13 views28 pages

Introduction to Python- notes

The document provides an introduction to Python programming, detailing its history, features, and installation process. It covers basic concepts such as keywords, identifiers, variables, data types, operators, and user input, along with examples of syntax and type conversion. Additionally, it discusses common errors in Python programming, including syntax and logical errors.

Uploaded by

tanmaywrizz
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
13 views28 pages

Introduction to Python- notes

The document provides an introduction to Python programming, detailing its history, features, and installation process. It covers basic concepts such as keywords, identifiers, variables, data types, operators, and user input, along with examples of syntax and type conversion. Additionally, it discusses common errors in Python programming, including syntax and logical errors.

Uploaded by

tanmaywrizz
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 28

Introduction to Python

In order to tell the computer “What you want to do”, we write a program in a language which
computer can understand. Though there are many different programming languages such as BASIC,
Pascal, C, C++, Java, Haskell, Ruby, Python, etc. but we will study Python in this course.

Before learning the technicalities of Python, let’s get familiar with it. Python was created 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 I991. Python got its name from a BBC comedy series from seventies- “Monty Python’s
Flying Circus”.

Python can be used to follow both Procedural approach and Object-Oriented approach of
programming. It is free to use.

Some of the features which make Python so popular are as follows:

• It is a general-purpose programming language which can be used for both scientific and non-
scientific programming.
• It is a platform independent programming language.
• It is a very simple high-level language with vast library of add-on modules.
• It is excellent for beginners as the language is interpreted, hence gives immediate results.
• The programs written in Python are easily readable and understandable.
• It is suitable as an extension language for customizable applications.
• It is easy to learn and use.
INSTALLATION

To write and run a Python program, we need to have a Python interpreter installed in our computer.
IDLE (GUI integrated) is the standard, most popular Python development environment. IDLE is an
acronym for Integrated Development Environment. It lets edit, run, browse and debug Python
Programs from a single interface. This environment makes it easy to write programs. Python can be
downloaded and installed for free from http://www.python.org/download/ and download the latest
version. We will be using IDLE to run all our programs and exercise.

Running your first python script

EXECUTION MODE

There are two ways to use the Python interpreter:

INTERACTIVE MODE

To work in the interactive mode, we can simply type a Python statement on the >>> prompt directly.
As soon as we press enter, the interpreter executes the statement and displays the result(s)

1|Page
SCRIPT MODE

In the script mode, we can write a Python program in a file, save it and then use the interpreter to
execute it. Python scripts are saved as files where file name has extension ".py".

To create and run a Python script, we will use the following steps in IDLE, if the script mode is not
made available by default with the IDLE environment.

a. File->Open OR File->New Window (for creating a new script file)


b. Write the Python code as function i.e. script
c. Save it (^S)
d. Execute it in interactive mode- by using RUN option (^F5)
Interactive mode allows execution of individual statements instantaneously Whereas, Script mode
allows us to write more than one instruction in a file called Python source code file that can be
executed.

KEYWORDS, IDENTIFIERS AND VARIABLES

Keywords are special identifiers with predefined meanings that cannot change. As these words have
specific meaning for interpreter, they cannot be used for any other
purpose.

2|Page
IDENTIFIERS

Identifiers are the names used to identify a variable, function or other entities in a program. The
rules for naming an identifier in Python are as follows:

1. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more


letters, underscores and digits (0 to 9).

2. Python does not allow special characters like !,@, #, $, % etc.

3. Identifier must not be a keyword of Python.

4. Python is a case sensitive programming language. Thus, Sname and sname are two different
identifiers in Python.

Which of the following are valid variable names in Python?

• 1plus2 • my_book • _age

• If • yes&no • Interest1

A variable in a program is uniquely identified by a name (identifier). Variable in Python refers to an


item or element that is stored in the memory. Value of a variable can be a string (e.g., 'b', 'NSCD'),
numeric (e.g., 345) or any combination of alphanumeric characters (CD67).

ASSIGNMENT OPERATOR

In Python we can use an assignment statement to create new variables and assign specific values to
them. You can declare and assign value to a variable with the assignment operator ‘=’

a=10 (This will assign the value of 10 to the variable ‘a’.)

Multiple Assignments:

Assigning same value to multiple variables:

x = y = z = 100

It will assign value 100 to all three variables x, y and z.

Assigning multiple value to multiple variables

p, q, r = 10, 20, 30

It will assign the value order wise that is value 10 assign to variable p, value 20 assign to variable q
and value 30 assign to variable r.

DATA TYPES

Python has built-in data types such as numbers, strings, lists etc. Every value in Python has a
datatype. Data types are used to define the type of value a data can contain. Data types define the
way to store the values in memory. Since everything is an object in Python programming, data types
are actually classes and variables are instances (objects) of these classes.

3|Page
There are various data types in Python. Some of the important types are mentioned below in the

image-

Numeric Data

are the data-type which represent the numeric values. It can be any number from the -infinity to
+infinity. There are several numeric data types in Python:

Integer

Integer data types are the one which can hold the integral value of the number.

a=5

Float

It is a real number with floating point representation. It is specified by a decimal point.

b=5.5

Sequences

In Python, sequence is the ordered collection of similar or different data types. Sequences allow you
to store multiple values in an organized and efficient fashion. There are several sequence types in
Python:

String

String is an ordered sequence of letters/characters. A string is a collection of one or more characters


put in a single quote(‘ ‘), double-quote (“ “) or triple quote (‘’’ ‘’’). The quotes are not part of string.
They only tell the computer where the string constant begins and ends. They can have any character
or sign, including space in them.

Lists

List is also a sequence of values of any type. It is used to store values of same and different data
types like integer, string, float etc. Values in the list are called elements / items. These are
indexed/ordered. List is enclosed in square brackets.

Example: dob = [19,"January",1990]

OPERATORS

4|Page
Operators are special symbols which represent computation. They are applied on operand(s), which
can be values or variables. Same operators can behave differently on different data types. Operators
when applied on operands form an expression. Operators are categorized as Arithmetic, Relational,
Logical and Assignment. Value and variables when used with operators are known as operands.

ARITHMETIC OPERATORS

Operator Meaning Expression Result

+ Addition 10 + 20 30

- Subtraction 30 - 10 20

* Multiplication 30 * 100 3000

/ Division 30 / 10 3.0

1/2 0.5

// Integer Division 25 // 10 2

1 // 2 0

% Remainder 25 % 10 5

** Raised to power 3 ** 2 9

INPUT AND OUTPUT

In Python, we have the input() function for taking the user input. The input() function prompts the
user to enter data. It accepts all user input as string. The syntax for input() is:

input ([Prompt])

Python uses the print() function to output data to standard output device - the screen.

a = "Hello World!"

print(a)

Example Code Sample Output

a = 20 30

b = 10

print(a + b)

5|Page
print(15 + 35) 50

print("My name is Kabir") My name is Kabir

a = "tarun" My name is : tarun

print("My name is :",a)

x = 1.3 x=

print("x = /n", x) 1.3

m=6 I have 6 apples

print(" I have %d apples",m)

USER INPUT

In all the examples till now, we have been using the calculations on known values (constants). Now
let us learn to take user’s input in the program. In python, input() function is used for the same
purpose.

Syntax Meaning

<String Variable>=input(<String>) For string input

<integer Variable>=int(input(<String>)) For integer input

<float Variable>=float(input(<String>)) For float (Real no.) input

TYPE CONVERSION

The process of converting the value of one data type (integer, string, float, etc.) to another data
type is called type conversion. Python has two types of type conversion.

• Implicit Type Conversion

• Explicit Type Conversion

IMPLICIT TYPE CONVERSION

In Implicit type conversion, Python automatically converts one data type to another data type. This
process doesn't need any user involvement.

EXAMPLE:

# Code to calculate the Simple Interest

6|Page
principle_amount = 2000

roi = 4.5

ime = 10

simple_interest = (principle_amount * roi * time)/100

print("datatype of principle amount : ", type(principle_amount))

print("datatype of rate of interest : ", type(roi))

print("value of simple interest : ", simple_interest)

print("datatype of simple interest : ", type(simple_interest))

When we run the above program, the output will be

datatype of principle amount : <class 'int'>

datatype of rate of interest : <class 'float'>

value of simple interest : 900

datatype of simple interest : <class 'float'>

In the above program,

• We calculate the simple interest by using the variable priniciple_amount and roi with time
divide by 100.

• We will look at the data type of all the objects respectively.

• In the output we can see the datatype of principle_amount is an integer, datatype of roi is a
float.

• Also, we can see the simple_interest has float data type because Python always converts
smaller data type to larger data type to avoid the loss of data.

Example Sample Output Explanation


Code

a = 10 File "cbse2.py", line 3, in The output shows an error which says that we cannot
<module> print(a+b) add integer and string variable types using implicit
b = "Hello"
conversion.
TypeError : unsupported
print(a+b)
operand type(s) for +: 'int'
and 'str'

c = 'Ram' RamRamRam The output shows that the string is printed 3 times
when we use a multiply operator with a string.
N=3

print(c*N)

7|Page
x = True 11 The output shows that the boolean value x will be
converted to integer and as it is true will be
y = 10
considered as 1 and then give the output.
print(x +
10)

m = False 23 The output shows that the boolean value m will be


converted to integer and as it is false will be
n = 23
considered as 0 and then give the output.
print(n –
m)

EXPLICIT TYPE CONVERSION

In Explicit Type Conversion, users convert the data type of an object to required data type. We use
the predefined functions like int(), float(), str(), etc to perform explicit type conversion. This type of
conversion is also called typecasting because the user casts (changes) the data type of the objects.

Syntax:

(required_datatype) (expression)

Typecasting can be done by assigning the required data type function to the expression.

Example: Adding of string and an integer using explicit conversion

Birth_day = 10

Birth_month = "July"

print("Before type casting :", type(Birth_day))

print("data type of Birth_month : ", type(Birth_month))

Birth_day = str(Birth_day)

print("After type casting :",type(Birth_day))

Birth_date = Birth_day + Birth_month

print("birth date of the student : ", Birth_day)

print("data type of Birth_date : ", type(Birth_date))

When we run the above program, the output will be

Before type casting : <class 'int'>

data type of Birth_month : <class 'str'>

After type casting : <class 'str'>

birth date of the student : ' 10 July '

8|Page
data type of Birth_date : <class 'str'>

In above program,

• We add Birth_day and Birth_month variable.

• We converted Birth_day from integer(lower) to string(higher) type using str() function to


perform the addition.

• We got the Birth_date value and data type to be string.

Example Code Sample Explanation


Output

a = 20 20 Apples Writing str(a) will convert integer a into a string and then will
add to the string b.
b = "Apples"
print(str(a)+ b)

x = 20.3 30 Writing int(x) will convert a float number to integer by just


considering the integer part of the number and then perform
y = 10
the operation.
print(int(x) + y)

m = False 1 Writing Bool() will convert the integer value to Boolean.

n=5 If it is zero then it is converted to False, else to True for all


other cases.
print(Bool(n)+ m)

COMPARISON OPERATORS

Comparison operators are used to compare values. It either returns True or False according to the
condition.

Operator Meaning Expression Result

> Greater Than 20 > 10 True

15 > 25 False

< Less Than 20 < 45 True

20 < 10 False

== Equal To 5 == 5 True

9|Page
5 == 6 False

!= Not Equal to 67 != 45 True

35 != 35 False

>= Greater than or Equal to 45 >= 45 True

23 >=34 False

<= Less than or equal to 13 <= 24 True

13 <= 12 False

LOGICAL OPERATORS

Logical operators are the and, or, not operators.

Operator Meaning Expression Result

And And operator True and True True

True and False False

Or Or operator True or False True

False or False False

Not Not Operator not False True

not True False

PYTHON COMMENTS

Comments are non-executable statements written in the program to make it more readable and
understandable to different individuals. A comment is text that doesn't affect the outcome of a code,
it is just a piece of text to let someone know what you have done in a program or what is being done
in a block of code. In Python, single line comments are indicated by # while multiline comments are
placed inside triple quotes (‘’’ ‘’’)

In Python, we use the hash (#) symbol to start writing a comment.

10 | P a g e
TYPES OF ERRORS

There are three types of errors in Python:

A. Syntax error

Errors that occur due to improper syntax of statements in the program are called syntax errors. For
example, parentheses must occur in pairs, thus the statement print (“how is incorrect.

Common Syntax Errors in Python-

1. Misspelling a keyword inpt in place of input ().

2. Missing a keyword.

3. Misusing a keyword input (“enter a number”).

4. Missing parenthesis/brackets, quotes.

5. Incorrect variable naming eg using a reserved word in place of a variable name, using special
characters in a variable name.

6. Incorrect use of assignment operator eg 5=a in place of a=5.

B. Logical error

A logical error is a bug in the program that causes it to behave incorrectly. A logical error produces an
undesired output but without abrupt termination of the execution of the program. Unlike a program
with syntax errors, a program with logic errors can be run, but it does not operate as intended.
Consider the following example of an logical error:

x = float(input('Enter a number: '))

y = float(input('Enter a number: '))

z = x+y/2

print ('The average of the two numbers you have entered is:', z)

11 | P a g e
The example above should calculate the average of the two numbers the user enters. But, because of
the order of operations in arithmetic (the division is evaluated before addition) the program will not
give the right answer:

Enter a number: 3

Enter a number: 4

The average of the two numbers you have entered is: 5.0

To rectify this problem, we will simply add the parentheses: z = (x+y)/2

C. Runtime error

Runtime error is when the statement is correct syntactically, but the interpreter cannot execute it.
Runtime errors do not appear until after the program starts running or executing. A runtime error is a
program error that occurs during the execution of a program. example- Division by zero, trying to
access a file which doesn't exist.

Let’s Practice

Python Code Sample Output

# To calculate Area and Length:50 Breadth:20


Area:100 Perimeter:140
# Perimeter of a rectangle L=int(input("Length"))
B=int(input("Breadth")) Area=L*B Perimeter=2*(L+B)
print("Area:",Area)

print("Perimeter:",Perimeter)

Try writing your code Sample Output

# To calculate Area of a triangle # with Base and Height Base:20

Height:10

#Input Base Area:100

#Input Height

#Calculate Area

#Display Area

# To calculating average marks # of 3 subjects English:80

12 | P a g e
#Input English Marks Maths:75

#Input Maths Marks Science:85

#Input Science Marks Total Marks : 240

#Calculate Total Marks Average Marks: 80.0

#Calculate Average Marks

#Display Total Marks

#Display _________#Average Marks

# To calculate discounted amount # with discount % Amount: 5000

#Input Amount Discount%:10

#Input Discount% Discount:500

#Calculate Discount Discounted Amt:4500

#Calculate ___________Discounted Amount

#Display Discount

#Display ____________Discounted Amount

EXERCISE 4-A

1. Fill in the blanks:

a. Two numeric data types in Python are float and _____________.

b. ________________ function is used to cast the string variable “a” that is equal to “2” into
integer 2

c. _________________ are the names given to memory locations to store values.

d. Special symbols which perform some action on operands______________________.

e. Type conversion method from one data type to another is called__________________.

f. The process of identifying and removing errors from a computer program is called
________________.

2. State True/False. (Write the correct statement if False)

a. ‘+’ operator when used with strings is used to join/concatenate them.

b. 2age is a valid variable name.

c. Python doesn’t require explicit memory management as the interpreter itself allocates
memory to new variables.

d. In Python3, Whatever you enter as input, the input() function converts it into a string.

13 | P a g e
e. The expression int(x) implies that the variable x is converted to integer.

f. Print function cannot be used more than once in a program

g. Comments are used to explain code, make code more readable, and prevent execution when
testing code. Comments start with a # and Python will ignore them.

3. Find and Correct the errors in the following

Code Correction

a. print(“Hello World”)”

b. num2= input(enter num 2)

c. num=5 print(num):

d. age=7:

print(“I am” +age + “years old”):

e. print(Hello World!)

4. Write the output of the following code:

Code Output

a. print(9//2)

b. print(3*1**3)

c. var = "James" * 2 * 3

print(var)

d. valueOne = 5 ** 2

valueTwo = 5 ** 3

print(valueOne)

print(valueTwo)

e. p, q, r = 10, 20 ,30

print(p, q, r)

f. print("hello", "world", "bye" + "-"*3)

g. print("hello"+ "-" + "world" + "-" + "bye")

14 | P a g e
h. print(4 * "test")

i. print(float(5))

5. What is the output of print(2 * 3 ** 3 * 4)

6. What is the value of the following Python Expression print(36 / 4)

7. What is the output of print(2%6)

8. What is the output of this code, if a=1 and b=2?

a=a**b

b=a**b

a=a**b

print(a)

MULTIPLE CHOICE QUESTIONS:

i. In Python3, which functions are used to accept input from the user

a. input() c) raw_input()

b. rawinput() d) string()

ii. What is the output for the given expression?

print(22 % 3)

a. 7 c) 1

b. 0 d) 5

v. Which one of these is used for floor division?

a. / c) //

b. % d) None of the above

vi. Which is the correct output for -

print(3**2)

a. 5 c) 9

b. 6 d) 10

vii. Which of the following cannot be a valid variable name?

a. init c) int

b. it d) on

15 | P a g e
viii. Which of the following is an invalid statement?

a. abc = 1,000,000 c) a b c = 1000 2000 3000

b. a,b,c = 1000, 2000, 3000 d) a_b_c = 1,000,000

ix. Which of the following is an invalid variable name?

a. my_string_1 c) 1st_string

b. foo d) none

x. Which of the following is invalid expression?

a. a=1 c) a = 1

b. str= 1 d) none of the above

xi. Is Python a case sensitive language when dealing with variables?

a. Yes c) no

b. machine dependent d) none of the mentioned

xii. Which of the following options is correct in context to the variable name?

a. Variable name can start with a digit

b. Variable name can start with an underscore

c. keywords can be used as variable names

d. Variable names can have symbols like @,# etc

xiii. Which punctuation symbols are used to mark the beginning and end of a print command in
Python?

a. {} c) [ ]

b. () d) < >

xiv. Which of the following statements is the CORRECT?

a. display("Welcome to Python") c) Print("Welcome to Python")

b. print("Welcome to Python"); d) print("Welcome to Python")

xv. When we save a python file, the extension is

a. python c) .py

b. .pi d) .pt

xvi. In Python, the variable "Program" is the same as "program"

a. Yes

b. No

16 | P a g e
xvii. Storage locations in Python are:

a. Constants c) Data types

b. Variables d) Operators

xviii. The given statement is-


x=y=z= “Python is wonderful!”

a) Valid

b) Invalid

As studied in the previous section, List is a sequence of values of any type. Values in the list are called
elements / items. List is enclosed in square brackets.

Example:

a = [1,2.3,"Hello"]

List is one of the most frequently used and very versatile data type used in Python. A number of
operations can be performed on the lists, which we will study as we go forward.

How to create a list ?

In Python programming, a list is created by placing all the items (elements) inside a square bracket [
], separated by commas.

It can have any number of items and they may be of different types (integer, float, string etc.).

#empty list

empty_list = []

#list of integers

age = [15,12,18]

How to access elements of a list ?

A list is made up of various elements which need to be individually accessed on the basis of the
application it is used for. There are two ways to access an individual element of a list:

1. List Index

2. Negative Indexing

List Index

A list index is the position at which any element is present in the list. Index in the list starts from 0, so
if a list has 5 elements the index will start from 0 and go on till 4. In order to access an element in a
list we need to use index operator [].

Negative Indexing

17 | P a g e
Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the

Second last item and so on.

In order to access elements using negative indexing, we can use the negative index as mentioned in
the above figure.

Task Sample Code Output

Accessing Using List my_list=


Index
['p','y','t','h','o','n'] po

print(my_list[0])

print(my_list[4])

my_list TypeError: list indices must be integers or


=['p','y','t','h','o','n'] slices, not float

print(my_list[4.0])

Accessing using Negative day = ['f','r','i','d','a','y']


Index
print(a[-1]) y

print(a[-6]) f

ADDING ELEMENT TO A LIST

We can add an element to any list using two methods :

1. Using append() method

2. Using insert() method

3. Using extend() method

Using append() method

18 | P a g e
Elements can be added to the List by using built-in append() function. Only one element at a time
can be added to the list by using append() method, for addition of multiple elements with the
append() method, loops are used.

Using insert() Method

append() method only works for addition of elements at the end of the List, for addition of element
at the desired position, insert() method is used. Unlike append() which takes only one argument,
insert() method requires two arguments(position, value).

Using extend() method

Other than append() and insert() methods, there's one more method for Addition of elements,
extend(), this method is used to add multiple elements at the same time at the end of the list.

Task Sample Code Output

Using append() List = []


method
print("Initial blank List: ") Initial blank List: []

print(List)

# Addition of Elements

List.append(1)
List after Addition: [1, 2, 4]
List.append(2)

List.append(4)

print("\nList after Addition : ")

print(List)

Using insert() # Creating a List List = [1,2,3,4]


method
print("Initial List: ")
Initial List: [1, 2, 3, 4]
print(List)

# Addition of Element at specific


Position

List.insert(3, 12) List after InsertOperation: ['Kabir',


1, 2, 3, 12, 4]
List.insert(0, 'Kabir')

print("List after Insert Operation: ")

print(List)

19 | P a g e
Using extend() # Creating a List List = [1,2,3,4]
method
print("Initial List: ") Initial List:[1, 2, 3, 4]

print(List)

# Addition of multiple elements(using


Extend Method)
List after Extend Operation:
List.extend([8, 'Artificial',
'Intelligence']) [1, 2, 3, 4, 8, 'Artificial',
'Intelligence']
print("\nList after Extend Operation: ")

print(List)

REMOVING ELEMENTS FROM A LIST

Elements from a list can removed using two methods :

1. Using remove() method

2. Using pop() method

Using remove() method

Elements can be removed from the list by using built-in remove() function but an Error arises if
element doesn't exist in the set. Remove() method only removes one element at a time, to remove
range of elements, iterator is used. The remove() method removes the specified item.

NOTE – Remove method in List will only remove the first occurrence of the searched element.

Using pop() method

Pop() function can also be used to remove and return an element from the set, but by default it
removes only the last element of the set, to remove an element from a specific position of the List,
index of the element is passed as an argument to the pop() method.

Task Sample Code Output

Using remove() # Creating a List Intial List:


method
List = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,12] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

print("Intial List: ")

print(List)

List after Removal:

# Removing elements from List using [1, 2, 3, 4, 7, 8, 9, 10, 11, 12]


Remove() method

20 | P a g e
List.remove(5)

List.remove(6)

print("\nList after Removal: ")

print(List)

Using pop() # Removing element by using pop() List after popping an element:
method
List.pop() [1, 2, 3, 4, 7, 8, 9, 10, 11]

print("\nList after popping an element:


")

print(List)
List after popping a specific element:
[1, 2, 4, 7, 8, 9, 10, 11]

# Removing element at a specific


location

List.pop(2)

print("\nContent after pop ")

print(List)

LIST METHODS

Some of the other functions which can be used with lists are mentioned below:

Python List Methods

append() Add an element to the end of the list.

extend() Add all elements of a list to the another list.

insert() Insert an item at the defined index.

remove() Removes an item from the list.

pop() Removes and returns an element at the given index.

21 | P a g e
clear() Removes all items from the list.

index() Returns the index of the first matched item.

count() Returns the count of number of items passed as an argument.

sort() Sort items in a list in ascending order.

reverse() Reverse the order of items in the list.

len() Returns number of elements in the list.

EXERCISE 4-B

Q1. Find the error in the following code segments

1. List = [ ]

print("Initial blank List: "

print(List)

# Addition of Elements in the List List.append[1]

List.append[2]

List.append[3]

print("\nList after Addition : ")

print(List)

2. # Creating a List of numbers

List = (10, 20, 30)

print("\nList of numbers: ")

print(List)

3. # To add an item on a specific place in the list

List = ["Delhi", "Mumbai", "Chennai"]

List.insert("Kolkata")

print("\nList Items: ",List)

4. # To remove an item from a specific place in the list

List = ["Delhi", "Mumbai", "Chennai"]

22 | P a g e
List.remove(2)

print("\nList Items: ",List)

5. # Finding number of items in list

List = [14,23,45,67,89,36]

print((count(List)))

6. #Print the list from second element to fourth element

r=["Hello", "Hola", "Bonjour", "Namaste", "Hallo"]

print(r[1;4])

Q2. Write the output of following programs-

1. marks=[5,10,15,20]

print(sum(marks))

2. list=[12,45,0,73,5]

print(list[2]*list[4])

3. letter=["A","B","C","D","E"]

letter.reverse()

print(letter)

In the programs we have seen till now, there has always been a series of statements faithfully
executed by Python in exact top-down order. What if you wanted to change the flow of how it
works? For example, you want the program to take some decisions and do different things depending
on different situations, such as printing 'Good Morning' or 'Good Evening' depending on the time of
the day?

As you might have guessed, this is achieved using control flow statements. There are three control
flow statements in Python - if, for and while.

There come situations in real life when we need to make some decisions and based on these
decisions, we need to decide what should we do next. Similar situations arise in programming also
where we need to make some decisions and based on these decisions we will execute the next block
of code.

23 | P a g e
Decision making statements in programming languages decide the direction of flow of program
execution. Decision making statements available in Python are:

● if statement

● if..else statements

● if-elif ladder

IF STATEMENT

The if statement is used to check a condition: if the condition is true, we run a block of statements
(called the if-block).

SYNTAX:

if text expression:

statement(s)

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.

NOTE:

• In python, the body of the if statement is indicated by the indentation. Body starts with an
indentation and the first unindented line marks the end.

• Python interprets non-zero values ad True. None and 0 are interpreted as False.

Python if Statement Flowchart Example

#Check if the number is positive message

num = 3

if num > 0:

print(num, “is a positive number.”)

print(“this is always printed”)

24 | P a g e
When you run the program, the output will be:

3 is a positive number

This is always printed

In the above example, num > 0 is the test expression. The body of if is executed only if this evaluates
to True.

When variable num is equal to 3, test expression is true and body inside body of if is executed.

NOTE: The print() statement falls outside of the if block (unindented). Hence, it is executed
regardless of the test expression.

Python if...else Statement

SYNTAX of if...else:

if test expression:

Body of if

else:

Body of else

The if..else statement evaluates test expression and will execute body of if only when test condition
is True.

If the condition is False, body of else is executed. Indentation is used to separate the blocks.

Python if..else Flowchart Example of if...else

#A program to check if a person can vote

age = input(“Enter Your Age”)

if age >= 18:

print(“You are eligible to vote”)

else:

print(“You are not eligible to vote”)

In the above example, when if the age entered by the person is greater than or equal to 18, he/she
can vote. Otherwise, the person is not eligible to vote.

Python if...elif...else Statement

25 | P a g e
SYNTAX of if...elif...else:

if test expression:

Body of if

elif test expression:

Body of elif

else:

Body of else

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.

Python if...elif...else Flowchart Example of if...elif...else

#To check the grade of a student Marks = 60

if marks > 75:

print("You get an A grade")

elif marks > 60:

print("You get a B grade")

else:

print("You get a C grade")

THE FOR LOOP

The for...in statement is another looping statement which iterates over a sequence of objects i.e. go
through each item in a sequence. We will see more about sequences in detail in later chapters. What
you need to know right now is that a sequence is just an ordered collection of items.

26 | P a g e
Syntax of for Loop:

for val in sequence:

Body of for

Here, val is the variable that takes the value of the item inside the sequence on each iteration.

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.

# Program to find the sum of all numbers of a list

# List of numbers

numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]

#variable to store the sum

sum = 0

# iterate over the list

for val in numbers:

sum = sum+val

# Output: The sum is 48

print("The sum is", sum)

when you run the program, the output will be:

The sum is 48

THE WHILE STATEMENT

The while statement allows you to repeatedly execute a block of statements as long as a condition is
true. A while statement is an example of what is called a looping statement. A while statement can
have an optional else clause.

while test_expression:

Body of while

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.

27 | P a g e
Flowchart of while Loop Example: Python while Loop

# Program to add natural # numbers upto

# sum = 1+2+3+...+n

# To take input from the user

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

n = 10

# initialize sum and counter

sum = 0

i=1

while i <= n:

sum = sum + i

i = i+1

# print the sum

print("The sum is", sum)

when you run the program, the output will be:

Enter n: 10

The sum is 55

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

We need to increase the value of the 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 is displayed.

28 | P a g e

You might also like