Ln. 3 - Brief Overview of Python
Ln. 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
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.
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)
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
Boolean The two data values are TRUE and FALSE, TRUE
represented by 1 or 0.
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)
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.
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.
• 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
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"
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
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
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
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.
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
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”)
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
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.
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
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
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
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-
Output:
5x1=5 5 x 2 = 10 ………………………………….. 5 x 9 = 45 5 x 10 = 50
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