Python
Python is high-level language. Python is an open-source, high level, interpreter based language.
computers understand the language of 0s and 1s which is called machine language or low level
language. A program written in a high-level language is called source code.
language translators like compilers and interpreters are needed to translate the source code into
machine language.
Python uses an interpreter to convert its instructions into machine language, so that it can be
understood by the computer.
An interpreter processes the program statements one by one, first translating and then executing
Features of Python :
• Python is a high level language. It is a free and open source language.
• It is an interpreted language, as Python programs are executed by an interpreter.
• Python programs are easy to understand as they have a clearly defined syntax and relatively simple
structure.
• Python is case-sensitive. For example, NUMBER and number are not same in Python.
• Python is portable and platform independent, means it can run on various operating systems and
hardware platforms.
• Python has a rich library of predefined functions.
• Python is also helpful in web development. Many popular web services and applications are built
using Python.
• Python uses indentation for blocks and nested blocks.
Working with Python:
To write and run (execute) a Python program, we need to have a Python interpreter. The interpreter
is also called Python shell. The symbol >>> is the Python prompt, which indicates that the interpreter
is ready to take instructions. We can type commands or statements on this prompt to execute them
using a Python interpreter
Execution Modes :
There are two ways to use the Python interpreter: a) Interactive mode
b) Script mode
A) 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. Interactive
mode is convenient for testing a single line code for instant execution. But in the interactive mode,
we cannot save the statements for future use.
(B) 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 execute a script, we can either:
a) Type the file name along with the path at the prompt. For example, if the name of the file is
prog5—1.py we type prog5-1.py. We can otherwise open the program directly from IDLE .
b) While working in the script mode, after saving the f ile, click [Run]->[Run Module] from the menu.
Python Keywords:
Keywords are reserved words. Each keyword has a specific meaning to the Python interpreter.
IdentIfIers:
In programming language identifiers are names used to identify a variable, function, or other entities
in a program. The rules for naming an identifier in Python are as follows:
• The name should begin with an uppercase or a lowercase alphabet or an underscore sign (_). This
may be followed by any combination of characters a–z, A–Z, 0–9 or underscore (_). Thus, an
identifier cannot start with a digit.
• It can be of any length.
• It should not be a keyword or reserved word
• We cannot use special symbols like !, @, #, $, %, etc., in identifiers.
Ex: avg = (marks1 + marks2 + marks3)/3 (identifiers - marks1, marks2, marks3 and avg)
VarIables
A variable in a program is uniquely identified by a name (identifier). Variable in Python refers to an
object — an item or element that is stored in the memory. Value of a variable can be a string (e.g.,
‘b’, ‘Global Citizen’), numeric (e.g., 345) or any combination of alphanumeric characters (CD67).
we can use an assignment statement to create new variables and assign specific values.
message = "Keep Smiling"
print(message)
Output:
The variable message holds string type valueas (Keep Smiling).
Comments
Comments are used to add a remark or a note in the source code. Comments are not executed by
interpreter. They are added with the purpose of making the source code easier for humans to
understand. They are used primarily to document the meaning and purpose of source code and its
input and output requirements, so that we can remember later how it functions and how to use it.
Ex: Write a Python program to find the sum of two numbers.
#To find the sum of two numbers
num1 = 10
num2 = 20
result = num1 + num2 #calculated sum of two n umber
print(result) # this line print the result
EverythIng Is an object :
Python treats every value or data item whether numeric, string, or other type (discussed in the next
section) as an object. Every object in Python is assigned a unique identity (ID) which remains the
same for the lifetime of that object. The function id() returns the identity of an object.
>>> num1 = 20
>>> id(num1)
1433920576 #Identity of num1
Data types:
Every value belongs to a specific data type in Python. Data type identifies the type of data values a
variable can hold and the operations that can be performed on that data.
Number :
Number data type stores numerical values only.
Boolean data type (bool) is a subtype of integer. It is a unique data type, consisting of two constants,
True and False.
Sequence:
A Python sequence is an ordered collection of items, where each item is indexed by an integer.
a. String :
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 or in double
quotation.
>>> str1 = 'Hello Friend'
>>> str2 = "452"
We cannot perform numerical operations on strings, even when the string contains a
numeric value, as in str2.
b. List:
List is a sequence of items separated by commas and the items are enclosed in square
brackets [ ].
>>> list1 = [5, 3.4, "New Delhi", "20C", 45]
>>> print(list1)
[5, 3.4, 'New Delhi', '20C', 45]
c. Tuple :
Tuple is a sequence of items separated by commas and items are enclosed in parenthesis
().Once created, we cannot change the tuple.
>>> tuple1 = (10, 20, "Apple", 3.4, 'a')
>>> print(tuple1) (10, 20, "Apple", 3.4, 'a')
Set
Set is an unordered collection of items separated by commas and the items are enclosed in curly
brackets { }.it cannot have duplicate entries. Once created, elements of a set cannot be changed.
>>> set1 = {10,20,3.14,"New Delhi"}
>>> print(type(set1))
>>> print(set1)
{10, 20, 3.14, "New Delhi"}
>>> set2 = {1,2,1,3}
>>> print(set2)
{1, 2, 3}
None
None is a special data type with a single value. It is used to signify the absence of value in a situation.
None supports no special operations, and it is neither same as False nor 0 (zero).
>>> myVar = None
>>> print(type(myVar))
>>> print(myVar) None
Mapping
Mapping is an unordered data type in Python.
a.Dictionary
• Dictionary in Python holds data items in key-value pairs. Items in a dictionary are enclosed in
curly brackets { }.
• Dictionaries permit faster access to data. Every key is separated from its value using a colon
(:) sign. The key : value pairs of a dictionary can be accessed using the key.
• The keys are usually strings and their values can be any data type.
• In order to access any value in the dictionary, we have to specify its key in square brackets [ ].
>>> dict1 = {'Fruit':'Apple', 'Climate':'Cold', 'Price(kg)':120}
>>> print(dict1)
{'Fruit': 'Apple', 'Climate': 'Cold', 'Price(kg)': 120}
>>> print(dict1['Price(kg)'])
120
Mutable and Immutable Data Types
Sometimes we may require to change or update the values of certain variables used in a program.
However, for certain data types, Python does not allow us to change the values once a variable of
that type has been created and assigned values.
• Variables whose values can be changed after they are created and assigned are called
mutable.
• Variables whose values cannot be changed after they are created and assigned are called
immutable. When an attempt is made to update the value of an immutable variable, the old
variable is destroyed and a new variable is created by the same name in memory.
Deciding Usage of Python Data Types:
It is preferred to use lists when we need a simple iterable collection of data that may go for frequent
modifications. For example, if we store the names of students of a class in a list, then it is easy to
update the list when some new students join or some leave the course. Tuples are used when we do
not need any change in the data.
Operator
An operator is used to perform specific mathematical or logical operation on values. The values that
the operators work on are called operands. For example, in the expression 10 + num, the value 10,
and the variable num are operands and the + (plus) sign is an operator.
1. Arithmetic Operators
Python supports arithmetic operators that are used to perform the four basic arithmetic operations
as well as modular division, floor division and exponentiation.
2. Relational Operators:
Relational operator compares the values of the operands on its either side and determines
the relationship among them.
Assume the Python variables num1 = 10, num2 = 0, num3 = 10, str1 = "Good", str2 =
"Afternoon" for the following examples
3. Assignment operator
Assignment operator assigns or changes the value of the variable on its left.
4. Logical Operators
There are three logical operators supported by Python. These operators (and, or, not) are to
be written in lower case only. The logical operator evaluates to either True or False based on
the logical operands on either side. Every value is logically either True or False.
5. Identity operators
Identity operators are used to determine whether the value of a variable is of a certain type
or not. Identity operators can also be used to determine whether two variables are referring
to the same object or not.
6. Membership operators
Membership operators are used to check if a value is a member of the given sequence or not.
Expression
An expression is defined as a combination of constants, variables, and operators. An expression
always evaluates to a value. Some examples of valid expressions are given below.
(i) 100 (iv) 3.0 + 3.14
(ii) num (v) 23/3 -5 * 7(14 -2)
(iii) num – 20.4 (vi) "Global" + "Citizen"
Precedence of Operators Evaluation of the expression is based on precedence of operators. When an
expression contains different kinds of operators, precedence determines which operator should be
applied first. Higher precedence operator is evaluated before the lower precedence operator.
Precedence of Operators :
Precedence of Operators Evaluation of the expression is based on precedence of operators. When an
expression contains different kinds of operators, precedence determines which operator should be
applied first.
Ex 1. How will Python evaluate the following expression? (20 + 30) * 40
50 * 40 = 2000
2. How will the following expression be evaluated in Python? 15.0 / 4 + (8 + 3.0)
15.0 / 4 + (8.0 + 3.0)
15.0 / 4.0 + 11.0
3.75 + 11.0
14.75
Statement: In Python, a statement is a unit of code that the Python interpreter can execute.
>>> x = 4 #assignment statement
>>> cube = x ** 3 #assignment statement
>>> print (x, cube) #print statement 4 64
Input and Output
Input: 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 user may enter a number or a string but
the input() function treats them as strings only. Syntax : input ([Prompt])
>>> fname = input("Enter your first name: ")
Enter your first name: Arnab
The variable fname will get the string ‘Arnab’.
>>> age = input("Enter your age: ")
Enter your age: 19
>>> type(age)
<Class ‘str’>
The variable age will get the string ‘19’.
>>> age = int( input("Enter your age:"))
Enter your age: 19
>>> type(age)
<Class ‘int’>
Output: Python uses the print() function to output data to standard output device — the screen. The
print()outputs a complete line and then moves to the next line for subsequent output.
The syntax for print() is: print(value [, ..., sep = ' ', end = '\n'])
• sep: The optional parameter sep is a separator between the output values. We can use a character,
integer or a string as a separator. The default separator is space.
• end: This is also optional and it allows us to specify any string to be appended after the last value.
The default is a new line.
Type Conversion:
We can change the data type of a variable in Python from one type to another. Such data type
conversion can happen in two ways: either explicitly (forced) when the programmer specifies for the
interpreter to convert a data type to another type; or implicitly, when the interpreter understands
such a need by itself and does the type conversion automatically.
1. Explicit Conversion: when data type conversion takes place because the programmer forced
it in the program. Syntax: (new_data_type) (expression)
int(x) Converts x to an integer
float(x) Converts x to a floating-point number
str(x) Converts x to a string representation
chr(x) Converts ASCII value of x to character
ord(x) Returns the character associated with the ASCII code x
Program to show explicit type casting.
priceIcecream = 25
priceBrownie = 45
totalPrice = priceIcecream + priceBrownie
print("The total in Rs." + str(totalPrice))
Output: The total in Rs.70
2. Implicit Conversion: when data type conversion is done automatically by Python and is not
instructed by the programmer.
Program to show implicit conversion from int to float.
num1 = 10 #num1 is an integer
num2 = 20.0 #num2 is a float
sum1 = num1 + num2 #sum1 is sum of a float and an integer
print(sum1)
print(type(sum1))
Output: 30.0
<class ‘float’>
result was automatically converted to a float value stored in variable sum1 without explicitly
telling the interpreter.
Debugging:
A programmer can make mistakes while writing a program, and hence, the program may not
execute or may generate wrong output. The process of identifying and removing such
mistakes, also known as bugs or errors, from a program is called debugging. Errors occurring
in programs can be categorised as:
i) Syntax errors
ii) Logical errors
iii) Runtime errors
Syntax errors: The interpreter interprets the statements only if it is syntactically (as per the
rules of Python) correct. If any syntax error is present, the interpreter shows error
message(s) and stops the execution there.
Ex: parentheses must be in pairs, so the expression (10 + 12) is syntactically correct, whereas
(7 + 11 is not due to absence of right parenthesis. Such errors need to be removed before
the execution of the program.
Logical Errors: 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. The only evidence to the existence of logical errors is the wrong output.
Ex: For example, if we wish to find the average of two numbers 10 and 12 and we write the
code as 10 + 12/2, it would run successfully and produce the result 16. Surely, 16 is not the
average of 10 and 12. The correct code to find the average should have been (10 + 12)/2 to
give the correct output as 11.
Runtime error: 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.
Example of a program which generates runtime error
num1 = 10.0
num2 = int(input("num2 = ")) #if user inputs a string or a zero, it leads to runtime error
print(num1/num2)