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

1 Python Revision Tour 1 1

The document provides an overview of Python, including its history, capabilities, advantages, and limitations. It covers fundamental concepts such as tokens, keywords, identifiers, literals, operators, expressions, and data types, along with examples and possible questions for each topic. Additionally, it discusses control flow statements, including if statements and their variations, to illustrate decision-making in Python programming.

Uploaded by

Kalaanth Kawin
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)
1 views59 pages

1 Python Revision Tour 1 1

The document provides an overview of Python, including its history, capabilities, advantages, and limitations. It covers fundamental concepts such as tokens, keywords, identifiers, literals, operators, expressions, and data types, along with examples and possible questions for each topic. Additionally, it discusses control flow statements, including if statements and their variations, to illustrate decision-making in Python programming.

Uploaded by

Kalaanth Kawin
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

COMPUTER SCIENCE

PYTHON REVISION TOUR - I


PYTHON REVISION TOUR- I
INTRODUCTION TO PYTHON
Python was created by Guido Van Rossum
The language was released in February I991
Python got its name from a BBC comedy series from
seventies- “Monty Python’s Flying Circus”
Python can be used to follow both Procedural approach and
Object Oriented approach of programming
It is free to use
Python is based on or influenced with two programming
languages:
ABC language [replacement of BASIC]
Modula-3
WHAT CAN PYTHON DO?
 Python can be used on a server to create web applications.
 Python can be used alongside software to create workflows.
 Python can connect to database systems. It can also read and
modify files.
 Python can be used to handle big data and perform complex
mathematics.
 Python can be used for rapid prototyping, or for production-
ready software development.
WHY PYTHON?

 Works on different platforms (Windows, Mac, Linux,


Raspberry Pi, etc.)
 Has a simple syntax similar to the English language.
 Has syntax that allows developers to write programs with
fewer lines than some other programming languages.
 Runs on an interpreter system, meaning that code can be
executed as soon as it is written.
 Can be treated in a procedural way, an object-oriented way
or a functional way.
ADVANTAGES
Easy to use Object oriented language

Expressive language
Interpreted Language
Its completeness
Cross-platform Language
Free and Open source

Variety of Usage / Applications


LIMITATIONS OF PYTHON

Not the fastest language


Lesser Libraries than C, Java, Perl
Not Strong on Type-binding
Not Easily convertible
TOKENS
The smallest individual unit in a program is known as Token or
Lexical unit. Python has following tokens:

Keywords
Identifiers (Names)
Literals
Operators and
Punctuators
1) The smallest individual unit in a program is known
as ______
1) A token is also called as _________
2) There are _____ types of tokens.
3) List the types of tokens.
Example:

if a > 10 :
KEYWORDS

Keywords are predefined words with special


meaning to language compiler or interpreter.

These are reserved for special purpose and


must not be used as identifier names.
KEYWORDS
Value Keywords : True, False, None
Operator Keywords : and, or, not, in, is
Control Flow Keywords : if, elif, else
Iteration Keywords : for, while, break, continue, else
Structure Keywords : def, class, with, as, pass, lambda
Returning Keywords : return, yield
Import Keywords : import, from, as
Other keywords : assert, del, global, nonlocal, raise, except,
finally, try
POSSIBLE QUESTIONS – BASED ON THE CONCEPT
KEYWORDS

1) Which of the following is not a keyword?


a) eval b) assert c) nonlocal d) pass
2) Say true or false:
Keyword are predefined in the language compiler or
interpreter.
3) Identify a valid keyword.
a) Pass b) True c) false d) If
IDENTIFIERS
 are the name given to different parts of the program.
(variables, objects, classes, functions, lists, dictionaries and
so forth)
Rules :
 Must be made up of only letters, numbers and
underscore
 Cannot begin with a number
 Cannot have spaces in between the identifier
 Keywords cannot be used as identifiers
POSSIBLE QUESTIONS – BASED ON THE CONCEPT
IDENTIFIERS

1) Which of the following is an invalid variable?


a) _name b) mark1 c) city-name d) Prod_1
2) Identify valid variable name.
a) for b) 1stmark c) name,mark d) Address
3) State true or false:
 Keywords can be used as identifiers.
 Variable name can contain spaces
 Variable name cannot begin with a number
LITERALS / VALUES
 Are data items that have fixed or constant value.
 The several kinds of literals are
 String literal
 Single line strings
s = “Hello Welcome to class XII”
 Multiline strings
s = “Hello \
Welcome to class XII”

s = ‘ ‘ ‘ Hello
Welcome to class XII ’ ’ ’
CHARACTERS

GRAPHIC NON GRAPHIC

Carriage Return -- ( \ r )
Horizontal Tab – ( \ t )
Character with 16 bit Hex value ( \ uxxxx)
Character with 32 bit Hex value ( \Uxxxxxxxx)
ASCII Vertical Tab – (\v)
Character with Octal Value – (\ooo)
Character with Hex Value – (\xhh)
New line character – ( \n)
 Numeric literal
 Integer literals
 Decimal form – will begin with digits 1-9
e.g. 1234, 4100
 Octal form – an integer beginning with 0o(zero followed
by letter o) - e.g. 0o35, 0o77
Note: remember that for Octal, 8 and 9 are invalid digits
 Hexadecimal form – an integer beginning with 0x(zero
followed by x) - e.g. 0x73, 0xAF
Note: remember that valid digits/letters for hexadecimal
numbers are 0-9 and A-F
 Floating point literals or real literal floats – are written with
decimal point dividing the integer and fractional parts are
numbers having fractional parts. e.g. 0.17E5, 3.E2, .6E4
 Complex number literals – are of the form a + bj where a and
b are floats and j(or J) represents −1 (which is an imaginary
number)
 Boolean literal
 True
 False
 Special literal
 None
OPERATORS
Types of operators:
 Arithmetic operators  +, -, *, /, //, %, **
 Relational operators  >, <, >=, <=, = =, !=
 Logical operators  and, or, not
 Assignment operator  =
 Bitwise operator  &, ^, |
 Shift operator  <<, >>
 Identity operators  is, is not
 Membership operators  in, not in
 Arithmetic assignment operator  /=, +=, -=, *=, %=, **=,
//=
EXPRESSIONS
An expression in Python is any valid combination of
operators, literals and variables.

TYPES OF EXPRESSIONS:
 Arithmetic expression
 Relational expression
 Logical expression
OPERATORS THEIR ASSOCIATIVITY & PRECEDENCE
Highest
OPERATOR DESCRIPTION ASSOCIATIVITY

() Parentheses LEFT  RIGHT

** Exponentiation RIGHT  LEFT

~x Bitwise nor LEFT  RIGHT

+x, -x Positive, negative(unary +, - ) LEFT  RIGHT

Multiplication, division, floor


*, /, //, % LEFT  RIGHT
division, Modulus
+, - Addition, Subtraction LEFT  RIGHT

& Bitwise AND LEFT  RIGHT

| Bitwise OR LEFT  RIGHT

<, <=, >, >=, !=, Comparisons(relational


LEFT  RIGHT
= =, is, is not operators), identity operators
not x Boolean NOT LEFT  RIGHT

and Boolean AND LEFT  RIGHT

or Boolean OR LEFT  RIGHT Lowest


EVALUATING ARITHMETIC EXPRESSION
1) 17%20 1) 17%20 = 17

2) 12*(3%4)//2+6 2) 12*(3%4)//2+6 = 24

3) 2 ** 3 ** 2 3) 2 ** 3 ** 2 = 512

4) 7 // 5 + 8 * 2 / 4 – 3 4) 7 // 5 + 8 * 2 / 4 – 3 = 2.0

5) 8 * 3 + 2**3 // 9 – 4 5) 8 * 3 + 2**3 // 9 – 4 = 20

LINK
PUNCTUATORS

Are symbols that are used in programming languages to

organize sentence structures and indicate the rhythm and

emphasis of expressions, statements and program structure.

‘ “ # \ ( ) [ ] { } @ , : . =
DYNAMIC TYPING VS STATIC TYPING

Static Typing : a data type is attached with a variable when it


is defined first and it is fixed and cannot be
changed.

Dynamic Typing : Python supports dynamic typing.


Dynamic typing allows greater flexibility,
easier to write. (for example, no
declaration statements)
MULTIPLE ASSIGNMENTS
Assigning same value to multiple variables :
A = B = C = 10

Assigning multiple values to multiple variables:


A, B, C = 10, 20, 30

To swap values of the variables:


A, B = B, A
X,Y,Z=10,20,30
Z,Y,X = X+1, Z+10, Y-10
PRINT(X,Y,Z)  The output will be 10 40 11
x, x=100,200
y, y=x+100,x+200
print(x, y)  The output will be 200 400
INPUT & OUTPUT STATEMENTS
input() – built-in function used to accept values from the user.
It always returns a value of STRING type.

SYNTAX: variable = input(<prompt to be displayed>)


EXAMPLE: name = input(‘ Enter your name : ’)
To convert the values received through input() into
int and float:
variable = int(input(<prompt to be displayed>) (or)
variable = float(input(<prompt to be displayed>)
INPUT & OUTPUT STATEMENTS
output( ) – built-in function used to display values on the screen

SYNTAX: print(*objects,[sep=‘’ or<separator string>


end =‘\n’ or <end-string>])
EXAMPLE:
print(‘ Hello! How are you?’)
Will be displayed as: Hello! How are you?

print(‘hello’,’welcome’,’to’,’Alpha’,sep=‘#’)
Will be displayed as: hello#welcome#to#Alpha
print(‘ Hello!)
print(“How are you?’)
Will be displayed as: Hello!
How are you?

print(‘hello’,’welcome’,’to’,’Alpha’,sep=‘#’)
Will be displayed as: hello#welcome#to#Alpha

print(“My name is Varun”, end=‘@’)


print(‘I am 16 year old’)
Will be displayed as: My name is Varun@
I am 16 years old
CORE DATA TYPES
 Numbers
 Integers
• Boolean
 Floating point numbers
 Complex numbers
 Sequences
 Strings – sequence of pure Unicode characters enclosed within
single or double quotes
 List – values of any datatype enclosed within square brackets
 Tuples – values of any data type enclosed within parentheses
 Mappings
 Dictionary – is an unordered set of key : value pairs enclosed within
curly brackets.
MUTABLE AND IMMUTABLE DATA TYPES
Python data object can be broadly categorized into two types –
mutable and immutable types.

Immutable types: are those that can never change their value in
place. In python following types are immutable: integers, float,
Boolean, strings, tuples.
Mutable types: are those that can change their value in place.
In python the following are mutable types: Lists, Dictionaries,
Sets.
VARIABLE INTERNALS
Python is an object oriented language.
So every thing in python is an object.
An object is any identifiable entity that have some
characteristics/properties and behavior.
Every python object has three key attributes associated with it:
1. type of object
2. value of an object
3. id of an object
Type of an object determines the operations that can be
performed on the object.

Built – in function type() returns the type of an object.

Example:
>>> a=100
>>> type(a)  returns <class ‘int’>
>>> type(100)  returns <class ‘int’>
>>> name="Jaques"
>>> type(name)  returns <class ‘str’>
TYPE CASTING
The explicit type conversion is also known as Type Casting.
An explicit type conversion is user-defined conversion that
forces an expression to be of specific type.

SYNTAX :
data type_to_convert(expression)
For example:
str = “100” # String type
num = int(str) # will convert the string to integer type
MATH LIBRARY FUNCTIONS
import math # to include math library
Important functions:
ceil(), sqrt(), exp(),
fabs(), floor(), log(),
log10(), pow(), sin(),
cos(), tan()
TYPES OF STATEMENT IN PYTHON
Statements are the instructions given to computer to perform
any task.
Task may be simple calculation, checking the condition or
repeating action.
Python supports 3 types of statement:
1) Empty statement
2) Simple statement
3) Compound statement
EMPTY STATEMENT

It is the simplest statement i.e. a statement which does


nothing.
It is written by using keyword – pass

Whenever python encountered pass it does nothing and moves


to next statement in flow of control.
.
SIMPLE STATEMENT

Any single executable statement in Python is simple


statement.

EXAMPLE:

Name = input(“enter your name “)


print(name)
.
COMPOUND STATEMENT
It represent group of statement executed as unit.
The compound statement of python are written in a
specific pattern:
Compound_Statement_Header :
indented_body containing multiple simple
or compound statement
Compound Statement has:
 Header which begins with keyword/function and
ends with colon(:)
 A body contains of one or more python statements each
indented inside the header line.
 All statement in the body or under any header must be at
the same level of indentation
STATEMENT FLOW CONTROL
In python program statement may execute in a sequence,
selectively or iteratively.
Python programming support 3 Control Flow statements:
1. Sequence
2. Selection
3. Iteration
SELECTION STATEMENTS
IF STATEMENT OF PYTHON:
If - statement of python is used to execute statements based
on condition.
It tests the condition and if the condition is true it perform
certain action, we can also provide action for false situation.
if statement in Python is of many forms:
 if without false statement
 if with else
 if with elif
 Nested if
SIMPLE if
In the simplest form if statement in Python checks the
condition and execute the statement if the condition is true
and do nothing if the condition is false.
SYNTAX:
if <condition> :
Statement1
Statements ….
if statement is compound statement having header and a body
containing intended statement.All statement belonging to if
must have same indentation level
EXAMPLE:
Input monthly sale of employee and give bonus of 10% if sale
is more than 50000 otherwise bonus will be 0

bonus = 0
sale = int(input("Enter Monthly Sales :"))
if sale>50000:
bonus=sale * 10 /100
print("Bonus = " , bonus)
if with else:
if with else is used to test the condition. If the condition is
True it perform certain action and alternate course of action if
the condition is false.
Syntax:
if <condition>:
Statements
else:
Statements
EXAMPLE:

Input Age of person and print whether the person is eligible


for voting or not.
age = int(input("Enter your age "))
if age>=18:
print("Congratulation! you are eligible for voting ")
else:
print("Sorry! You are not eligible for voting")
if with elif
if with elif is used where multiple chain of condition is to be checked.
Each elif must be followed by condition and then statement for it. After
every elif we can give else which will be executed if all the condition
evaluates to false
Syntax:
if condition:
Statements
elif condition:
Statements
elif condition:
Statements
else:
statements
EXAMPLE:
Input temperature of water and print its physical state.
temp = int(input("Enter temperature of water "))
if temp>100:
print("Gaseous State")
elif temp < 0
print(“Solid State”)
else:
print(“Liquid State”)
Nested if:
In this type of “if” we put if within another if as a statement of it. Mostly
used in a situation where we want different else for each condition.
Syntax:
if condition1:
if condition2:
statements
else:
statements
elif condition3:
statements
else:
statements
STORING CONDITION:
Sometimes the conditions being used are repetitive. In
such cases we can store conditions in a name and then
use that named conditional in the if statements.
EXAMPLE:
all = a = = 1 and b = = 2 and c = = 3
if all:
print(“Condition fulfilled”)
else:
print(“Condition not fulfilled”)
PYTHON LOOP STATEMENTS
To carry out repetition of statements Python provide 2 loop
statements

1) Conditional loop (while)

2) Counting loop (for)


for - loop
 for loop in python is used to create a loop to process items of any
sequence like List, Tuple, Dictionary, String

 It can also be used to create loop of fixed number of steps like 5


times, 10 times, n times etc. using range() function.
range() function
can be used in for loop to repeat the statement(s) n number of times.
Syntax:
 range(lower_limit, upper_limit)
 The range function generate set of values from lower_limit to
upper_limit-1 EXAMPLE:
 range(1,10)  will generate set of values from 1-9
 range(0,7)  will generate [0-6] default step value
will be +1 range(1,10)  will generate
(1,2,3,4,5,6,7,8,9)
Example – for loop with List
School=["Principal", "PGT", "TGT", "PRT"]
for sm in School:
print(sm)

Example – for loop with Tuple


Code=(10,20,30,40,50,60)
for cd in Code:
print(cd)

Example – for loop with string


for ch in ‘Plan’:
print(ch)
while LOOP
 While loop in python is conditional loop which repeat the instruction as long
as condition remains true.
 It is entry-controlled loop i.e. it first check the condition and if it is true then
allows to enter in loop.

 while loop contains various loop elements:


 initialization
 test condition
 body of loop and
 update statement
while LOOP STATEMENTS
1. Initialization : it is used to give starting value in a loop variable from where
to start the loop
2. Test condition : it is the condition or last value up to which loop will be
executed.
3. Body of loop : it specifies the action/statement to repeat in the loop
4. Update statement : it is the increase or decrease in loop variable to reach the
test condition.
Example of simple while loop
i=1
while i<=10:
print(i)
i+=1
JUMP STATEMENTS

1) break
2) continue
1) break statement in python is used to terminate the containing loop for any
given condition.
2) Program resumes from the statement immediately after the loop. Continue
statement in python is used to skip the statements below continue
statement inside loop and forces the loop to continue with next value.
Example – break
for i in range(1,20):
if i % 6 == 0:
break
print(i)
print(“Loop Over”)
The above code produces the following output
12345
Loop Over
Example – continue
for i in range(1,20):
if i % 6 == 0:
continue
print(i, end = ‘ ‘)
print(‘Loop Over’)
The above code produces output
1 2 3 4 5 7 8 9 10 11 13 14 15 16 17 19
Loop Over
when the value of i becomes divisible from 6, condition will becomes True and loop
will skip all the statement below continue and continues in loop with next value of
iteration.
else with while
Loop in python provides else clause with loop also which will execute when the loop
terminates normally i.e. when the test condition fails in while loop or when last value
is executed in for loop but not when break terminates the loop.
Example
i=1
while i<=10:
print(i)
i+=1
else:
print("Loop Over")
Output
1 2 3 4 5 6 7 8 9 10
Loop Over
else with for
Example
names=["allahabad","lucknow","varanasi","kanpur","agra","ghaziabad",
"mathura","meerut"]
city = input("Enter city to search: ") for c in
names:
if c == city:
print(“City Found") break
else:
print("Not found") Output:
Enter city to search : varanasi City
Found
Enter city to search : unnao Not
found

You might also like