0% found this document useful (0 votes)
96 views59 pages

Cs - REVISION TOUR

The document discusses various concepts related to Python programming language including learning objectives, modes of working, tokens, data types, variables, operators, comments, and data types. It provides details on interactive and script modes of executing Python code. It also describes various tokens like keywords, identifiers, literals, operators, and delimiters. The different data types in Python including integer, float, complex, boolean, string, list, tuple, sets, none, and dictionaries are explained.

Uploaded by

hemlatageography
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)
96 views59 pages

Cs - REVISION TOUR

The document discusses various concepts related to Python programming language including learning objectives, modes of working, tokens, data types, variables, operators, comments, and data types. It provides details on interactive and script modes of executing Python code. It also describes various tokens like keywords, identifiers, literals, operators, and delimiters. The different data types in Python including integer, float, complex, boolean, string, list, tuple, sets, none, and dictionaries are explained.

Uploaded by

hemlatageography
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/ 59

Learning Objectives :

Students will be able to


understand following
concepts of python

Chapter - 1 1. Modes of working


2. Tokens, keywords,
identifiers, variables,
literals, operators and
punctuators
3. Expression, Comments
4. Data types
5. Mutable & immutable
6. Operator precedence
7. Type Conversion

Python Revision Tour- I


Class XII
Introduction to Python
An ordered set of instructions or commands to be
executed by a computer is called a program.

 The language used to specify those set of instructions


to the computer is called a programming language
for example Python, C, C++, Java, etc.

 Inthis Chapter we will see brief overview of Python


programming language

 Pythonis a very popular and easy to learn


programming language, created by Guido van
Rossum in 1991.
A Python program is called a script.
Script is a sequence of definitions and
commands.
These commands are executed by Python
interpreter known as PYTHON SHELL.

In python programming,
 data types are inbuilt hence support
“dynamic typing”
 declaration of variables is not required.
 memory management is automatically
done.
Features of Python
1. Python is an interpreted, interactive,
directly executed language.

2. It is free open-source software having


large repository of libraries.

3. It is extensible and highly efficient as there


is no wastage of time in declaring variables.
Advantages of Python
1. Platform independent – It can run across different
platforms like windows, Linux, Mac OS and other OS.

2. Easy to use (Readability) – It uses simple, concise


and English like instructions that are easy to read and
understand.

3. High Productivity – It is a simple language with


small codes and extensive libraries. Therefore it offers
higher productivity to programmers as compared to
C++ and java.
Advantages of Python
4. Less learning time– Because of simple and
shorter code, lesser time is required to
understand and learn python.

5. Syntax highlighting – It allows to distinguish


between input, output and error message by
different colour codes.

6. Interpreted language – Code execution &


interpretation line by line.
Two modes to interact with Python

(Python Shell)
(Python Editor)
Execution Modes:
1) Interactive Mode :
we can type a Python statement on the >>>
prompt directly. As soon as we press enter, the
interpreter executes the statement and
displays the result(s)
Working in the 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 and
we have to retype the statements to run them
again.
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.
But for programs 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.
Python has a built-in editor called IDLE (Integrated
Development and Learning Environment )which
can be used to create programs. After opening
the IDLE, we can click File>New File to create a
new file, then write our program on that file and
save it with a desired name. By default, the Python
scripts are saved in the Python installation folder.
Python Character Set
A set of valid characters recognized by python.
• Python uses the traditional ASCII character set.
• The latest version recognizes the Unicode character set.
The ASCII character set is a subset of the Unicode
character set.
Letters: a-z,
A-Z
Digits : 0-9
Special symbols : Special symbol available over keyboard
White spaces: blank space, tab, carriage return,
new line, form feed

Other characters: Unicode


Tokens

Smallest individual unit in a program is


known as token.

1. Keywords
2. Identifiers
3. Literals
4. Operators
5. Delimiters
1. Keywords
Reserved word of the compiler/interpreter which can’t
be used as identifier.
2. Identifiers

A Python identifier is a name


used to identify a variable,
function, class, module or other
object.
Identifier Naming Convention
1. A variable name can contain letter, digits and underscore (_).
No other characters are allowed.

2. A variable name must start with an alphabet or and underscore


(_).

3. A variable name cannot contain spaces.

4. Keyword cannot be used as a variable name.

5. Variable names are case sensitive. Num and num are different.

6. Variable names should be short and meaningful.

Invalid variable names – 3dgraph, roll#no, first name, d.o.b, while


GradePay File_12_2018 JAMES007
GRADEPAY _ismarried _to_update

Grade-Pay 12_2018_File $JAMES007


if RollNo. Roll No
Variables
Variable is an identifier whose value
can change.
 For example variable age can have
different value for different person.
Variable name should be unique in a
program. Value of a variable can be
string (for example,‘b’, ‘Global Citizen’),
number (for example 10,71,80.52) or
any combination of alphanumeric
(alphabets and numbers for example
‘b10’) characters.
In Python, we can use an assignment
statement to create new variables
and assign specific values to them.
gender = 'M'
message = "Keep Smiling"
price = 987.9

Variablesmust always be assigned


values before they are used in the
program, otherwise it will lead to an
error.
3. Literals
Literals in Python can be defined as number,
text, or other data that represent values to be
stored in variables.
Example of String Literals in Python
name = ‘Johni’ , fname=“johny”

Example of Integer Literals in Python(numeric literal)


age = 22

Example of Float Literals in Python(numeric literal)


height = 6.2

Example of Special Literals in Python


name = None
3. Literals
Escape sequence

e.g.
print(“I am a student of \n APS \t Hello ”)
4. Operators
Operators can be defined as symbols that are used to
perform operations on operands.

Types of Operators
a. Arithmetic Operators.
b. Relational Operators.
c. Assignment Operators.
d. Logical Operators.
e. Membership Operators
f. Identity Operators
Operators
a. Arithmetic Operators.
Arithmetic Operators are used to perform arithmetic
operations like addition, multiplication, division etc.
print ("hello"+"python")
print(2+3)
print(10-3)
print(22%5)
print(19//5)
print(2**3)
Output:
hellopython
5
7
2
3
8
Operators
b. Relational Operators.
Relational Operators are used to compare the values.
print(5==3) False
print(7>3) True
print(15<7) False
print(3!=2) True
print(7>=8) False
print(3<=4) True
Operators
c. Assignment Operators.
Used to assign values to the variables.
a=10
print(a)

a+=9
print(a)
Output:
b=11 10
b*=3 19
print(b) 33
9.5
c=19
c/=2 16
print(c)

d=2
d**=4
print(d)
Operators
d. Logical Operators.
Logical Operators are used to perform logical
operations on the given two variables or values.

a=30 a=70
b=20 b=20
if(a==30 and b==20):
print("hello")
if(a==30 or b==20):
Output :- print("hello")
hello
Operators
e. Membership Operators
It is used to validate whether a value is found within a
sequence such as strings, lists, or tuples.

E.g. E.g.
a = 22 a = 22
list = [11, 22,33,44] list = [11, 22,33,44]
ans= a in list ans= a not in list
print(ans) print(ans)
Output: True Output: False
Operators
f. Identity Operators
Identity operators in Python compare the memory
locations of two objects.
5. Delimiters
These are the symbols which can be used as
separator of values or to enclose some values.

e.g ( ) {} [ ] , ; :
Token Category
X Variable

y Variable

z Variable

print Keyword

() Delimiter

/ Operator

68 Literal

“x, y, z” Literal
Comment
 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.
 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.
 Multiline comment can be given using
‘’’ Docstring’’’
Example :- ‘’’ this is program for
find maximum of 2 numbers’’’
Write a Python program to find the area of a
rectangle given that its length is 10 units and
breadth is 20 units.

#To find the area of a rectangle


length = 10
breadth = 20
area = length * breadth
print(area)
Output:
200
Data Type
 Datatype identifies the type of data which a variable
can hold and the operations that can be performed
on those data.

Data types

Numbers Sequences Sets None Mappings

Floating
Integer Complex Strings Dictionaries
Point

Boolean Lists

Tuples
Data Type
a. int (integer): Integer represents whole
numbers. (positive or negative)
e.g. -6, 0, 23466
b. float (floating point numbers): It
represents numbers with decimal
point.
e.g. -43.2, 6.0
c. Complex numbers: It is made up of pair
of real and imaginary number.
e.g. 2+5j
Data Type
Boolean (bool): It represents one of the
two possible values – True or False.

>>> bool_1 = (6>10)


>>> print (bool_1)
False
>>> bool_2 = (6<10)
>>> print (bool_2)
True
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
available in Python are Strings, Lists
and Tuples. A brief introduction to
these data types is as follows:
a) String
b) List
c) Tuple
String
String (str): It is a sequence of
characters. (combination of letters,
numbers and symbols).
It is enclosed within single or double
quotes.
e.g. (‘ ’ or “ ”)

>>> rem= “Hello Welcome to Python”


>>> print (rem)
Hello Welcome to Python
• In Python string is a sequence of characters and each character can be individually
access using index. From beginning the first character in String is at index 0 and last
will be at len-1. From backward direction last character will be at index -1 and first
character will be at –len.
Forward indexing
0 1 2 3 4 5 6
W E L C O M E
-7 -6 -5 -4 -3 -2 -1

Backward indexing
It is possible to change one type of value/
variable to another type. It is known as type
conversion or type casting.

For explicit type casting, we use


functions (constructors):
int ( )
float ( )
str ( )
bool ( )
List
Listis a sequence of items separated
by commas and items are enclosed in
square brackets [ ]. Note that items
may be of different date types.

#To create a list


>>> list1 = [5, 3.4, "New Delhi", "20C", 45]
#print the elements of the list list1
>>> list1
[5, 3.4, 'New Delhi', '20C', 45]
Tuple
 Tuple is a sequence of items separated by
commas and items are enclosed in
parenthesis ( ). This is unlike list, where values
are enclosed in brackets [ ]. Once created,
we cannot change items in the tuple. Similar
to List, items may be of different data types.
#create a tuple tuple1
>>> tuple1 = (10, 20, "Apple", 3.4, 'a')
#print the elements of the tuple tuple1
>>> print(tuple1)
(10, 20, "Apple", 3.4, 'a')
Sets
Sets: Sets is an unordered collection
of values, of any type, with no
duplicate entry. Sets are mutable.

Example:
>>> s = set ([1,2,34])
>>> s
output: {1, 2, 34}
Data Type
None: It is a special data type with
single value.
It is used to signify absence of value
evaluating to false in a situation.

>>> value_1 = None


>>> print (value_1)
None
Mutable and Immutable Data Types
Variables whose values can be
changed after they are created and
assigned are called mutable

1. List
2. Set
3. Dictionary
Immutable type:
Variables whose values can NOT be
changed after they are created and
assigned are called immutable
1. int
2. float
3. decimal
4. complex
5. bool
6. string
7. tuple
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 [ ].
Example of Dictionary
#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
Data Type
type() – if you wish to determine type of
the variable.
e.g.
>>> type(10)
<class ‘int’>
>>> type(8.2)
<class ‘float’>
>>> type(“hello”)
<class ‘str’>
>>> type(True)
<class ‘bool’>
Expressions
Expressions are combination of value(s). i.e.
constant, variable and operators.
Expression Value
5+2*4 13
8+12*2-4 28

Converting mathematical expression to


equivalent Python expression
Algebraic Expression Python Expression
𝑥
y=3( ) y=3*x/2
2
z= 3bc + 4 z = 3*b*c + 4
Precedence of Operators
How will the following expression be
evaluated in Python?
15.0 / 4 + (8 + 3.0)
 Solution:
= 15.0 / 4 + (8.0 + 3.0) #Step 1
= 15.0 / 4.0 + 11.0 #Step 2
= 3.75 + 11.0 #Step 3
= 14.75 #Step 4
Statement
 InPython, 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
Type Conversion
 Asand when required, 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.
Explicit Conversion
 Explicit conversion, also called type casting
happens when data type conversion takes
place because the programmer forced it in
the program. The general form of an explicit
data type conversion is:
(new_data_type) (expression)
 With explicit type conversion, there is a risk
of loss of information since we are forcing an
expression to be of a specific type.
 For example, converting a floating value of
x = 2 0.67 into an integer type, i.e., int(x) will
discard the fractional part .67.
Implicit Conversion

Implicitconversion,
happens when data type
conversion is done
automatically by Python
and is not instructed by the
programmer.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy