0% found this document useful (0 votes)
10 views20 pages

Ln. 3 - Brief Overview of Python

This document provides an overview of Python, a high-level programming language created in 1991, highlighting its advantages, limitations, and various applications. It covers essential concepts such as downloading Python, working in interactive and script modes, data types, variables, operators, and includes example programs. Additionally, it explains Python's syntax, keywords, and the use of functions like print(), input(), and type().

Uploaded by

studynerd247
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views20 pages

Ln. 3 - Brief Overview of Python

This document provides an overview of Python, a high-level programming language created in 1991, highlighting its advantages, limitations, and various applications. It covers essential concepts such as downloading Python, working in interactive and script modes, data types, variables, operators, and includes example programs. Additionally, it explains Python's syntax, keywords, and the use of functions like print(), input(), and type().

Uploaded by

studynerd247
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

LESSON 3 – BRIEF OVERVIEW OF PYTHON

Introduction-
Python is a popular high level programming language.
It was created in 1991 by Guido van Rossum.
It is used for: Web applications , software development , mathematics , Game development ,
Database applications , System Administrators, AI
Owing to its user-friendliness, Python has been used to create some of the most popular websites
in the world of internet such as: Google, Youtube, Instagram etc

Advantages of Python-
• Python works on different platforms (Windows, Mac, Linux, etc).
• Python has a simple syntax and is easy to learn it.
• It is possible to get desired output in minimum instructions.
• Python is an interpreted language. This means that Python interprets and executes the code line
by line.
• It is an easy to debug language and is suitable for beginners and advanced users.
• It is a platform independent and portable language.
• It is easy to download and install.

Limitations of Python-
• It is not a fast language. Slow Execution Speed
• High Memory Consumption.
• It is not easy to convert it to some other language.
• Not strong on ‘Type Binding’ ie.. It does not catch type mismatch issues.
• It is case sensitive.
• Design restrictions

How to download Python?


✓ Python can be downloaded from www.python.org
✓ It is available in two versions- Python 2.x and Python 3.x
✓ Open www.python.org on any browser.
✓ To write and run (execute) a Python program, we need to
have a Python interpreter installed on our computer or
we can use any online Python interpreter.
✓ The interpreter is also called Python shell.
✓ IDLE is Python’s Integrated Development and Learning
Environment.
✓ After installation, open Python IDLE 3.6.5, and a window
will be opened which will look like-

How to work in Python?


• We can work in Python in two ways- Interactive Mode , Script Mode
• To work in both of these , you need to open Python IDLE.

Interactive mode-
• It works like a Command Interpreter or as a Shell Prompt.
• Here we can type the command – one at a time and then Python executes it then and there.
• The command has to be typed after the command prompt ( >>>).
• It indicates that the interpreter is ready to receive instructions.
• We can type commands or statements on this prompt for execution.

Script mode:
• Here we can save the commands entered by the user in the form of a program.
• We can run a complete program by writing in Script mode.
To work in a script mode, you have to do the following-
Step 1 : Create module/ script / program file
Click File → New in the IDLE python shell. A new
window pops up.
Type the commands.
Click File → Save with an extension .py
Step 2 : Run module/ script / program file
Open the file created. File → Open
Run → Run module command or F5
Commands are executed and the o/p is seen in the
interactive mode.

PRINT command:
The Python print statement is used to print or display results.
Syntax:
print (“string”)
Eg: print("Hello, World!")
The string can be in double or single quotes.

COMMENTS:
Comments are used to add a remark or a note in the source code.
Comments are not executed by the interpreter.
They are added with the purpose of making the source code easier for humans to understand.
In Python, a single line comment starts with # (hash sign).
Everything following the # till the end of that line is treated as a comment and the interpreter
simply ignores it while executing the statement.
Eg:
#This is a comment.
print("Hello, World!")

Keywords :
 Keywords are reserved words that has a specific meaning to the Python interpreter.
 Cannot be used as identifiers, variable name or any other purpose.
 Eg: False, class, None, True, and, as, break, if, in try, with, is etc.

Identifiers :
• Identifiers are names used to identify a variable, function, or other entities in a program.

Rules to follow for naming Identifiers :


The name should begin with an uppercase or a lowercase alphabet or an underscore sign (_). Thus,
an identifier cannot start with a digit.
It can be of any length. But better to keep it short and meaningful.
It should not be a keyword or reserved word•
We cannot use special symbols like !, @, #, $, %, etc.
Eg: Myfile, Date9_7_17, Z2T0Z9, _DS, _CHK FILE13.
Some invald identifiers are – DATA-REC, 29COLOR, break, My.File.

Variables-
While programming it is often necessary to store a value for later use, in the program.
A variable is like a box that can be used to store a piece of information.
We give each box (a variable) a name, so we can use the data stored with it when needed.
Variables are containers for storing data values.
Its values can change during the execution of a program.
In Python, we can use an assignment statement to create new variables and assign specific values
to them.
Eg:-
gender = 'M'
message = "Keep Smiling"
price = 987.9

Variable Names-
• A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume).
• Rules for Python variables:
✓ A variable name must start with a letter or the underscore character
✓ A variable name cannot start with a number
✓ A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
✓ Variable names are case-sensitive (age, Age and AGE are three different variables)

Examples of Multiple Assignments:


a=b=c=125
a, b, c = 1, 2, “john”
x,y = y,x
print (x,y)
a, b, c = 10, 20, 30
Which means, a= 10 b=20 c=30

Program 1 : # Get the values of two numbers in 2 variables , Swap the values , Display the results
x=100
y=200
x,y=y,x
x,y O/p→ (200, 100)

Program 2 : Write a Python program to find the area of a rectangle given that its length is 10 units
and breadth is 20 units.
length = 10
breadth = 20
area = length * breadth
print(area)

Program 3 :
# Get the marks of 5 subjects , Calculate the sum & average , Display the results
eng = 56
mat = 59s
sci = 64
sst = 78
seclan = 89
average = (eng+mat+sci+sst+seclan) / 5
print ("the average score is: ", average)

id( ) Function
• The id () function is the object's memory address.
• It returns a unique id for the specified object.
• All objects in Python has its own unique id.
• The id is assigned to the object when it is created.

Examples
n = 300
print (n)
O/p: 300
print (id(n))
O/p : 157379912

Data Types
Every value belongs to a specific data type in Python.
Data type identifies the type of data which a variable can hold and the operations that can be
performed on those data.
Number , String, Boolean , List , Tuple , Set, Dictionary
Data Type Definition Example

Numbers To hold only numeric values 1000

String Consists of a set of characters. Dave

Boolean The two data values are TRUE and FALSE, TRUE
represented by 1 or 0.

List An ordered sequence of items. Mutable. [1, 2.2, 'python']

Tuple An ordered sequence of items same as list. The only (5,'program',


difference is that tuples are immutable. Tuples once 1+3j)
created cannot be modified.

Set An unordered collection of unique items. {1,2,2,3,3,3}

Dictionary An unordered collection of key-value pairs. {1:'value','key':2}

String Data Types


• String is a group of characters.
• These characters may be alphabets, digits or special characters including spaces.
• String values are enclosed either in single
quotation marks (for example ‘Hello’) or in
double quotation marks (for example “Hello”).
• We cannot perform numerical operations on
strings, even when the string contains a numeric
value.
>>> str1 = 'Hello Friend'
>>> str2 = "452"
• String is of 2 types- Single line string , Multi line string

Numbers
• It is used to store numeric values
• Python has three numeric types: Integers, floating point, complex
int : This type is used to store positive or negative numbers with no decimal points.
Example: a = 10 b = 20
Ø float : If we want to take decimal points also than we go with the float data type.
Example: a = 10.5 b = 5.3
Ø complex : Complex data types are used to store real and imaginary values.
Example: a = x+yj Where x is called real part and y is called imaginary part.
a = 5+10j

Type Conversion
Type Conversion of Integer: Output :-
int() function converts any data type to integer.
e.g. a = "101“ # string 101
b=int(a) # converts string data type to integer. 122
c=int(122.4) # converts float data type to integer.
print(b)
print(c)
Type Conversion of Floating point:
float() function converts any data type to floating point number.
Output :-
e.g. a='301.4‘ #string
b=float(a) #converts string to floating point. 301.4
c=float(121) #converts integer to floating point 121.0
print(b)
print(c)

Boolean Data Types


• It is a unique data type, consisting of two constants, True and False.
• The equality operator = = compares 2 values and produces a boolean value related to whether the
2 values are equal to one another.
Eg:- print(5= = 5) O/P à True
• The bool ( ) method will return or convert a value to a boolean value.
• Syntax, bool( [x])
Eg:- x= True
bool(x) O/P à True
• If no parameter is passed then by default it returns False.

List & Tuples


• A list in Python represents a list of comma-separated values of any datatype between square
brackets. Eg:- colors=['red','blue','green']
• Lists can be changed /modified
• A tuple is a collection of values, and we declare it using parentheses. Eg:- numbers=(1,2,'three')
• Tuple cannot be changed.

Set & Dictionary


• Set is an unordered collection of unique items that cannot be changed.
e.g. set1={11,22,33,22}
print(set1) Output {33, 11, 22}
• The dictionary is an unordered set of comma-separated key: value pairs, within { }
• e.g. name = {'Navneet': 35, 'Gaurav': 42,‘Sunit’: 36, ‘Vikas’:40}
print(name)

type () function
• type() function is used to find a variable's type in Python.
>>> quantity = 10
>>> type(quantity)
<class 'int'>
>>> Price = -1921.9
>>> type(price)
<class 'float'>

Type Error:
When you try to perform an operation on a data type which is not suitable for it, then Python raises an
error called Type Error.
Note:
• Function int ( ) around input( ) converts the read value into int type.
• Function float ( ) around input( ) converts the read value into float type.
• You can check the type of read value by using the type ( ) function after the input ( ) is executed.
>>> type(age_new)
<class 'int'>

Input Function :
• The input() function allows user input.
Syntax: input()
Note:
The input( ) always returns a value of String type.
When the output is displayed it encloses the values within quotes.
Try to perform some operation on the command.
Eg: age + 1
An error occurs as an integer cannot be added to a string.
Type Error: When you try to perform an operation on a data type which is not suitable for it,
then Python raises an error called Type Error.

Program to find SI
principle=float(input("Enter the principle amount:"))
time=int(input("Enter the time(years):"))
rate=float(input("Enter the rate:"))
simple_interest=(principle*time*rate)/100
print("The simple interest is: ",simple_interest)

Operators
Operators are special symbols in Python that carry out operations on variables and values.
The value that the operator operates on is called the operand.
Types of operators are - Arithmetic operators , Assignment operators , Comparison operators ,
Logical operators , Membership operators

Arithmetic operators-
Arithmetic operators are used with numeric values to perform common mathematical operations.
/ - Divide left operand by the right one and returns quotient.
% - Modulus - Divides left hand operand by right hand operand and returns remainder
// - Floor division Divide left operand by the right one and returns quotient without the decimal
value.
** - Exponent – returns the result of a number raised to the power.

Operator Precedence
• In Python, as in mathematics, we need to keep in mind that operators will be evaluated in order
of precedence, not from left to right or right to left.

Program - Find the area of a triangle-


s = (a+b+c)/2
area = √(s(s-a)*(s-b)*(s-c))
a=5b=6c=7
a = float(input('Enter first side: ‘))
b = float(input('Enter second side: ‘))
c = float(input('Enter third side: ‘))
s = (a + b + c) / 2
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)

Assignment Operators
Assignment operators are used to assign values to the variables.
a = 5 is a simple assignment operator that assigns the value 5 on the right to the variable a on
the left.
Assign(=)
Assigns a value to the expression on the left.
Note: = = is used for comparing, but = is used for assigning.

Add and Assign(+=)


Adds the values on either side and assigns it to the expression on the left.
a+=10 is the same as a=a+10.
The same goes for all the next assignment operators.
Subtract and Assign(-=) Divide and Assign(/=)
Multiply and Assign(*=) Modulus and Assign(%=)
Exponent and Assign(**=) Floor-Divide and Assign(//=)
Relational Operators
Relational operators compares the values.
It either returns True or False according to the condition.
It works with nearly all types of data like numbers, list, string etc.

• For numeric types, the values are compared after removing the zeroes after decimal point from a
floating point number. So 3.0 and 3 are equal.
• In strings, capital letters are lesser than small letters.
• For eg:- ‘A’ is less than ‘a’ because ASCII value of A=65 and a=97.
Note:
To get the ASCII code of a character, use the ord() function.
>>> ord('a') 97
>>> ord('.') 46

Logical Operators
Logical operators refer to the ways in which the relations among values can be connected.

x = True
y = False
print('x and y is',x and y)
Output
print('x or y is',x or y)
('x and y is', False)
print('not x is',not x)
('x or y is', True)
x=5 ('not x is', False)
print(x > 3 and x < 10)
# returns True because 5 is greater than 3 AND 5 is less than 10

Membership Operators
Membership operators in Python are used to test whether a value is found within a sequence such as
strings, lists, or tuples.
Operator Description
in Evaluates to true if it finds a variable in the specified sequence
and false otherwise.
not in Evaluates to true if it does not finds a variable in the specified
sequence and false otherwise.

Example-
>>> 'Hello' in 'Hello world!' True
>>> 'house' in 'Hello world!' False
>>> 'house' not in 'Hello world!' True
haystack = "The quick brown fox jumps over the lazy dog."
needle = "fox"
result = needle in haystack
print("result:", result) O/p - True

Operator Precedence
Highest precedence to lowest precedence table
Operator Description
() Parentheses
** Exponentiation (raise to the power)
~+- Complement, unary plus and minus
* / % // Multiply, divide, modulo and floor division
+- Addition and subtraction
>> << Right and left bitwise shift
& Bitwise 'AND'td>
^| Bitwise exclusive `OR' and regular `OR'
<= < > >= Comparison operators
<> == != Equality operators
= %= /= //= -= Assignment operators
+= *= **=
is , is not Identity operators
In, not in Membership operators
not or and Logical operators

# Python Program to find Volume & Surface Area of a Cylinder


PI = 3.14
radius = float(input('Please Enter the Radius of a Cylinder: '))
height = float(input('Please Enter the Height of a Cylinder: '))
sa = 2 * PI * radius * (radius + height)
Volume = PI * radius * radius * height
print("\n The Surface area of a Cylinder = " sa)
print(" The Volume of a Cylinder = " Volume)

Expressions
✓ An expression is defined as a combination of constants, variables and operators.
✓ An expression always evaluates to a value.
✓ A value or a standalone variable is also considered as an expression but a standalone operator is
not an expression.
✓ Some examples of valid expressions are given below.
(i) num – 20.4 (iii) 23/3 -5 * 7(14 -2)
(ii) 3.0 + 3.14 (iv) "Global"+"Citizen"

Ordinal value / Unicode value of a character


ord() function: It gives ASCII value of a single character.
chr() function: It takes the ordinal value in integer form and returns the character corresponding to
that ordinal value.
ord ("a") : 97 chr(97) : “a"
Ord (“A”) : 65 chr(90) : “Z"
ord ("Z") : 90 chr(48) : “0”
ord("0") : 48 chr(65) : “A”
Mutable & Immutable Types
• Objects whose value can change are said to be mutable; list, set, dict) are mutable.
• Objects whose value will not change are said to be immutable. Eg:- int, float, bool, str, tuple
• When an object is initiated, it is assigned a unique object id.
• Mutability means that in the same memory address, new values can be stored when you want.

end parameter in print( )


• To print in one line use, [Use script mode]
PRINT ( “Hello World”, end=“”)
PRINT ( “This is me ”) Output => Hello WorldThis is me
Or
PRINT ( “Hello World”, end=“ , ”)
PRINT ( “This is me ”) Output => Hello World , This is me
Note: The end=' ' is just to say that you want a space after the end of the statement instead of a new
line character.

sep argument
• The sep argument specifies the separator character.
• If no value is given for sep, then by default, print( ) will add a space in between items when
printing.
Print(“Hi”,”My”,”name”,”is”,”Jeny”)
This gives the output
My name is Jeny
Here since sep character is a space, here the words will have spaces between them.
print("My","name","is",“Jeny",sep='...')
The output is-
My...name...is...Jeny
My.*.*.*.*.*name.*.*.*.*.*is.*.*.*.*.*Jeny

Strings - Traversing a string


• Traversing means iterating through the elements of a string one character at a time.
• We can traverse a string character by character using the index.
Index
❑ The characters in a string can be accessed using its index.
❑ The Characters are given in two-way indices:
❑ 0 , 1 , 2 , …… in the forward direction
❑ -1 , -2 , -3 ,…… in the backward direction.

Accessing String Elements OUTPUT-


str='Computer Science'
print('str -', str) str - Computer Science
print('str[0] -', str[0]) str[0] - C
print('str[1:4] -', str[1:4]) str[1:4] - omp
print('str[2:] -', str[2:]) str[2:] - mputer Science
print('str *2 -', str *2 ) str *2 - Computer ScienceComputer Science
print("str +'yes' -", str +'yes') str +' yes' - Computer Science yes

String slices
• It is a part of a string where strings are sliced using a range of indices.
• The syntax of slice is:
[start: stop: step]
word = “RESPONSIBILITY”
word[ 0 : 14 ] RESPONSIBILITY
word[ 0 : 3] RES
word[ 2 : 5 ] SPO
word[ -7 : -3 ] IBIL
word[ : 14 ] RESPONSIBILITY
word[ : 5 ] RESPO
word[ 3 : ] PONSIBILITY

word='amazing'
>>> word[1:6:2] → 'mzn'
>>> word[-7:-3:3] → 'az'
>>> word[ : :-2] → 'giaa'
s="Hello"
>>> print(s[5]) → Out of range error

Program – [To print the reverse of a string – PALINDROME ]


a=str(input("Enter a string: "))
print("Reverse of the string is: ")
print(a[ : :-1])
Output-
Enter a string: WELCOME
Reverse of the string is: EMOCLEW

Note:
• For any index n, s[:n] + s[n:] will give the original string s.
• String [ : : -1] is an easy way to reverse a string using string slice mechanism.
Eg:-
s="AMAZING"
print(s[:3]+s[3:])
O/p - AMAZING

name = “superb”
for ch in name:
print(ch , “-”, end=“ “)
OUTPUT-
Program
str= "SCHOOL" S
for i in str: C
print(i) H
O
O
Questions- L
Write the corresponding Python assignment statements:
a) Assign 10 to variable length and 20 to variable breadth
length, breadth=10, 20
b) Assign the average of values of variables length and breadth to a variable sum.
Sum= (length + breadth) / 2
) Assign a list containing strings ‘Paper’, ‘Gel Pen’, and ‘Eraser’ to a variable stationery.
Stationery= [‘Paper’, ‘Gel Pen’, ‘Eraser’ ]
d) Assign the strings ‘Mohandas’, ‘Karamchand’, and ‘Gandhi’ to variables first, middle and last.
first, middle , last= ‘Mohandas’, ‘Karamchand’, ‘Gandhi’
e) Assign the concatenated value of string variables first, middle and last to variable fullname. Make
sure to incorporate blank spaces appropriately between different parts of names.
Fullname= first+’ ‘ +middle+ ‘ ‘ +last

Give the output of the following when num1 = 4, num2 = 3, num3 = 2


a) num1 += num2 + num3
print (num1) O/p- 9
b) num1 = 2 ** (num2 + num3)
print (num1) O/p- 32
c) a = '5' + '5'
print(a) O/p- 55
d) print(4.00/(2.0+2.0)) O/p- 1.0
e) num1 = 2+9*((3*12)-8)/10
print(num1) O/p- 27.2
f) num1 = float(10)
print (num1) O/p- 10.0
g) num1 = int('3.14’)
print (num1) O/p- error
h) print(10 != 9 and 20 >= 20) O/p- True
i) print(5 % 10 + 10 < 50 and 29 <= 29) O/p- True

String Operators
Concatenation operator +
Replication operator *
Membership operators in , not in
Comparison operators < <= > >= == !=

Concatenation Operator
The + operator creates a new string by joining the 2 operand strings.
Eg:- “tea” + “pot” Output - teapot
“1” + “1” Output - 11
“123” + “abc” Output - 123abc
Note: The statement “2” + 3 will give an error because we cannot combine numbers and strings

Replication Operator
This operator when used with a string replicates same string multiple times.
e.g. "XY" * 3 will give: "XYXYXY"
"3" * 4 will give: "3333“
"5" * "7" is invalid
5* ”@” will give “@@@@@”
Note: operands must be one string & other Number

Membership Operator
• in – Returns true if a character or a substring exists in the given string and false otherwise.
• not in - Returns true if a character doesn’t exist in the given string and false otherwise.
Note: Both the operands must be strings.
“a” in “Sanjeev” will result into True.
“anj” not in “Sanjeev” will result into False.

Comparison Operators
Python’s comparison operators are –
< <= > >= == !=
“a” == “a” True
“abc”==“abc” True
“a”!=“abc” True
“A”==“a” False
‘a’<‘A’ False (because Unicode value of lower case is higher than upper case)

Debugging
• The process of identifying and removing logical errors and runtime errors is called debugging.
• We need to debug a program so that is can run successfully and generate the desired output.
• Due to errors, a program may not execute or may generate wrong output.
❖ Syntax errors
❖ Logical errors
❖ Runtime errors

Syntax errors
• The formal set of rules defined for writing any statement in a language is known as syntax.
• When the syntax rules of a programming language are violated, syntax errors will arise.
• Syntax errors are the most basic type of error.
• If any syntax error is present, the interpreter shows error message(s) and stops the execution
there.
• Such errors need to be removed before execution of the program.
Examples:
missing parenthesis, incompatible data types
print "hello world
a = 3 + ‘5 7’

Runtime errors
• A runtime error causes abnormal termination of program while it is executing.
• It occurs when the statement is correct syntactically, but the interpreter can not execute it.
• Also called exceptions because they usually indicate that something exceptional (and bad) has
happened.
• A syntax error happens when Python can't understand what you are saying. A run-time error
happens when Python understands what you are saying, but runs into trouble when following
your instructions.
Eg:-
• division by zero
• performing an operation on incompatible types.
• using an identifier which has not been defined.

Logical errors / Semantic error


• Errors that occur due to the mistake on the part of the user are called logical errors.
• You won't get an error message, because no syntax or runtime error has occurred.
• These are the most difficult errors to find and debug.
• It does not stop execution but the program behaves incorrectly and produces undesired /wrong
output.
Ex : Typing a +b + c / 3 instead of (a + b+ c) /3

Function
• A function refers to a set of statements or instructions grouped under a name that perform
specified tasks.
• For repeated or routine tasks, we define a function.
• A function is defined once and can be reused at multiple places in a program by simply writing the
function name, i.e., by calling that function.

Built in Function
• Python has many predefined functions called built-in functions.
• Eg:- print() and input().
• Use of built-in functions makes programming faster and efficient.
• A module is a python file in which multiple functions are grouped together.
• These functions can be easily used in a Python program by importing the module using import
command.
• To use a built-in function we must know the following about that function: Function Name,
Arguments , Return Value

User defined functions


• Functions that we define ourselves to do certain specific task are referred as user-defined
functions.
Syntax of User defined Functions
Function Definition:
def function_name(parameters):
# Function body
return result
Function call:
function_name(arguments)

Program Flow control-


• Flow control is the process of managing the execution of the program.

Types of statements-
✓ Sequential statements
✓ Selection or Control statements
✓ Iteration or Looping statements

Sequential Statements
• Till now we were dealing with statements that only consisted of sequential execution, in which
statements are always performed one after the next, in exactly the order specified. These are
sequential statements.
• But at times, a program needs to skip over some statements, execute a series of statements
repetitively, or choose between alternate sets of statements to execute. That is where control
structures come in.

Control statements
❑ Control statements are used to control the flow of execution depending upon the specified
condition/logic.
❑ Also known as decision making statements.
The if statement is the conditional statement in
Python. There are 3 forms of if statement:
1. Simple if statement
2. The if..else statement
3. The if..elif..else statement

If statements-
The block of code in an if statement only
executes code when the expression value is
True.
Simple if statement
The if statement tests a condition. If the condition is True, it carries out some instructions and does
nothing in case the condition is False.
Syntax
if <condition>:
statement
eg: -
if x >1000:
print(“x is more”)

The if-else statement


The if - else statement tests a condition and in case the condition is True, it carries out statements
indented below if and in case the condition is False, it carries out statement below else.
Syntax
if <condition> :
statement
else :
statement
e.g.
if amount>1000:
disc = amount * 0.10
else:
disc = amount * 0.05

if……elif…….else statement
An elif statement can check multiple expressions and executes a block of code as soon as one of the
conditions evaluates to True.
If the condition1 is True, it executes statements in block1, and in case the condition1 is False, it
moves to condition2, and in case the condition2 is True, executes statements in block2, so on.
In case none of the given conditions is true, then it executes the statements under else block
The else statement is optional and there can only be a maximum of one else statement following
an if.
Syntax is-
if <condition1> :
statement
elif <condition2> :
statement
elif <condition3> :
statement
........………………….
else :
statement
Example:
mark = int(input("What mark did you get? "))
if mark > 60:
print("You got a distinction!")
elif mark > 50:
print("You received a merit")
elif mark > 40:
print("You passed")
else
print("Please try the test again")
Nested if
• You can place an if (or if…else, if…elif) statement inside another statement.
• This process is called nesting and enables you to make complex decisions based on different
inputs. Here is a sample syntax:
if condition:
if condition:
statements
else:
statements
else:
statements

Iteration statements (Loop)


• Iteration statements are used to execute a block of statements as long as the condition is true.
• Loops statements are used when we need to run same code again and again.
• Python Iteration(Loops) statements are of 2 types :-
1. While Loop – It is the conditional loop that repeats until a certain condition happens.
2. For Loop – It is the counting loop that repeats a certain number of times.

for loop
• It is used to iterate over items of any sequence, such as a list or a string.
• Syntax-
for variables in sequence:
statements
Eg:-
for i in [3,5,10]:
print(i)
print(i * i) Output- 3 9 5 25 10 100

Range function
The range() function generates a list. Its parameters are-
Start: Starting number of the sequence
Stop: Generates numbers upto this number, excluding it.
Step(optional) : Determines the increment between each number in the sequence.

Eg:- for i in range(5,3,-1):


print(i)
Output- 5
4

range( 1 , n): will produce a list having values starting from 1,2,3… upto n-1. The default step size is 1
range( 1 , n, 2): will produce a list having values starting from 1,3,5… upto n-1. The step size is 2
1) range( 1 , 7): will produce 1, 2, 3, 4, 5, 6.
2) range( 1 , 9, 2): will produce 1, 3, 5, 7.
3) range( 5, 1, -1): will produce 5, 4, 3, 2.
4) range(5): will produce 0,1,2,3,4. Default start value is 0

#Print numbers till a limit


n=int(input('Enter the limit'))
for i in range(1, n+1):
print(i)

# Print numbers from 20 to 1 in decreasing order


for i in range(20, 0,-1):
print(i)

for loop
For x in range(5):
print(‘This is iteration number: ‘, x)
Output-
This is iteration number: 0
This is iteration number: 1
This is iteration number: 2
This is iteration number: 3
This is iteration number: 4

Nested for Loops


• A loop inside another loop is called a nested loop.
Syntax-
for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)

Eg:- adj = ["red", "big", "tasty"]


fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)

While loop
• With the while loop we can execute a set of statements as long as a condition is true.
• It is an entry controlled loop, ie….it first checks the condition and if it is true then only enters the
loop.
• While loop contains various loop elements-
initialization, test condition, body of loop, update statement
• Syntax-
while (condition) :
statement

Example- Infinite loop


a=1
while a<=10:
print(a)

TIP:
To cancel the running of an endless loop, use CTRL + C

Program-
count = 0
while (count < 9):
print ('The count is:', count)
count = count + 1
print ("Good bye!" )

SAMPLE PROGRAMS-

Program - Compound Interest = P (1 + r/100) n


p = float(input(" Please Enter the Principal Amount : "))
r = float(input(" Please Enter the Rate Of Interest : "))
n = float(input(" Please Enter number of times : "))
ci = p * ((1 + (r/100) ** n
print("Compound Interest = “, ci)

Program - Temp conversion


Fahrenheit = int(input("Enter a temperature in Fahrenheit: "))
Celsius = (Fahrenheit - 32) * 5.0/9.0
print ("Temperature:", Fahrenheit, "Fahrenheit = ", Celsius, " C" )

Program - Accept a number and check if it is positive, negative or zero.


num= float(input("Enter a number: "))
if num>= 0:
if num== 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")

Program - Find the largest of 3 numbers.


X = int (input(“Enter Num1 : ” ))
Y = int (input(“Enter Num2 : ” ))
Z = int (input(“Enter Num3 : ” ))
if X >= Y and X >= Z:
Largest = X
elif Y>=X and Y>=Z:
Largest = Y
else:
Largest = Z
print(“Largest Number :”, Largest)
Program - Prog to find if a number is even or odd
num = int(input("Enter a number: "))
if (num % 2) == 0:
print("Even number”)
else:
print(“Odd number”)

Program - Ticket eligibility


age = 38
if (age >= 11):
print ("You are eligible to see the Football match.")
if (age <= 20 or age >= 60):
print("Ticket price is $12")
else:
print("Ticket price is $20")
else:
print ("You're not eligible to buy a ticket.")

Program – Arithmetic operations


num1 = input (“Please enter a number”)
num2 = input (“Please enter a second number”)
op = input (“Select an operation: 1. Add 2. Subtract 3. Multiply”)
if op == 1:
add = num1 + num2
print add
elif op == 2:
sub = num1 – num2
print sub
elif op == 3:
mul = num1*num2
print mul

Program - Sum of Series


Sum=0
for i in range(1, 11):
print(i)
Sum=Sum + i
print(“Sum of Series”, Sum)
Output:
1 2 3 4 5 6 7 8 9 10
Sum of Series 55

Program – Multiplication Table


num=5
for a in range (1,11) :
print(num, ‘x’ , a, ‘=‘, num * a

Output:
5x1=5 5 x 2 = 10 ………………………………….. 5 x 9 = 45 5 x 10 = 50

Program - To find sum of the digits


num = int(input(“Enter the number :”))
ds = 0
while num>0 :
ds = ds +num % 10
num = num // 10
print(“Digit Sum :”, ds)

Program- Accept a number as input from the user and calculates the average, as long as the
user enters a positive number.
num=0
count=0
sum=0
while num>=0:
num = int(input('enter any number .. -1 to exit: ‘))
if num >= 0:
count = count + 1
sum = sum + num
avg = sum/count
print('Total numbers: ', count, ', Average: ', avg)

Program
Printing the square of numbers using while loop
n=1
while n <= 10:
squareNum = n**2
print(n,squareNum)
n += 1

You might also like