0% found this document useful (0 votes)
101 views

Class XII - L1 - Python Revision Tour 1

The document discusses the basics of Python programming including tokens, data types, variables, input/output functions and more. It covers keywords, identifiers, literals, operators, punctuators and the barebones of a Python program. Common data types like integers, floats, strings, lists and tuples are also explained.

Uploaded by

Harsh Yadav
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
101 views

Class XII - L1 - Python Revision Tour 1

The document discusses the basics of Python programming including tokens, data types, variables, input/output functions and more. It covers keywords, identifiers, literals, operators, punctuators and the barebones of a Python program. Common data types like integers, floats, strings, lists and tuples are also explained.

Uploaded by

Harsh Yadav
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

LESSON 1 : PYTHON REVISION TOUR 1

1
1.1 INTRODUCTION
• Python programming language was developed by Guido Van Rossum in early
1990s, has become very popular among beginners and as well as the developers.
• A python program may contain various components like expressions, statements,
comments, functions, blocks and indentation.

1.2 TOKENS OF PYTHON:


• The smallest individual unit in a program is known as a Token or a lexical unit.
• Python has following tokens:
a. Keywords
b. Identifiers (Names)
c. Literals
d. Operators
e. Punctuators
a. Keywords:
• Keywords are predefined words with special meaning to the language
compiler or interpreter.
• These are reserved for special purpose and must not be used as
normal identifier names.
• Pythons keywords: False, None,Break, True, Class, Elif, Lambda, While,
import, raise, etc
b. Identifiers:
• Identifies are the names given to different parts of the program like
variables, classes, objects, functions etc.
• The naming rule for python identifiers can be as follows:
1. Variable names must only be a non-keyword word with no spaces
in between.
2. Variable names must be made up of only letters, numbers and
underscore.
3. Variable names can not begin with a number, although they can
contain numbers.
Example: MyFile DATA9_7_77

2
c. Literals / values:
• Literals are data items that have a fixed/ constant values.
• Python allows several kinds of literals, which are:
1. String literals:
• string literal is a sequence of characters surrounded by
quotes. String literals can be either be single line string or
multi-line string.
• Single line string must terminate in one line. The closing
quotes should be on the same line as that of the opening
quotes.
• Multi-line string are string spread across multiple lines.
2. Numeric literals:
• Numeric literals are numeric values and these can be one :
1. Int (signed integer)
2. Floating point literals.
3. Boolean literals
4. Complex number literals
3. Boolean literals:
• A boolean literal in python is used to represent one of the
boolean values i.e., true or false
• A boolean literal can either have value as true or false.

4. Special literal None:


• Python has one special literal, which is None. The None
literal is used to indicate absence of value.
• Python can also store literal collections, in the form of
tuples and lists etc.

3
d. Operators:
• Operators are tokens that trigger some computation/ action when
applied to variables and other objects in an expression.
• The operators can be:
1. Arithmetic operators (+, -, *, /, %, **, //)
2. Bitwise operators (&, ^, |)
3. Shift operators (<<, >>)
4. Identity operators ( is, is not)
5. Relational operators(<, >, <=, >=, ==, !=)
6. Logical operators (and, or)
7. Assignment operators( =)
8. Membership operators( in, not in)
9. Arithmetic-assignment operators (/=, +=, -=, */, %=, **=, //=)
e. Punctuators:
• Punctuators are symbols that are used in programming languages to organize
sentences, structures and indicate the rhythm and emphasis of expressions,
statements and program structure.
• Most common punctuators of python programming are
‘, “, #, \, ( ), {}, [], @, :, ., `, =.

1.3 BAREBONES OF PYTHON PROGRAM:


• A Python program may contain various elements such as comments, statements,
expressions etc.
• Expressions, which are any legal combination of symbols that represents a
value.
• Statement, which are program instructions.
• Comments, which are the additional readable information to clarify the source
code. Comments can be single line or multiline comments.
• Functions, which are named code-sections and can be reused by specifying their
names.
• Block(s) or suite(s), which is a group of statements which are part of another
statement or a function. All statements inside a block or suite are indented at the
same level.

4
1.4 VARIABLES AND ASSIGNMENTS:
• Variables represents labelled storage locations, whose values can be manipulated
during program run.
• In python, to create a variable, just by assigning to its name the value of appropriate
type.
• Example: student = ‘jacob’, age = 16.
Dynamic typing:
• A variable pointing to a value of a certain type, can be made to point to a
value/object of different type, this is called dynamic typing.
• Dynamic typing means a variable can hold values of different types at different
times.
• Example:
x=10
print (x)
10
x= “hello world”
print (x)
hello world
Multiple assignment:
• Assigning same value to multiple variables: we can assign same value to multiple
variables in a single statement, e,g.,
A= b= c =10
It will assign value 10 to variables a, b, c.
• Assigning multiple values to multiple variables: we can assign multiple values to
multiple variables in single statement, e,g.,
x, y, z = 10, 20, 30
It will assign the values in order wise, i,e., first variable first value, second variable
second value and third variable third value. x=10, y=20, z=30.

1.5. SIMPLE INPUT AND OUTPUT:


• In python, to get input from user , we can use built-in function input(). The function
input () is used as follows:
variable_to_hold_the_value = input (<prompt to be displayed> )

5
• Example: name = input (‘ what is your name ?’)
• The input() function always returns a value of string type. Python offers two
function int () and float().
• While inputting integer values using int() with input(), we should make sure that
the values being entered must be int type compatible. Same with the float() with
input().

Output through print( ) statement:


• The print() function of python 3 is a way to send output to standard output
device, which is normally a monitor.
• The simplified syntax to use print() is as follows:
print(* objects, [sep = ‘ ‘ or <separator-string> end = ‘\n’ or <end-string> ] )
• *objects means it can be one or multiple comma separated objects to be
printed.
• Example: print(“hello”)
• The print statement has a number of features:
1. It auto-converts the items to strings i,e., if printing a numeric value, it will
automatically convert it into equivalent string and print it, for numeric ex
pressions, it first evalutes them and then converts the result to string, before
printing.
2. It inserts space between items automatically because the default value of
separgument is space.
3. It appends a newline character at the end of the line unless end argument is
given.

1.6 DATA TYPES:


• Data types are means to identify type of data and set of valid operations for it.
• Python has the following built-in data types:

6
1. Data types for number:
a. Python offers data types to store and process different types of numeric data
b. Integers: there are two types of integers in python. Signed integer and
booleans.
c. Floating point numbers: this type represent machine-level double precision
floating point numbers.
d. Complex numbers: python represents complex numbers in the form A+Bj.
Complex numbers are a composite quantity made of two parts: the real and
imaginary part, both of which are represented as float values.

2. Data types for strings:


a. All strings in python are sequences of pure unicode characters. Unicode is a
system designed to represented every character from every language.
b. A string can hold any type of known characters i.e., letters, numbers and
special character, of any known scripted language.
c. Example: “abcd”, “1234”, ‘$%^&’, etc
d. A python string is a sequence of characters and each character can be
individually accessed using its index.
3. Lists:
a. A list in python represents a group of comma-seperated values of any data
type within the square bracket.
a. Example: [1, 2, 3, 4, 5], [‘neha’, 102, 79.5].

4. Tuples:
a. Tuples are represented as group of comma-seperated values of any data type
within the parentheses.
b. Example: p = (1, 2, 3, 4), r = (‘a’, ‘e’, ‘i’, ‘o’, ‘u’)

5. Dictionaries:
a. The dictionary is an unordered set of comma-seperated key : value pairs,
within { }, with the requirement that within a dictionary, no two keys can be the same.
b. Example: {‘a’:1, ‘e’:2, ‘i’:3, ‘o’:4, ‘u’:5}.

7
1.7 MUTABLE AND IMMUTABLE TYPES:
Immutable types:
• The immutable types are those that can never change their values in place.
• Integers, floating point numbers, booleans, string, tuples are immutable types in
python.
• In immutable types, the variable names are stored as references to a value
object Each time change of the value address of memory also changes.
Mutable types:
• Mutability means that in the same memory address, new value can be stored as
and when user wants.
• The types that do not support this property are immutable types.
• The mutable types are those values can be changed in place.
• Lists, dictionaries and sets are the three mutable types in python.

1.8 EXPRESSIONS:
• An expression in python is any valid combination of operators, literals and
variables.
• The expressions in python can be of any type: arithmetic expressions, string
expressions, relational expressions, logical expressions, etc.
• Arithmetic expressions involves numbers and arithmetic operators.Example:
2+5**3, -8*6/5, etc
• An expression having literals and/or variables of any valid type and relational
operators is a relational expression.
Example: x > y, y <= z, z != q, etc
• An expression having literals and/or variables of any valid type and logical
operators is a logical expression.
Example: a or b, a and not b.
• Python provides two string operators + and *, when combined with string
operands and integers, from string expression.
Example: “and” + “then”, “and” * 2

8
Evaluating Arithmetic expression:
Rules for evaluating arithmetic expressions:
• Determines the order of evaluation in an expression considering the operator
precedence.
• As per the evaluation order, for each of the sub-expression
i. Evaluate each of its operands or arguments.
ii. Performs any implicit conversions.
iii. Compute its result based on the operator.
iv. Replace the sub-expression with the computed result and carry on the
expression evaluation.
v. Repeat till the final result is obtained.
In a mixed arithmetic expression, python converts all operands up to the type
of the largest operand. If both arguments are standard numeric types, the
following are applied:
• If either argument is a complex number, the other is converted to complex.
• Otherwise, if either argument is a floating point number, the other is converted
to floating point.
• No conversion if both operands are integer.

Evaluating relational expression:


• All comparison operations in python have the same priority, which is lower than
that of any arithmetic operations. All relational expressions yield Boolean
values only i.e., true or false.
• Chained expressions like a < b < c have the interpretation that is conventional
in mathematics i,e., comparisons in python are chained arbitrarily.

Evaluating logical expression:


While evaluating logical expressions, python follows the rules:
• The precedence of logical operators is lower than the arithmetic operators,
so constituent arithmetic sub-expression is evaluated first and then logical
operators are applied.
Example: 25/5 or 2.0 + 20/10 will be first evaluated as 5 or 4.0
• The precedence of logical operators among themselves is not, and, or. So
the expression a or b and not c will be evaluated as (a or ( b and (not c)))

9
• While evaluating, python minimizes internal work by following the rules:
1. In or evaluating, python only evaluates the second argument if the first one is
falsetval.
2. In and evaluation, python only evaluates the second argument if the
first one is truetval.
Type casting:
• An explicit type conversion is user-defined conversion that forces an
expression to be of specific type. The explicit type conversion is also known as
type casting.
• Type casting in python is performed by <type>( ) function of appropriate
data type. Syntax: < datatype > (expression)
• Where <datatype> is the data type to which user want to type cast the
expression.
Example: if we have ( a = 3 and b = 5.0) then
int( b) will cast the data-type of the expression as int.

Math library function:


• Python’s standard library provides a module namely math for math related
functions that work with all number types except for complex numbers.
• To work with functions of math module, first need to import to the program by
giving statement as follows: import math

10
Some of the math library functions:

Prototype
S No. Function Description Example
(General Form)
The ceil () function
math ceil (1.03) gives 2.0
1. ceil Math cell (num) returns the smallest
math ceil (-103) gives – 10.
integer root less than
The sqrt ( ) function
returns the square root
2. sqrt Math. Sqrt (num) math sqrt (81.0) gives 9.0
of num. if num < 0,
domain error occurs.
The exp ( ) function re-
turns the natural loga- math. Exp (2.0) gives the
3. exp Math exp (arg)
rithm e raised to the org value of e2
power.
math. Fabs (1.0) gives 1.0
The fabs ( ) function re-
4. fabs Math. Fabs (num) turns the absolute value Math. Floor (-1.03)
of num
gives – 2.0
The floor ( ) function
returns the natural oga-
math. Floor (1.3) gives 1.0
rithm for num. A domain
5. floor Math. Floor (num) error occurs if num is Math. Floor (-1.03)
negative and a range
gives – 2.0
error occurs if the argu-
ment num is zero.
The log () function re-
turns the natural loga- math. Log (1.0) gives the nat-

rithm for num. a domain ural logarithm for 1.0


Math. Log(num,
6. log error occurs if num is Math. Log (1024, 2) will give
[base])
negative and a range logarithm of 1024 to the
error occurs if the argu- base 2.
ment num is zero.

11
The log 10 ( ) function
returns the base 10
logarithm for num. a
Math. Log 10 math. Log 10 (1.0) gives base
7. log 10 domain error occurs if
(num) 10 logarithm for 1.0
num is negative and a
range error occurs if
the argument is zero
The pow ( ) function
returns base raised to
exp power i. e., base math. Pow (3.0, 0) gives value

math. pow (base, exp. A domain error of 3


8. pow
exp) occurs if num is nega- Math. Pow (4.0, 2.0) gives
tive and a range error value of 42.
occurs if the argument
is zero.
The sin ( ) function
returns the sine of arg. math. sin (val) (val is
9. sin math. sin (arg)
The value of arg must a number)
be in radians.
The cos ( ) function
returns the cosine of arg. math. cos (val)
10. cos math. Tan (arg)
The value of arg must be (val is a number)
in radians
The tan ( ) function
returns the tangent of arg. math. tan (val)
11. Tan math. tan (arg)
The value of arg must be (val is a number)
in radius
The degrees ( ) converts
math. Degrees (3.14) would give
12. Degrees math. Degrees (x) angle x from radians to
179.91
degrees.

12
1.9 STATEMENT FLOW CONTROL:
• Statements can be executed sequentially, selectively or iteratively. Every
programming language provides constructs to support sequence, selection or
iteration.
• A conditional is a statement set which is executed, on the basis of result of a
condition.
• A loop is a statement set which is executed repeatedly, until the end condition is
satisfied.
Compound statement:
• A compound statement represents a group of statements executed as a unit.
• The compound statements of python are written in a specific pattern:
< compound statement header > :
< indented body containing multiple simple and/or compound statements >
• The conditionals and the loops are compound statements, they contain other
statements.
• For all the compound statements:
a. The contained statements are not written in the same column as the control
statements rather they are indented to the right and together they are
called a block.
b. The first line of compound statement, i.e., its header contains a colon ( : )
at the end of it.
• Example:
num1 = int(input(“enter the number 1”))
num2 = int(input(“enter the number 2”))
if num2 < num1:
t = num2 * num1
t = t +10
print(num2, num1, t)

Simple statements:
• Compound statements are made of simple statements. Any single executable
statement is a simple statement in python.

13
Empty statement:
• The simplest statements is the empty statements i.e., a statement which does
nothing. In python and empty statement is the pass statement.
• Whenever python encounters pass statement, python does nothing and moves to
next statement in the flow control.

1.10 THE IF CONDITIONAL:


• An if statement tests a particular condition, if the condition evaluates to true, a
course-of action is followed i.e., a statement or set of statements is executed.
• If the condition is false, it does nothing.
• Syntax:
If <conditional expression> :
Statement
[statement]
• Flow chart:

Test
Expression
?

body of if

• Example:
if grade == ‘A’ :
print(“ congratulations ! you did well”)

The if-else conditional statement:


• This form of if statement tests a condition and if the condition evaluates to true, it car-
ries out
the statements indented below if.
• In case condition evaluates to false, it carries out statement indented below else.
• Syntax:
If <conditional expression>:
Statement
[statements]
Else:
Statement
[statements]

14
• Flow chart:

Test
Expression False
?

True
body of if


Example:
if a > = 0:
print( a, “is zero or a positive number”)
else:
Print(a, “ is a negative number”)
The if- elif conditional statement:
• If the user wants to check a condition after or when control reaches else
i.e., condition test in the form of else if.
• To serve such conditions, python provides if-elif and if-elif-else statements.
• Syntax:
if < conditional expression > :
Statement
[statements]
elif <conditional expression >:
Statement
[statements]
Nested if statements:
• Python also supports nested-if form of it. A nested if is an if that has another
if in its if’s body or in else body or in elif body.
• Example:
if x < y and x < z:
if y < z:
min, mid, max = x, y, z
else:
min, mid, max = x, z, y
elif y < x and y < z :
if x < z:
min, mid, max = y, x, z
else:
min, mis, max = y, z, x

15
Storing conditions:
• The conditions being used in code are complex and repetitive. In such cases
to make programmore readable, named conditions can be used, we can store
conditions in a name and thenuse that name conditional in the if statement.
• Example: consider
b, c = 2, 3
#Store condition in a name called all.
all = a == 1 and b == 2 and c == 3
#Test variable.
if all:
Print(“condition fulfilled”)
#Use it again.
if all:
Print(“condition fulfilled again”)

1.11 LOOPING STATEMENT:


Python provides two types of loops:
The for loop:
• The for loop of python is designed to process the items of any sequence, such as
list or a
string, one by one.
• Syntax:
for < variable > in <sequence> :
Statements_to_repeat
• Example:
for element in [10, 15, 20, 25] :
Print(element + 2, end = ‘ ‘)
The while loop:
• A while loop is a conditional loop that will repeat the instructions within itself as
long as
a conditional remains true ( boolean true or truth value true).
• Syntax:
while < logicalExpression>:
loop-body
• Example:
while count > 0:
count = count - 1
Product = product + n2

16
1.12 JUMP STATEMENT:
Break statement:
• A break statement terminates the very loop it lies within.
• A break statement skips the rest of the loop and jumps over to the statement following
the loop.
• Example:
if b == 0 :
Print(“ division by zero error ! Aborting !”)
Break
else :
c = a/b
print(“quotient = “, c)
Continue statement:
• The continue statement forces the next iteration of the loop to take place unlike
thebreak statement, skipping any code in between.
• The continue statement skips the rest of the loop statements and cause the next
iteration of the loop to take place.

1.13 MORE ON LOOPS:


Loop else statement:
• Python loops have an optional else clause.
• Syntax of python loops along with else clause is as given:
for < variable > in < sequence>:
statement 1
statement 2
…..
else :
statement (s)
• The else clause of a python loop executes when the loop terminates normally, i.e.,
when test-condition results into false for a while loop or for loop has executed for
the last value in the sequence, not when the break statement terminates the loop.

17
Nested loops:
• A loop may contain another loop in its body. This form of a loop is called
nested loop.
• In a nested loop the inner loop must terminate before the outer loop.
• Example:
for i in range (1, 6) :
for j in range (1, i) :
print(“*”, end = ‘ ‘)
print( )
• In nested loops, a break statement will terminate the very loop it appears in. If
break statement is inside the inner loop then only the inner loop will terminate and
outer loop will continue.

18

You might also like