You are on page 1of 24

SNBP INTERNATIONAL SCHOOL & KIDZONE

SENIOR SECONDARY SCHOOL


MORWADI, PIMPRI, PUNE
CBSE AFFILIATION No.:- 1130522
ACADEMIC SESSION 2022-2023
Grade XI
Informatics Practices
Python Programming

Program : An ordered set of instructions or commands to be executed by


a computer is called a program
Languages:
C
 C++
 Java
 Python
Python:
 Python is a very popular and easy to learn programming language,
created by Guido van Rossum in 1991.
 Python is a widely used general-purpose, high level programming
language.
 It was initially designed by Guido van Rossum in 1991 and developed
by Python Software Foundation.
 It was mainly developed for emphasis on code readability, and its
syntax allows programmers to express concepts in fewer lines of
code.
 Python is a programming language that lets you work quickly and in-
tegrate systems more efficiently.
Why to learn Python
 Python is object-oriented
 Dynamically Typed Language
 Python is free (open source)
 Python is Powerful
 Python is Portable
 Python is easy to Read, Use and Learn
 Interpreted Language
 Straight forward syntax

Applications:
 1. To developed AI application
 2. Data science
 3. Machine learning, Deep learning
 4. To developed Desktop application
 5. To developed web application (django,flask)
 6. To developed network application, database application
 7. Games

Features of Python
 Interactive
 Object Oriented
 GUI Programming Support
 Platform Independent
 Easy to code
 High-Level Language

Python code Execution

 Python‟s traditional runtime execution model: Source code you type


is translated to byte code, which is then run by the Python Virtual
Machine (PVM). Your code is automatically compiled, but then it is
interpreted
 To write and run (execute) a Python program, we need to have a Py-
thon interpreter installed on our computer or we can use any online
Python interpreter. The interpreter is also called Python shell.
 the symbol >>> is called Python prompt, which indicates that the in-
terpreter is ready to receive instructions. We can type commands or
statements on this prompt for execution.

Execution Mode:
1. Interactive mode - In the interactive mode, we can type a Python state-
ment on the >>> prompt directly. As soon as we press enter, the inter-
preter executes the statement and displays the result(s),
2. 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. Usually, beginners learn Python in interactive mode, but for pro-
grams having more than a few lines, we should always save the code in
files for future use. Python scripts can be created using any editor.

Identifiers

 An identifier is a name of a program element, and it is user-defined.


There are some rules to follow while choosing an identifier:
 An identifier may only begin with A-Z, a-z, or an underscore (_).
 It can be a combination of letters, digits, and underscores- zero or
more.
 Python is case-sensitive. Name and name are two different identifi-
ers.
 A reserved keyword may not be used as an identifier.
 We can use underscore (_) to separate multiple words in the identi-
fier.
 Identifier cannot start with digits and must not contain any blank
spaces or tabs.
Keyboard
 Python keywords are special reserved words that have specific
meanings and purposes and can‟t be used for anything.
 False class finally is return
 None continue for lambda try
 True def from nonlocal while
 and del global not with
 as elif if or yield
 assert else import pass
break except in raise

Variable
 Variable is an identifier whose value can change. For example varia-
ble age can have different value for different person. Variable name
should be unique in a program.
 We can use an assignment statement to create new variables and
assign specific values to them.
 gender = 'M'
 message = "Keep Smiling"
 price = 987.9
 Variables must always be assigned values before they are used in
the program, otherwise it will lead to an error.

Rules
 Python variables can only begin with a letter(A-Z/a-z) or an under-
score(_).
 The rest of the identifier may contain letters(A-Z/a-z), under-
scores(_), and numbers(0-9).
 A variable cannot begin with a number.
 No special character used except underscore (_).
 Python is case-sensitive, and so are Python identifiers. Name and
name are two different identifiers.
 Reserved words (keywords) cannot be used as identifier names.
 Python variables do not have to explicitly declare to reserve
memory space. The variable is declared automatically when the
value is assigned to it.

Download
 The latest version of Python is available on the official website:
 https://www.python. org/

Syntax: a structure of statements in a computer language.

Algorithm: An algorithm is a step by step method of solving a problem. It


is also used to manipulate data in various ways.

The procedures that a computer follows in order to perform an operation


is called an algorithm. A process or set of rules to be followed in calcula-
tions or other problem-solving operations, especially by a computer, is
called an Algorithm.

Flowchart: A flowchart is a graphical or pictorial representation of an


algorithm using different symbols, shapes and arrows to illustrate the
flow of a program.

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
Int (Integer):
The int data type specifies that the particular object is an integer.
Syntax:
int <variable_name>
For example:
Specifying int a means that the variable ‘a’ can take any whole number or
integer.

Float:
The float data type is different from the integer data type. It can store
whole number values as well as decimals.
Syntax:
float <variable_name>
For example:
Specifying float marks means that the variable marks can store
whole numbers as well as decimal values like 3.4, 7.8, 35.000.
Note:
Python has the special ability to automatically identify the data type
and treat it in the way that data type has to be treated. For example, if
we create a variable ‘val’ and store 5 in it, it will automatically treat ‘val’
as an integer. Later, if we change the value of ‘val’ from 5 to ‘Hello’,
Python will automatically detect this change and then make ‘val’ a
string data type.

Boolean data type (bool) is a subtype of integer. It is a unique data type,


consisting of two constants, True and False. Boolean True value is non-
zero. Boolean False is the value zero.

Sequence

A Python sequence is an ordered collection of items, where each item is


indexed by an integer value. Three types of sequence data types availa-
ble in Python are Strings, Lists and Tuples.
(A) String

String is a group of characters. These characters may be alpha-


bets, digits or special characters including spaces. String values
are enclosed either in single quotation marks

>>> str1 = 'Hello Friend'


>>> str2 = "452"

We cannot perform numerical operations on strings, even when


the string contains a numeric value.
(B) List
List is a sequence of items separated by commas and items are
enclosed in square brackets [ ]. Note that items may be of differ-
ent date types.

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 ( ).

tuple1 = (10, 20, "Apple", 3.4, 'a')

Mapping
Mapping is an unordered data type in Python. Currently, there is
only one standard mapping data type in Python called Dictionary.

(A) Dictionary
Dictionary in Python holds data items in key-value pairs and Items
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.
Keys are usually of string type and their values can be of any data
type. In order to access any value in the dictionary, we have to
specify its key in square brackets [ ].

#create a dictionary
>>> dict1 = {'Fruit':'Apple', 'Climate':'Cold', 'Price(kg)':120}
>>> print(dict1)
{'Fruit': 'Apple', 'Climate': 'Cold', 'Price(kg)': 120}
#getting value by specifying a key
>>> print(dict1['Price(kg)'])
120

Variable declaration

Python variables do not have to explicitly declare to reserve memory


space. The variable is declared automatically when the value is assigned
to it.
This means we do not need to declare the data type of the variable. This
is handled automatically according to the type of value assigned to the
variable. To assign a value to Python variables, you don‟t need to declare
its type.
1. Variable Declaration Syntax: variable=value

Example:
o >> num1=30
o >>num2=45.78
o >>name=‟bright‟
2. Assigning and Reassigning Python Variables
To assign a value to Python variables, you don‟t need to declare its
type.
You name it according to the rules stated above, and type the value af-
ter the equal sign(=).
o >>> age=7
>>> print(age)
o output: >>>7
o >>> age='Dinosaur'
o >>> print(age)
o output: >>> Dinosaur
As shown in above you can assign multiple different type of value to
one variable.
3. Multiple Assignments
You can assign values to multiple Python variables in one statement.
o >>> age,city=21,'Indore'
o >>> print(age,city)
o output: >>>21 Indore
Or you can assign the same value to multiple Python variables

>>> age=fav=7
o >>> print(age,fav)
o output: >>>7 7
This is how you assign values to Python Variables

4.Swapping Variables
Swapping means interchanging values. To swap Python variables, you
don‟t need to do much.
o >>> a,b='red','blue'
o >>> a,b=b,a
o >>> print(a,b)
o output: >>>blue red
o >>>a,b=7,8
o >>>a,b=b,a
o >>>print(a,b)
o output: >>>8 7

Comments
Python Syntax „Comments‟ let you store tags at the right places in the
code. You can use them to explain complex sections of code.
The interpreter ignores comments. Declare a comment using an octo-
thorpe (#).
>>> #This is a comment
Python does not support general multiline comments like Java or C++.
In C++, we have // for single-lined comments, and /* … */ for multiple-
lined comments. Here, we only have single-lined python comment.
To declare a Python comment, use the hash (#).
o >>> #This is a comment

Multiline Python Comment


To have multiline python comment in your code, you must use a hash
at the beginning of every line of your comment in python.
o >>> #Line 1 of comment
o >>> #Line 2 of comment
o >>> #Line 3 of comment
You can also use triple quotes („‟‟ „‟‟ or “”” “””) for this purpose.
o >>> """This comment
o is spanned across
o multiple lines"""
o Output: „This comment\n is spanned across\n multiple lines‟
This gives us an output because we type it in the shell. When you create
a file and write this in that, there is no output.
While triple quotes are generally used for multiline python comment,
we can conveniently use them for python comment as well.

Input and Output in Python


Functions like input() and print() are widely used for standard input and
output operations respectively.
1.6.1 Input() function in Python
We might want to take the input from the user. In Python, we have the
input() function allow us to take input from user.
The input() function always accept values in string format only.
Syntax:
o input([prompt])
Where prompt is the string we wish to display on the screen. It is op-
tional.
o >>> num = input('Enter a number: ')
o Enter a number: 10
o >>> num
o '10'

Here, we can see that the entered value 10 is a string, not a number.
To convert this into a number we can use int() or float() functions.
o >>> int('10')
o 10
o >>> float('10')
o 10.0
Similarly you can covert the input value at the time of input by,
o >>> num = int(input('Enter a number: '))
o Enter a number: 10
o >>> num
o 10

print() function in Python


We use the print() function to output data to the standard output de-
vice (screen).
An example of its use is given below.
o print('This sentence is output to the screen')
o Output
o This sentence is output to the screen
Another example is given below:
oa=5
o print('The value of a is', a)
o Output
o The value of a is 5

What is Python Operator?


Python operator is a symbol that performs an operation on one or more
operands. An operand is a variable or a value on which we perform the
operation.
2.1 Basic Operators
2.1.1 Arithmetic Operators
These Python arithmetic operators include Python operators for basic
mathematical operations.

a. Addition (+) Operator


It adds the values on either side of the operator.
o >>> 3+4
o Output
o7
b. Subtraction (-)
Subtracts the value on the right from the one on the left.
o >>> 3-4
o Output
o -1

c. Multiplication (*)
Multiplies the values on either side of the operator.
o >>> 3*4
o Output
o 12
D. Division (/)
Divides the value on the left by the one on the right. Notice that divi-
sion results in a floating-point value.
o >>> 3/4
o Output
o 0.75

E. Exponentiation (**)
Raises the first number to the power of the second.
o >>> 3**4
o Output
o 81
f. Floor Division (//)
Divides and returns the integer value of the quotient. It dumps the dig-
its after the decimal.
o >>> 4//3
o Output
o1
o >>> 10//3
o Output
o3

g. Modulus (%)
Divides and returns the value of the remainder.
o >>> 3%4

o Output
o3
o >>> 4%3
o Output
o1
o >>> 10%3
o Output
o1
o >>> 10.5%3
o Output
o 1.5

Python Relational Operator

Relational Python Operator carries out the comparison between oper-


ands.
They tell us whether an operand is greater than the other, lesser, equal,
or a combination of those.
a. Less than (<)
This operator checks if the value on the left of the operator is lesser
than the one on the right.
o >>> 3<4
o Output
o True
b. Greater than (>)
It checks if the value on the left of the operator is greater than the one
on the right.
o >>> 3>4
o Output
o False

c. Less than or equal to (<=)


It checks if the value on the left of the operator is lesser than or equal
to the one on the right.
o >>> 7<=7
o Output
o True
d. Greater than or equal to(>=)
It checks if the value on the left of the operator is greater than or equal
to the one on the right.
o >>> 0>=0
o Output
o True
e. Equal to (= =)
This operator checks if the value on the left of the operator is equal to
the one on the right.
1 is equal to the Boolean value True, but 2 isn‟t. Also, 0 is equal to
False.
o >>> 3==3.0
o Output
o True
o >>> 1==True
o Output
o True
o >>> 7==True
o Output
o False
o >>> 0==False
o Output
o True
o >>> 0.5==True
o Output

o False
f. Not equal to (! =)
It checks if the value on the left of the operator is not equal to the one
on the right.
The Python operator <> does the same job, but has been abandoned in
Python 3.
When the condition for a relative operator is fulfilled, it returns true.
Otherwise, it returns False. You can use this return value in a further
statement or expression.
o >>> 1!=1.0
o Output
o False
o >>> -1<>-1.0
o #This causes a syntax error

Python Assignment Operators


Python assignment operator assigns a value to a variable. It may manipu-
late the value by a factor before assigning it.
We have 8 assignment operators- one plain, and seven for the 7 arithme-
tic python operators.
a. Assign (=)
Assigns a value to the expression on the left. Notice that = = is used for
comparing, but = is used for assigning.
o >>> a=7

o >>> print(a)
o Output
o7
b. 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.
o >>> a+=2
o >>> print(a)
o Output
o9
c. Subtract and Assign (-=)

Subtracts the value on the right from the value on the left. Then it as-
signs it to the expression on the left.
o >>> a-=2
o >>> print(a)
o Output
o7
d. Divide and Assign (/=)
Divides the value on the left by the one on the right. Then it assigns it to
the expression on the left.
o >>> a/=7
o >>> print(a)
o Output
o 1.0

e. Multiply and Assign (*=)


Multiplies the values on either side. Then it assigns it to the expression
on the left.
o >>> a*=8
o >>> print(a)
o Output
o 8.0

f. Modulus and Assign (%=)


Performs modulus on the values on either side. Then it assigns it to the
expression on the left.
o >>> a%=3
o >>> print(a)
o Output

o 2.0
g. Exponent and Assign (**=)
Performs exponentiation on the values on either side. Then assigns it to
the expression on the left.
o >>> a**=5
o >>> print(a)
o Output
o 32.0

h. Floor-Divide and Assign (//=)


Performs floor-division on the values on either side. Then assigns it to
the expression on the left.
o >>> a//=3
o >>> print(a)
o Output
o 10.0
2.1.4 Python Logical Operator

a. and Operator in Python


If the conditions on both sides of the operator are true, then the ex-
pression as a whole is true.
o >>> a=7>7 and 2>-1
o >>> print(a)
o Output
o False

b. or Operator in Python
The expression is false only if both the statements around the operator
are false. Otherwise, it is true.
o >>> a=7>7 or 2>-1

o >>> print(a)
o Output
o True
o „and‟ returns the first False value or the last value; „or‟ returns the
first True value or the last value
o >>> 7 and 0 or 5
o Output
o5
c. not Operator in Python
This inverts the Boolean value of an expression. It converts True to
False, and False to True.
As you can see below, the Boolean value for 0 is False. So, not inverts it
to True.
o >>> a=not(0)
o >>> print(a)
o Output
o True

2.1.5 Membership Python Operator: ‘in’, ‘not in’ operators


These operators test whether a value is a member of a sequence. The se-
quence may be a list, a string, or a tuple.
a. in Operator in Python
This checks if a value is a member of a sequence.
In our example, we see that the string „fox‟ does not belong to the list
pets. But the string „cat‟ belongs to it, so it returns True.
Also, the string „me‟ is a substring to the string „disappointment‟.
Therefore, it returns true.
o >>> pets=[„dog‟,‟cat‟,‟ferret‟]
o >>> „fox‟ in pets
o Output

o False
o >>> „cat‟ in pets
o Output
o True
o >>> „me‟ in „disappointment‟
o Output
o True
b. not in Operator in Python
Unlike „in‟, „not in‟ checks if a value is not a member of a sequence.
o >>> „pot‟ not in „disappointment‟
o Output
o True
2.1.6 Python Identity Operator: ‘is’ , ‘is not’

These operators test if the two operands share an identity.


a. is Operator in Python
If two operands have the same identity, it returns true. Otherwise, it re-
turns False. Here, 2 is not the same as 20, so it returns False.
Also, „2‟ and “2” are the same. The difference in quotes does not make
them different. So, it returns True.
o >>> 2 is 20
o Output
o False
o >>> „2‟ is “2”
o Output
o True

You might also like