JAWAHAR NAVODAYA VIDYALAYA :: BNAVASI KURNOOL
2.Introduction to Python
Q1:What is Program?
Ans: An ordered set of instructions or commands to be executed by a
computer is called a program
Q2:What is Programming Language?
Ans :The language used to specify set of instructions to the computer is called a
programming language .Example : Python, C, C++, Java, etc.
Q3.What is Python?
Ans:Python is a programming,highlevel,interpreted,portable,free&open source
language, as Python programsare executed by an interpreter.Created by Guido
van Rossum in February,1991.Python got its name from a BBC comedy series
from seventies called ―Monty Pythons Flying Circus‖. It is based on two
programming languages called ABC and Modula–3.
Q4: What are the Advantages of Python?
1.Easy to Use: Python is compact and very easy to use with very simple syntax
rules. It is programmer–friendly
2.Expressive Language: Because of simple syntax and fewer lines of code, it is
more capable to express code's purpose than many other languages
3.Interpreted Language: Python interprets and executes the code line by line at a
time. It makes Python an easy–to–debug language and thus suitable for beginners
and advanced users.programs written in Python are easily readable and
understandable
4.Completeness: Python Standard Library provides various modules for different
functionalities.
5.Cross–Platform Language: Python can run on different platforms like Windows,
Linux / Unix, Macintosh, Super Computers, Smart Phones etc. Hence it portable
language
6.Free and Open Source: Python is freely available at free of cost and its source
code is available to every body for further improvement
7.Variety of Usage: Python can be used for a variety of applications like Software
development, Scripting, Web Applications, ,Game development, System
Administration, Rapid Prototyping, GUI Programs, Database Applications etc.,
scientific computing, big data and Artificial Intelligence.
8.Case Sensitive:It is case sensitive. i.e. Uppercase and Lowercase alphabets are
different
3.1.1 Working with Python
To write and run Python program, install Python interpreter in computer. IDLE
(GUI integrated) is the standard, most popular Python development environment.
Python shell(interpreter) can be used in 2 ways(i)Interactive Mode
(ii) Script Mode
Other offline IDE’s are: 1.PyCharm, 2.Visual Studio Code, 3.Jupyter 4.Spyder 5.Thonny
6.Sublime Text,7.Atom 8.IDLE 9.Wing IDE 10. Anaconda Navigator
Other online IDE’s are: 1.Replit 2.Google Colab, 3. Jupyter Notebook (Binder)
4.Programiz 5. PythonAnywhere 6. OnlineGDB
7.Trinket,8.JDoodle 9.Pythontutor 10 .OneCompiler
(i)Interactive Mode:As the name suggests, this mode allows to interact
with OS. This mode does not save commands in form of a program. The
symbol '>>>' is called Python prompt, indicates that interpreter is ready to
accept command.
(ii) Script Mode:In the script mode, we can write a Python program in a
file, save it and then use the interpreter to execute the program from the
file. Such program files have a .py extension and they are also known as
scripts.
Basic Structure Of Python Program:
1.Comments:These are the statements that will be ignored by Python
interpreter .A single line comment starts with the symbol #. For multiline
comment content will be enclosed in triple quotes (" " ") or triple apostrophe (' ' ').
2.Functions: A function is a code that has collection of statements to do some
task. It has a name and a function can be executed repeatedly as many times
required
def wish(name): def def rip(name):
print("HAPPY BIRTH DAY Mr.", name) print("REST IN PEACE Late",name)
wish("Syed Rafiq") rip("Syed Rafiq")
3.Statement:A statement is a programming instruction that does something i.e.
performs some action.
Ex:x = 15
y =x – 2 * 4
z = x + z – 10
if (x > y):
4.Expression:An expression in Python is a combination of literals, operators and
operands that is evaluated to produce some other values
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"
5 Indentation:Python uses indentation for block as well as for nested block
structures. Leading whitespace (spaces and tabs) at the beginning of a statement
is called indentation.
A block is a piece of Python program text that is executed as a unit.
PYTHON CHARACTER SET:
Python character set represents the set of valid characters that Python supports. It has the
following character set
Letters A–Z, a–z
Digits 0–9
Special Space + – * / ** \ { } ( ) // = != == < , > . ' ' " " ; : % ! & # <= >=
Symbols @ _ (underscore)
Whitespace Blank Space, Escape characters( Newline \n ,Tab \t, Carriage
Return \r, , Form feed\f)
Other Python can process all ASCII(American Standard code for
Characters Information Interchange) and Unicode characters as part of data
or literals
3.2.Keywords or Reserved Words:Each keyword in python has a specific meaning
to the Python interpreter.keywords cannot be used as identifiers, variables &
functions and Python has the 33 keywords. Except ―False‖, ―None‖, and ―True‖
all the keywords are in lowercase.
To get the updated keywords list type below program
import keyword
list=keyword.kwlist
print(len(list))
for i in list:
print(i)
3.3.Identifiers: In Python programming language, identifiers are names
used to identify a variable, function, or other entities in a program.
The 4 rules for naming an identifier in Python are as follows:
1.Name should begin with uppercase (A-Z) or lowercase (a-z) or underscore sign (_).
2.It can be of any length (it is preferred tokeep it short and meaningful)
3.An identifier cannot start with a digit & It should not be a keyword
4.We cannot use special symbols like !, @, #, $, %, etc.in identifiers
Valid Identifiers Invalid Identifiers Remarks
_marks !marks No Special Character
Myfile My file No Space
syed_rafiq syed-rafiq Hyphen given
name 1name Can’t start with digit
true True Reserve words can’t use
Variables:A variable is an identifier whose value can change during program
execution.In Python, we can use an assignment operator(=) to create new
variables and assign specific values to them.
Ex: gender = 'M' , message = "Keep Smiling" , age=30
Multiple Assignments: Different ways of assignments are
1. Assigning same value to multiple variables
Ex: a = b = c = 18
2. Assigning multiple values to multiple variables
Ex1: x, y, z = 10, 20, 30 # Means x=10, y=20, z=30
Ex2: x,y = y,x # This makes x=20, y = 10
Ex3: a, b, c = 5, 10, 7
a, b, c = a+1, b+2, c–1
print (a, b, c) # a=6, b=12, c=6
Displaying type of variable: The type( ) can be used to display the data type of
a variable.
>>> a=10 >>> a=20.5 >>> a="Python" >>>a=True
>>> type(a) >>> type(a) >>> type(a) >>>type(a)
<class 'int'> <class 'float'> <class 'str'> >>><class ‗bool‘>
id of an object: The id of an object is the memory location of it. The function
id( ) is used for this purpose Ex:
Constant: A constant is a value that should not change during the execution of
the program
Eg:PI= 3.14; gravity=9.8
Input() And Output() functions In Python:
Input:-In Python, we have the input() function for taking values entered by input device such as a
keyboard. The input() function prompts user to enter data.
Syntax for input() is: variable = input([Prompt]) Eg:>>> name = input("Enter your name: ")
Print():Python uses the print() function to output data to standard output device — the screen.
The function print() evaluates the expression before displaying it on the screen
Syntax for print() is: print(value) Eg:>>>print("Hello")
Data Types in Python:
MUTABLE AND IMMUTABLE DATA TYPES:
Mutable Types: The mutable types are those that can change their value in place. Lists, Sets and Dictionaries and
are mutable types
Immutable Types: The immutable types are those that cannot change their value in place. Integers, Float, Booleans,
Complex,Strings and Tuples are immutable types
(a)Sequences:- Sequence: is an ordered collection of items, where each item is indexed by an
integer value. Python provides THREE sequence data types like Strings, Lists, Tuples, and mapping
data type Dictionaries
(a)Strings: String is a group of characters, Every character in a string has an index ,and Every
character has two indexes Forward Indexing(0,1,2,3…) to and Backward Indexing(-1,-2,-3,…)
Index 0 1 2 3 4 5
String P Y T H O N
Index –6 –5 –4 –3 –2 –1
Ex:
(b)Tuples: Tuples are a sequence of values of any data type, and are indexed by integers.
They are immutable (we cannot modify). Tuples are enclosed in parentheses () separated by
commas(,). Example: t=(1,2.3,’jnv’)
Single Element tuple: To construct a tuple with one element add comma (,) after single element
Ex: t=(1,)
Nested tuple: If a tuple contains an element , which is a tuple itself
Eg:t=(1,2,(3,4,5),6,7), t4=((101,'phy',),(102,'eng'),(3,'ip'))
(c)Sets: A set is an unordered collection of unique elements with no duplicate entry. Sets not
allowed indexing and slicing, they are mutable (changeable). Sets are enclosed in curly brackets { }.
Example: s={1,2.3,'jnv'}, s=set([1,2.3,'jnv']),
Eg:s1={10,True,'Rafiq',1.43,1}Duplicate items not allowed
Adding Element in set Removing Element in set Sets allow immutable Sets not allowed mutable
>>> s={10,20,30} >>> s={10,20,30,40} se={1,2,3,(10.20,30)} se={1,2,3,[10.20,30]}
>>> print(s) >>> print(s) se={1,2,3,{1:1,2:2,3:3}}
{10, 20, 30} {10, 20, 30,40} Empty set se={1,2,3,{10,20,30}}
>>> s.add(40) >>> s.remove(40) a=set()
>>> s >>> s Update set
{40, 10, 20, 30} {10, 20, 30} s.update([50,60,70])
d)Lists: List is a sequence of values of any type. Values in the list are called elements / items.
They are mutable and indexed/ordered. List is enclosed in square brackets [].
Example: l = *1, 2.3,’jnv’+
Mapping:-Mapping is an unordered data type in Python. Currently, there is only one standard
mapping data type in Python called Dictionary.
Dictionary: Dictionary is an unordered data type in Python holds data items in key-value pairs,
They are mutable. Dictionaries are enclosed in curly brackets { }
Ex: d={"Name" : "Teja", "Age":16,"Group":"MPC","Fees":20000,"School":"JNV"}
Operators:An operator is a symbol that is used in a program in respect of some
operation. Each programming language will have its own set of operators.
The constants or variables that participate in the operation are called
operands
Unary Operator: If an operator takes only one operand Ex:5
Binary Operator: If an operator takes two operands Ex: 1+3=4
Python Operators: Python supports 5 kinds of operators.
1. Arithmetic Operators: Python supports arithmetic operators to perform the four basic
arithmetic operations (+ - *), /True division (In true division the result of dividing two
integers is a float) , floor or integer division(In floor division the result of dividing two integers
is a integer) value gives (//)Quotient, modulus division(%)Remainder, and exponentiation
(**)Power(^)
2.Assignment Operators: In Python, assign values to variables. There are 7 ASo’s in Python
3.Relatonal or Comparison Operators: in Python are used to compare two values and return a
Boolean result (True or False).There are 6 RO’s in Python 1.Greater than(>) 2.Greater Than or Equal
To(>=),3. Less Than(<),4. Lesser Than or Equal To(<=),5. Equal To(==),6. Not Equal To(! =)
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 its either side.
1.and: and operator is used by applying(.-->dot) between two variables, it is just like
multiplication. If both operands are True, then condition becomes True
2.or : or operator is used by applying(+-->plus) between two variables, it is just like addition.
If any of the two operands are True, then condition becomes True
3.Not: Used to reverse the logical state of its operand.It returns True if the conditional expression
returns False, and vice-versa. #WAPP by using LO operators
Membership Operators : is used to check if a value is a member of the given sequence
or not. There are two membership operators in python in and not in.
1. in Operator: Returns True if the variable or value is found in the specified sequence
and False otherwise.
2. Not in: Returns True if the variable/value is not found in the specified sequence
and False otherwise
Debugging:The process of identifying and removing errors is called
debugging. Python supports three types of errors
1. Syntax Error 2.Logical Error 3.Runtime Error
1.Syntax Error: In Python, a syntax error occurs when the interpreter
encounters code that doesn't conform to the language's grammar rules.
Ex: 1.print(‗Helo‖), Ex: 2.print(―Hello, 3.a=10
b=5
if(a<b)
print(x)
2.Logical Error:logical error/bug (called semantic error) does not stop
execution but the program behaves incorrectly and produces undesired
/wrong output
Ex:if we wish to find the average of two numbers 10 and 12
>>>int(10+12/2)
16
>>>
>>>int(10+12)/2
11.0
Ex: Suppose if u want to add 2 numbers and type below code like this
a=input("enter number1")
b=input("Enter number2")
c=a+b
print('add',c)
it will give output like this
12
To add 2 numbers use correct logical code
a=int(input("enter number1"))
b=int(input("Enter number2"))
c=a+b
print('add',c)
3. Runtime Error:A runtime error causes abnormal termination of program
while it is executing. Runtime error is when the statement is correct
syntactically, but the interpreter cannot execute it.
Ex:-For example, we have a statement having division operation in the
program. By mistake, if the denominator value is zero then it will give a
runtime error like ―division by zero‖.
Ex1.:13/0 (ZeroDivisionError:)
Ex:2
>>>str = "Hello"
>>> print(str + 5) (TypeError)
Ex 3:int(‗bc‘) (Value Error)
Ex 4: c=[1,2,3,4]
print(c[4])(Index Error)
Precedence of Operators: When an expression contains more than one
operator, their precedence (order or hierarchy) determines which operator should
be applied first. Higher precedence operator is evaluated before the lower
precedence operator.
Operator Associativity: Almost all the operators have left to right associativity
except exponent operator (**) which has right to left associativity.
In Python, PEMDAS is the rule that defines the order of operations when
evaluating mathematical expressions.
PEMDAS stands for:
P → Parentheses () – operations inside parentheses are done first
E → Exponents ** – powers and roots
M → Multiplication *
D → Division / // %
A → Addition +
S → Subtraction -
⚡ Multiplication, Division, Floor Division, and Modulus have the same
precedence and are evaluated from left to right. Similarly, Addition and
Subtraction are also evaluated left to right.
# Example 1 : print(10 + 2 * 3) [# Multiplication first → 10 + (2*3) = 16]
# Example 2:- print((10 + 2) * 3) [# Parentheses first → (12) * 3 = 36]
# Example 3 print(2 ** 3 * 2) [# Exponent first → (2**3) * 2 = 8 * 2 = 16]
# Example 4 print(20 / 5 * 2) Division and Multiplication same precedence
→ (20/5) * 2 = 4 * 2 = 8.0
# Example 5 print(15 - 3 + 2)
# Subtraction and Addition left-to-right → (15-3)+2 = 12+2 = 14
Ex7(a) Ex7(b) Ex:8(a) Ex:8(b)
7/2*6%4 7//2*6%4 2**4**2 (Right to left) 2**3**2
3.5*6%4 3*6%4 42=16 32=9
21%4 18%4 216=65536 29=512
1 2
Flow of Control: The order of execution of the statements in a program is
known as flow of control. The flow of control can be implemented using
control structures.
Python has three types of control structures—Sequence, Selection,
Iteration (repetition).
1.Sequence: are a set of statements whose execution process happens in a
sequence.
Ex:a=20
b=10
c=a-b
print(“Subtraction is”,c)
2. Selection/Decision/Conditional: The selection statement allows a program to test
several conditions and execute instructions based on which condition is true.
Some decision control statements are:
If: if only has one condition to check.
if-else: The if-else statement evaluates the condition and will execute
the body of if if the test condition is True, but if the condition is False,
then the body of else is executed.
if-elif-else: if-elif-else statement is used to conditionally execute a
statement or a block of statements.
#WAPP using if condition
#WAPP using if else ,elif condition
3.Repitition/Iteration/Looping statement: is used to repeat a
group(block) of programming instructions. Sometimes we need to
repeat certain things for a particular number of times
In Python, we generally have two loops/repetitive statements:
for loop
while loop
(a)for loop: The for statement is used to iterate over a range of values
or a sequence. The loop is executed for each item in the range
Syntax: for <control-variable> in <sequence/items in range>:
<statements inside body of the loop>
WAPP by using for condition
WAPP by using for condition
Ex 3:
while loop: The while statement executes a block of code
repeatedly as long as the control condition of the loop is true. The
control condition of the while loop is executed before any
statement inside the loop is executed
Ex:1E
Ex:2
The range() Function: is a built-in function in Python. It is used to create
a list containing a sequence of integers from the given start value upto stop
value.
The function range() is often used in for loops for generating a sequence of
numbers
Ex2: