Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
SlideShare a Scribd company logo

1

Computer Science with Python
Class: XII
Unit I: Computational Thinking and Programming -2
Chapter 1: Review of Python basics I (Revision Tour Class XI)
Mr. Vikram Singh Slathia
PGT Computer Science

2

Python
• In class XI we have learned about Python. In this class we will
learn Python with some new techniques.
• Python was created by Guido van Rossum. Python got its name
from a BBC comedy series – “Monty Python’s Flying Circus”.
• Python is based on two programming languages:
a. ABC Language b. Module 3
• We know that Python is a powerful and high level language and it
is an interpreted language.
• Python gives us two modes of working-
 Interactive mode
It allows us to interact with OS. It executes the code by typing in
Python Shell Script mode
In this we type python program in a file and then use interpreter
to executes the content of the file

3

Tokens
• Token is the smallest unit of any programming language. It is also
known as Lexical Unit. Types of token are-
i. Keywords
ii. Identifiers (Names)
iii. Literals
iv. Operators
v. Punctuators
i. Keywords
Keywords are those words which
provides a special meaning to
interpreter.
These are reserved for specific
functioning. These can not be
used as identifiers, variable name
or any other purpose.
Available keywords in Python are-

4

ii. Identifiers
• These are building blocks of a program and are used to give
names to different parts/blocks of a program like - variable,
objects, classes, functions.
• An identifier may be a combination of letters and numbers. An
identifier must begin with an alphabet or an underscore( _ ) not
with any number.
• Python is case sensitive. Uppercase characters are distinct from
lowercase characters (P and p are different for interpreter).
• Keywords can not be used as an identifier.
• Space and special symbols are not permitted in an identifier name
except an underscore( _ ) sign.
• Some valid identifiers are –
• Myfile, Date9_7_17, Z2T0Z9, _DS, _CHK FILE13.
• Some invalid identifiers are –
• DATA-REC, 29COLOR, break, My.File.

5

iv. Literals / Values
• Literals are often called Constant Values.
• Python permits following types of literals -
◦ String literals – “Pankaj”
◦ Numeric literals – 10, 13.5, 3+5j
◦ Boolean literals – True or False
◦ Special Literal None
◦ Literal collections
String Literals
String Literal is a sequence of characters that can be a combination
of letters, numbers and special symbols, enclosed in quotation
marks, single, double or triple(“ “ or ‘ ‘ or “’ ‘”).
In python, string is of 2 types-
• Single line string
Text = “Hello World” or Text = ‘Hello World’
• Multi line string
Text = ‘hello or Text = ‘’’hello
world’ word ‘’’

6

Numeric Literals
 Numeric values can be of three types -
• int (signed integers)
• Decimal Integer Literals – 10, 17, 210 etc.
• Octal Integer Literals - 0o17, 0o217 etc.
• Hexadecimal Integer Literals – 0x14, 0xABD etc.
 float ( floating point real value)
• Fractional Form – 2.0, 17.5 -13.5, -.00015 etc.
• Exponent Form - -1.7E+8, .25E-4 etc.
 complex (complex numbers)
• 3+5i etc.
Boolean Literals
It can contain either of only two values – True or False
Special Literals
None, which means nothing (no value).

7

v. Operators
An Operator is a symbol that trigger some action when applied to
identifier(s)/ operand (s). Therefore, an operator requires operand(s)
to compute upon. example :
c = a + b
Here, a, b, c are operands and operators are = and + which are
performing differently.
vi. Punctuators
In Python, punctuators are used to construct the program and to
make balance between instructions and statements.
Punctuators have their own syntactic and semantic significance.
• Python has following Punctuators -
‘, ”, #, , (, ), [, ], {, }, @. ,, :, .. `, =

8

CORE
DATA
TYPE
Numbe
rs
Non
e
Sequenc
es
Mappin
gs
Integ
er
Floatin
g
Point
Compl
ex
Strin
g
Tupl
e
Lis
t
Dictiona
ry
Boole
an
DATA TYPES

9

Variables and Values
An important fact to know is-
◦ In Python, values are actually objects.
◦ And their variable names are actually their reference names.
Suppose we assign 12 to a variable
A = 12
Here, value 12 is an object and A is its reference name.
Mutable and Immutable Types
Following data types comes under mutable and immutable types-
• Mutable (Changeable)
 lists, dictionaries and sets.
• Immutable (Non-Changeable)
 integers, floats, Booleans, strings and tuples.

10

Operators
• The symbols that shows a special behavior or action when applied to
operands are called operators. For ex- + , - , > , < etc.
• Python supports following operators-
i. Arithmetic Operator
ii. Relation Operator
iii. Identity Operators
iv. Logical Operators
v. Bitwise Operators
vi. Membership Operators

11

Operator Associativity
In Python, if an expression or statement consists of multiple or
more than one operator then operator associativity will be
followed from left-to- right.
In above given expression, first 7*8 will be calculated as 56, then 56
will be divided by 5 and will result into 11.2, then 11.2 again
divided by 2 and will result into 5.0.
Only in case of **, associativity will be followed from right-to-left.
Above given example will be calculated as 3**(3**2).

12

Type Casting
As we know, in Python, an expression may be consists of
mixed datatypes.
In such cases, python changes data types of operands
internally. This process of internal data type conversion is
called implicit type conversion.
➢ One other option is explicit type conversion which is like-
<datatype> (identifier)
For ex-
a=“4”
b=int(a)
Another ex-
If a=5 and b=10.5 then we can convert a to float.
Like d=float(a)
In python, following are the data conversion functions-
a. int ( ) b. float( ) c. complex( ) d. str( ) e. bool( )

13

Taking Input in Python
• In Python, input () function is used to take input which takes input
in the form of string. Then it will be type casted as per
requirement. For ex- to calculate volume of a cylinder, program will
be as-
Its output will be as-

14

Types of statements in Python
In Python, statements are of three types:
» Empty Statements
• pass
» Simple Statements (Single Statement)
• name=input (“Enter your Name “)
• print(name) etc.
» Compound Statements
<Compound Statement Header>:
<Indented Body containing multiple simple
statements /compound statements >
• Header line starts with the keyword and ends at colon (:)
• The body consists of more than one simple Python
statements or compound statements.

15

Statement Flow Control
In a program, statements executes in sequential manner or
in selective manner or in iterative manner.
Sequential Selective Iterative

16

If conditional come in multiple forms:
• if Condition
• if-else condition
• if-elif conditional
• Nested if statement
if Statement
An if statement tests a particular condition;
If the condition evaluates to true, a course of action is
followed. If the condition is false, it does nothing.
Syntax:
if <condition>:
statement(s)

17

if-else Statements
If the condition evaluates to true, it carries out
statement indented below if and in case condition
evaluates to false, it carries out statements indented
below else.
Syntax:
if <condition>:
statement(s) when if condition is true
else:
statement(s) when else case is true dition is false

18

if-elif conditional
if statements are executed from the top down. As soon as one of the
conditions controlling the if is true, the statement associated with
that if is executed, and the rest of the ladder is bypassed. If none of
the conditions is true, then the final else statement will be executed.
The elif keyword is pythons way of saying "if the previous
conditions were not true, then try this condition".
Syntax:
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else

19

Flow Chart

20

Example:
num = 3.4
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")

21

Nested If -else
A nested if is an if statement that is the target of another if
statement. Nested if statements means an if statement inside
another if statement.

22

Syntax:
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
Example:
i = 10
if (i == 10):
# First if statement
if (i < 15):
print ("i is smaller than 15")
# Nested - if statement, Will only be executed if statement above it is true
if (i < 12):
print ("i is smaller than 12 too")
else:
print ("i is greater than 15")i = 10
if (i == 10):
# First if statement
if (i < 15):
print ("i is smaller than 15")
# Nested - if statement. Will only be executed if statement above. it is true
if (i < 12):
print ("i is smaller than 12 too")
else:
print ("i is greater than 15")

23

Loop/Repetitive Task/Iteration
These control structures are used for repeated execution of statement(s)
on the basis of a condition. Loop has three main components-
• Start (initialization of loop)
• Step (moving forward in loop )
• Stop (ending of loop)
Python has following loops-
– for loop
– while loop

24

range () Function
In Python, an important function is range().
Syntax:
range ( <lower limit>,<upper limit>)
If we write
range (0,5 )
Then a list will be created with the values [0,1,2,3,4]
i.e.
from lower limit to the value one less than ending limit.
range (0,10,2) will have the list [0,2,4,6,8]. range (5,0,-1) will have
the list [5,4,3,2,1].

25

For Loop
The for loop in Python is used to iterate over a sequence
(list, tuple, string) or other iterable objects.
Iterating over a sequence is called traversal.
Syntax:
for val in sequence:
Body of for

26

# Program to find the sum of all numbers stored in a list
# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
# variable to store the sum
sum = 0
# iterate over the list
for val in numbers:
sum = sum+val
print("The sum is", sum)

27

for loop with else
A for loop can have an optional else block as well. The else
part is executed if the items in the sequence used in for loop
exhausts.
Example:
digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")
output:
0
1
5

28

While Loop
The while loop in Python is used to iterate over a block of code
as long as the test expression (condition) is true.
We generally use this loop when we don't know the number of
times to iterate beforehand.
Syntax:
while test_expression:
Body of while

29

Example:
# Program to add natural numbers up to sum = 1+2+3+...+n
# To take input from the user,
n = int(input("Enter n: "))
# initialize sum and counter
sum = 0
i = 1
while i <= n:
sum = sum + i
i = i+1 # update counter
# print the sum
print("The sum is", sum)

30

Jump Statements
break Statement
while <test-condition>:
statement1
if <condition>:
break
statement2
statement3
Statement4
statemen 5
for <var> in <sequence>:
statement1
if <condition>: break
statement2
statement3
Statement4
statement5

31

Jump Statements
Example

32

Python revision tour i

33

in and not in operator
in operator-
3 in [1,2,3,4] will return True.
5 in [1,2,3,4] will return False.
not in operator-
5 not in [1,2,3,4] will return True.

34

Jump Statements
continue Statement
The continue statement is used to skip the rest of the code inside a
loop for the current iteration only. Loop does not terminate but
continues on with the next iteration.

35

Python revision tour i

36

Part one of Python Revision Tour of
Class XI Completed
Topics
• Strings
• Lists
• Tuples
• Dictionaries
• Sorting Tewchniques
are in next slide
For any querries you may contact me

37

For reference you check out online
• https://www.programiz.com/python-
programming/first-program
• https://www.w3schools.com/python/
default.asp

More Related Content

Python revision tour i

  • 1. Computer Science with Python Class: XII Unit I: Computational Thinking and Programming -2 Chapter 1: Review of Python basics I (Revision Tour Class XI) Mr. Vikram Singh Slathia PGT Computer Science
  • 2. Python • In class XI we have learned about Python. In this class we will learn Python with some new techniques. • Python was created by Guido van Rossum. Python got its name from a BBC comedy series – “Monty Python’s Flying Circus”. • Python is based on two programming languages: a. ABC Language b. Module 3 • We know that Python is a powerful and high level language and it is an interpreted language. • Python gives us two modes of working-  Interactive mode It allows us to interact with OS. It executes the code by typing in Python Shell Script mode In this we type python program in a file and then use interpreter to executes the content of the file
  • 3. Tokens • Token is the smallest unit of any programming language. It is also known as Lexical Unit. Types of token are- i. Keywords ii. Identifiers (Names) iii. Literals iv. Operators v. Punctuators i. Keywords Keywords are those words which provides a special meaning to interpreter. These are reserved for specific functioning. These can not be used as identifiers, variable name or any other purpose. Available keywords in Python are-
  • 4. ii. Identifiers • These are building blocks of a program and are used to give names to different parts/blocks of a program like - variable, objects, classes, functions. • An identifier may be a combination of letters and numbers. An identifier must begin with an alphabet or an underscore( _ ) not with any number. • Python is case sensitive. Uppercase characters are distinct from lowercase characters (P and p are different for interpreter). • Keywords can not be used as an identifier. • Space and special symbols are not permitted in an identifier name except an underscore( _ ) sign. • Some valid identifiers are – • Myfile, Date9_7_17, Z2T0Z9, _DS, _CHK FILE13. • Some invalid identifiers are – • DATA-REC, 29COLOR, break, My.File.
  • 5. iv. Literals / Values • Literals are often called Constant Values. • Python permits following types of literals - ◦ String literals – “Pankaj” ◦ Numeric literals – 10, 13.5, 3+5j ◦ Boolean literals – True or False ◦ Special Literal None ◦ Literal collections String Literals String Literal is a sequence of characters that can be a combination of letters, numbers and special symbols, enclosed in quotation marks, single, double or triple(“ “ or ‘ ‘ or “’ ‘”). In python, string is of 2 types- • Single line string Text = “Hello World” or Text = ‘Hello World’ • Multi line string Text = ‘hello or Text = ‘’’hello world’ word ‘’’
  • 6. Numeric Literals  Numeric values can be of three types - • int (signed integers) • Decimal Integer Literals – 10, 17, 210 etc. • Octal Integer Literals - 0o17, 0o217 etc. • Hexadecimal Integer Literals – 0x14, 0xABD etc.  float ( floating point real value) • Fractional Form – 2.0, 17.5 -13.5, -.00015 etc. • Exponent Form - -1.7E+8, .25E-4 etc.  complex (complex numbers) • 3+5i etc. Boolean Literals It can contain either of only two values – True or False Special Literals None, which means nothing (no value).
  • 7. v. Operators An Operator is a symbol that trigger some action when applied to identifier(s)/ operand (s). Therefore, an operator requires operand(s) to compute upon. example : c = a + b Here, a, b, c are operands and operators are = and + which are performing differently. vi. Punctuators In Python, punctuators are used to construct the program and to make balance between instructions and statements. Punctuators have their own syntactic and semantic significance. • Python has following Punctuators - ‘, ”, #, , (, ), [, ], {, }, @. ,, :, .. `, =
  • 9. Variables and Values An important fact to know is- ◦ In Python, values are actually objects. ◦ And their variable names are actually their reference names. Suppose we assign 12 to a variable A = 12 Here, value 12 is an object and A is its reference name. Mutable and Immutable Types Following data types comes under mutable and immutable types- • Mutable (Changeable)  lists, dictionaries and sets. • Immutable (Non-Changeable)  integers, floats, Booleans, strings and tuples.
  • 10. Operators • The symbols that shows a special behavior or action when applied to operands are called operators. For ex- + , - , > , < etc. • Python supports following operators- i. Arithmetic Operator ii. Relation Operator iii. Identity Operators iv. Logical Operators v. Bitwise Operators vi. Membership Operators
  • 11. Operator Associativity In Python, if an expression or statement consists of multiple or more than one operator then operator associativity will be followed from left-to- right. In above given expression, first 7*8 will be calculated as 56, then 56 will be divided by 5 and will result into 11.2, then 11.2 again divided by 2 and will result into 5.0. Only in case of **, associativity will be followed from right-to-left. Above given example will be calculated as 3**(3**2).
  • 12. Type Casting As we know, in Python, an expression may be consists of mixed datatypes. In such cases, python changes data types of operands internally. This process of internal data type conversion is called implicit type conversion. ➢ One other option is explicit type conversion which is like- <datatype> (identifier) For ex- a=“4” b=int(a) Another ex- If a=5 and b=10.5 then we can convert a to float. Like d=float(a) In python, following are the data conversion functions- a. int ( ) b. float( ) c. complex( ) d. str( ) e. bool( )
  • 13. Taking Input in Python • In Python, input () function is used to take input which takes input in the form of string. Then it will be type casted as per requirement. For ex- to calculate volume of a cylinder, program will be as- Its output will be as-
  • 14. Types of statements in Python In Python, statements are of three types: » Empty Statements • pass » Simple Statements (Single Statement) • name=input (“Enter your Name “) • print(name) etc. » Compound Statements <Compound Statement Header>: <Indented Body containing multiple simple statements /compound statements > • Header line starts with the keyword and ends at colon (:) • The body consists of more than one simple Python statements or compound statements.
  • 15. Statement Flow Control In a program, statements executes in sequential manner or in selective manner or in iterative manner. Sequential Selective Iterative
  • 16. If conditional come in multiple forms: • if Condition • if-else condition • if-elif conditional • Nested if statement if Statement An if statement tests a particular condition; If the condition evaluates to true, a course of action is followed. If the condition is false, it does nothing. Syntax: if <condition>: statement(s)
  • 17. if-else Statements If the condition evaluates to true, it carries out statement indented below if and in case condition evaluates to false, it carries out statements indented below else. Syntax: if <condition>: statement(s) when if condition is true else: statement(s) when else case is true dition is false
  • 18. if-elif conditional if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed. The elif keyword is pythons way of saying "if the previous conditions were not true, then try this condition". Syntax: if test expression: Body of if elif test expression: Body of elif else: Body of else
  • 20. Example: num = 3.4 if num > 0: print("Positive number") elif num == 0: print("Zero") else: print("Negative number")
  • 21. Nested If -else A nested if is an if statement that is the target of another if statement. Nested if statements means an if statement inside another if statement.
  • 22. Syntax: if (condition1): # Executes when condition1 is true if (condition2): # Executes when condition2 is true # if Block is end here # if Block is end here Example: i = 10 if (i == 10): # First if statement if (i < 15): print ("i is smaller than 15") # Nested - if statement, Will only be executed if statement above it is true if (i < 12): print ("i is smaller than 12 too") else: print ("i is greater than 15")i = 10 if (i == 10): # First if statement if (i < 15): print ("i is smaller than 15") # Nested - if statement. Will only be executed if statement above. it is true if (i < 12): print ("i is smaller than 12 too") else: print ("i is greater than 15")
  • 23. Loop/Repetitive Task/Iteration These control structures are used for repeated execution of statement(s) on the basis of a condition. Loop has three main components- • Start (initialization of loop) • Step (moving forward in loop ) • Stop (ending of loop) Python has following loops- – for loop – while loop
  • 24. range () Function In Python, an important function is range(). Syntax: range ( <lower limit>,<upper limit>) If we write range (0,5 ) Then a list will be created with the values [0,1,2,3,4] i.e. from lower limit to the value one less than ending limit. range (0,10,2) will have the list [0,2,4,6,8]. range (5,0,-1) will have the list [5,4,3,2,1].
  • 25. For Loop The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable objects. Iterating over a sequence is called traversal. Syntax: for val in sequence: Body of for
  • 26. # Program to find the sum of all numbers stored in a list # List of numbers numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11] # variable to store the sum sum = 0 # iterate over the list for val in numbers: sum = sum+val print("The sum is", sum)
  • 27. for loop with else A for loop can have an optional else block as well. The else part is executed if the items in the sequence used in for loop exhausts. Example: digits = [0, 1, 5] for i in digits: print(i) else: print("No items left.") output: 0 1 5
  • 28. While Loop The while loop in Python is used to iterate over a block of code as long as the test expression (condition) is true. We generally use this loop when we don't know the number of times to iterate beforehand. Syntax: while test_expression: Body of while
  • 29. Example: # Program to add natural numbers up to sum = 1+2+3+...+n # To take input from the user, n = int(input("Enter n: ")) # initialize sum and counter sum = 0 i = 1 while i <= n: sum = sum + i i = i+1 # update counter # print the sum print("The sum is", sum)
  • 30. Jump Statements break Statement while <test-condition>: statement1 if <condition>: break statement2 statement3 Statement4 statemen 5 for <var> in <sequence>: statement1 if <condition>: break statement2 statement3 Statement4 statement5
  • 33. in and not in operator in operator- 3 in [1,2,3,4] will return True. 5 in [1,2,3,4] will return False. not in operator- 5 not in [1,2,3,4] will return True.
  • 34. Jump Statements continue Statement The continue statement is used to skip the rest of the code inside a loop for the current iteration only. Loop does not terminate but continues on with the next iteration.
  • 36. Part one of Python Revision Tour of Class XI Completed Topics • Strings • Lists • Tuples • Dictionaries • Sorting Tewchniques are in next slide For any querries you may contact me
  • 37. For reference you check out online • https://www.programiz.com/python- programming/first-program • https://www.w3schools.com/python/ default.asp