Download as pdf or txt
Download as pdf or txt
You are on page 1of 74

Class- XII

Computer Science (083)


Unit-1 Computational Thinking and Programming-2
Unit-2 Computer Networks
Unit-3 Database Management
Unit-1
Computational Thinking and Programming-2

Ch-1 Review of Python Basics


Ch-1 Review of Python Basics
1) Introduction
2) Tokens
3) Structure of a Python Program
4) Variables and Data Types
5) Keywords
6) Mutable and Immutable types
7) Operators and Operands
8) Input and Output(Python’s in-built functions)
9) Comments in python
10) Flow of Execution
11) Strings
12) Lists
13) Tuples
14) Dictionary
Introduction

It is widely used general purpose, high level programming


language. Developed by Guido van Rossum in 1991.
It is used for: software development, web development
(server-side), system scripting, Mathematics.
Features of Python

1. Easy to use – Due to simple syntax rule


2. Interpreted language – Code execution &
interpretation line by line
3. Cross-platform language – It can run on
windows, linux, macinetosh etc. equally
4. Completeness – Support wide rage of library
5. Free & Open Source – Can be downloaded
freely and source code can be modify for
improvement
Shortcomings of Python
1. Lesser libraries – as compared to other
programming languages like c++,java,.net
2. Slow language – as it is interpreted languages, it
executes the program slowly.
How to work in Python
python->IDLE(Python GUI)
Tokens

 Smallest Individual unit in a program is known as Token


 Python has following tokens:
– Keywords
– Identifiers (Names)
– Literals
– Operators
– Punctuators
Keywords

– Keywords are the words that have special meaning


reserved by programming language.
 – They are reserved for special purpose and cannot
be used for normal identifier names.
– E.g. in, if, break, class, and, continue, True, False
Identifiers
– Identifiers are fundamental building block of a
program.
 – They are names given to variable, functions,
objects classes etc.
– Python is case sensitive i.e. it treats upper case
and lower case letter differently.
– Naming Conventions:
• Contain A-Z, a-z, _
• Name should not start with digit
• It can start with alphabet or ( _ ) underscore
Literals
– Literals are data items that have fixed
value.
– Python allows several kinds of literals:
• String literals
• Numeric literals
• Boolean literals
• Special Literal None
• Literal Collections
String Literals
 • The text enclosed in single or double quotes.
 • There is no character literal.
 • Example ‘a’, ‘anant’, “HelloWorld”
 • Python allows non-graphic characters in string values.
• Non-graphic characters are represented using escape
sequence.
\n for newline,
\t tab space,
\r carriage return
String Types in Python
• Strings are declared in two ways : –
 Single-line String: enclosed within single or
double quotes. It must terminate in one line.
• Text1=“Computer”
• Text2=‘Science’
 Multiline String: text spread over multiple lines in
one single string.
• It can be created in two ways
• By adding backslash at end of each line
• By enclosing the text in triple quotation mark
Size of Strings
 • Size of string can be determined by len( ) function.
 • It tells the count of the characters in the string.
 • In multiline comments backslash is not counted.
 • In multiline comments with triple quotes EOL character
at end of line is counted.
Numeric Literals

• Integer: positive negative numbers without


decimal
• Floating Point: Real numbers with decimal points
• Complex Number: are in form a+bj , where a and
b are floating point numbers and j is √-1 . Where a is
real part and b is imaginary part.
Boolean literals Special Literal None

• True and False are the two Boolean Literals


• Special literal None represent absence of
value
• None also indicates end of List
• They are built-in constant literals of Python
Operator
 • Operators are the symbol, which triggers some
computation when applied on operand.
 – Unary Operator: those operators that require only one
operand.
 • Unary Plus +
 • Unary Minus –
 • Bitwise Complement ~
 • Logical Negation not
 – Binary Operator: those operators that require only two operand.
• Arithmetic Operator +,-,*,/,%
• Bitwise Operator &, ^, |
• Shift Operator >> , <<
• Identity Operator is , is not
Relational Operators

• Less Than <


• Greater Than >
• Less Than or Equal to <=
• Greater than or Equal to >=
• Equal To == • Not Equal to !=
Logical Operators

• Logical AND and


• Logical OR or
Assignment Operator

• Assignment =
• Assign Quotient /=
• Assign Sum +=
• Assign Product *=
• Assign Remainder %=
• Assign Difference -=
• Assign Exponent **=
• Assign Floor Division //=
Membership Operator
 • Whether variable in sequence in
 • Whether variable not in sequence not in
Punctuator

 • Punctuators are the symbols used in programming


language to organize the statements of the program.
 • Common Punctuators are
‘“#\()[]{}@,:.=
Barebones of Python Program
 • Components of Program are
 Expression: legal combination of symbols to represent a value.
 A=5 b=b+9 Statement: Instruction that performs certain
action.
 Print(“Hello”) if(a>90):
 Comments: Additional information regarding the source code
which is not executed.
 Single Line Comment: begins with #’
 Multiline Comments: enclosed in triple quotes(‘’’) called
docstring
 Functions: block of code having name , and can be reused by
specifying the name in the program, whenever required.
 Block and Indentation: Group of statement which are part of
another statement or function.
Variable and Assignments
 • Named Label whose value can be changed and processed
during the program run.
 • Creating Variable: ‘
– Name=‘Anant’
– Age=9
– Age=30
 • Python do not have fixed memory locations, when the value
changes they change their location
 • lvalue: expression that can come on lhs of an assignment.
 • Rvalue: expression that can come on rhs of an assignment.
Dynamic Typing

• The process in which the variable pointing to a


value of certain type, can be made to point to
the value of other type.
age=10
print(age)
age=“ten”
print(age)
Dynamic Typing

• Caution: keep the data type in mind while changing.


• type( ) function is used to determine the type of
object.
Dynamic Typing vs Static Type
• In Dynamic Typing the data type attached
with the variable can change during the
program run Whereas in Static Typing the data
type defined for the first time is fixed for the
variable.
• Python Support Dynamic Typing
Multiple Assignment
• Python allows Multiple assignments.
• Assign same value to multiple variables. – x = y = z =
20 – here x, y, z has same value 20

• Assign multiple values to multiple variables.


– x , y , z = 20, 40, 60
– here x, y, z has value 20, 40 and 60 respectively
Example of Multiple Assignment
Variable Definition
• Variable is created or defined when the first
value is assigned to it.
• Variable is not created until some value is
assigned to it.
Simple Input and Output
 • input( ) function is used for taking value for a variable
during runtime.

 • When dealing with numbers we face this kind of error.


Reading Numbers

 • To overcome the above error we need to convert the string type object
to integer or any desired numeric type.
 • input( ) function always returns a value of string type.
 • Use int( ) or float( ) function to convert the type string to int and float
respectively.
Possible Errors while Reading Numeric
Values
 • When converting variable to int/float we need to make sure that the
value entered is of int/float type.

 • If we enter rashmi for age then rashmi cannot be converted to int.


Output Through print Statement

 • print statement has number of features


– Automatic conversion of items to string type.
– Inserting space between items automatically as default value of sep
(separator ) is space.

– It appends a newline at the end of the each print line.


sep and end argument in print
statement
Data Types

 • Python offers five built-in core data types


– Numbers( int, float, complex)
– String
– List
– Tuples
– Dictionary
Numbers
• Integers
– Integers Signed: positive and negative integers(Whole Numbers)
– Boolean: Truth Values False(0)/bool(0) and True(1) /bool(1)
• Floating Point Numbers: precision of 15 digits possible in Python
– Fractional Form: Normal Decimal Form, e.g. 325.89, 300.845
– Exponent Notation: Represents real numbers for measurable
quantities. E.g. 3.500789E05, 1.568789E09, 0.254E-07
• Complex Numbers: Python represents complex numbers as a pair of
floating point numbers. E.g. A+Bj. J is used as the imaginary part which has
value √-1.
• a=1.6+4j real part=1.6 imaginary component=4
• b=0+5.2j real part=0 imaginary component=5.2
a.real and b.real gives the real part
a.imag and b.imag gives the imaginary part
>>>a.real
1.6
String
 • Any number of valid characters within quotation marks.
 • It can hold any type of known characters like alphabets, numbers, special
characters etc.
 • Legal String in Python are “Raman”, ‘rocket’, “we2345@”,”%&$#”
 • String as a sequence of Characters
– String is stored as individual characters in contiguous location

– Length of the string can be determined using len(string).


– Individual letter of a string cannot be changed because the String is immutable.
name=‘hello’
name*2+=‘g’ # Not Possible
name=‘Computer’ #Possible , we can assign string to another string
List
 • List in Python represents a list of comma-separated
values of any data type between square brackets.
Mutable Data Type
[1,2,3,4,5]
[‘a’, ‘b’,’c’,’d’]
[‘rat’, ‘bat’,’cat’,’dog’]
Tuples

• Tuples in Python represents a list of comma-


separated values of any data type between
round brackets. Immutable Data Type
T=(1,2,3,4,5)
A=(‘a’, ‘b’,’c’,’d’)
B=(‘rat’, ‘bat’, ‘cat’, ’dog’)
Dictionary

 • Dictionary in Python represents unordered set of


comma-separated key : value pair within { }, with the
requirement that within a dictionary, no two keys can be
the same.
A={‘a’:1, ‘b’:2,’c’:3,’d’:4}
Immutable Types
 • The immutable types are those that can never change their
value in place.
 • Immutable Data Types are
– Integer
– Floating Point Number
– Boolean
– String
– Tuples
>>>a=10 >>>print(a) 10
>>>a=20 >>>print(a) 20
Note: We see that the above code is changing the value of the
variable, values are not changing in place. Variable names are
stored as references to a value-object, each time you change the
value, the variable’s reference memory address changes.
Mutable Types
• Mutable types are those whose values can be changed
in place.
• Mutable Data Types are
– List
– Dictionary
– Sets
 • Thus Mutability means that in the same memory address
, new value can be stored as and when you want.
Expression
• Expression is the valid combination of
operators, literals and variables.
• Expression is formed by atoms and operators.
 • Atoms are something which has value. E.g.
Literals, identifier, string, list, tuples, sets and
dictionary etc.
• Types of Expression
– Arithmetic Expression: a+5-6
– Relational Expression: x>90
– Logical Expression: a>b or 6
Evaluating Arithmetic Expression:
 • During evaluation if the operand are of same data type then the resultant
will be of the data type which is common.
 • Incase, during evaluation if the operand are of different data type then the
resultant will be of the data type of the largest operand. We need to promote
all the operand to the largest type through type promotion.
 • Implicit Type Conversion/Coercion
– Implicit conversion is performed by the compiler without programmer’s
intervention.
Note:

 • Division operator will result in floating point number,


even if both operands are integer type.
Type Casting

 • Python internally changes the data type of some


operand , so that all operand have same data type. This
is called Implicit Type Conversion.
 • Explicit Type Conversion/ Type Casting: user defined
conversion that forces an expression to be of specific
type.
– Type casting is done by (expression)
• Amt= int(amount)
• Different data types are int(), float(), complex(), str(), bool()
Types of statements in Python

 • Smallest executable unit of the program.


 • These are instructions given to the computer to perform any kind
of action, data movement, decision making, repeating actions etc.
 • They are of three types
– Empty Statement: Statement which does nothing. In Python
empty statement is a pass statement.
– Simple Statement: Any single executable statement is a
simple statement.
– Compound Statement: Group of Statement executed as a
unit. It has a header line and a body
• Header line: It begins with the keyword and ends with a
colon.
• Body: consist of one or more Python statements ,indented
inside header line. All Statement are at same level of indentation.
Program to find the Eligibility for voting
if Statement
 • In Python, if Statement is used for decision making. It
will run the body of code only when IF statement is true.
 • When you want to justify one condition while the other
condition is not true, then you use "if statement".
What happen when "if condition" does
not meet
How to use "elif" condition
 • By using "elif" condition, you are telling the program to print
out the third condition or possibility when the other condition
goes wrong or incorrect.
Repetition of Tasks -- A Necessity
 There are many situations when we need to repeat certain task or
functions some given number of times or based on certain
condition.
 What is Loop?
• Loops can execute a block of code number of times until a certain
condition is met. Their usage is fairly common in programming. Unlike
other programming language that have For Loop, while loop, do
while, etc.
• To carry out repetitive task python provides following
looping/iterative statements:
– Conditional Loop while
– Counting Loop for
The range( ) Function
 • The range( ) function of Python generates a list which is special sequence
type.
 • Range function works in three forms:
Operators in and not in
 • in operator tests if a given value is contained in a sequence or not
and return True or False.
The for loop
WAP to print natural numbers from 1 to
n, n is entered by the user.
WAP to print even numbers in the
range 1 to n, n is entered by the user.
WAP to print table of n, where n is
entered by the user
The while loop

Anatomy of a while Loop


• Initialization
• Test Expression
• The Body of the Loop
• Update Expression
WAP to print natural numbers from 1 to
n, n is entered by the user
WAP to print even numbers in the
range 1 to n, n is entered by the user.
WAP to print table of n, where n is
entered by the user.
Loop Else Statement

 • Both the loops of Python has else clause. The else of a loop
executes only when the loop end normally( i.e. only when the loop
is ending because the while loop’s test condition has become false
and for loop has executed the last sequence)
 • Note: The else clause of the Python Loop executes when the loop
terminates normally, not when the loop is terminating because of
break statements.
Jump Statement

 • You might face a situation in which you need to exit a loop completely
when an external condition is triggered or there may also be a situation
when you want to skip a part of the loop and start next execution.
 • Python provides break and continue statements to handle such situations
and to have good control on your loop.
The break Statement:
 • The break statement in Python terminates the current
loop and resumes execution at the next statement
The continue Statement:
 • The continue statement in Python returns the control to the
beginning of the while loop. The continue statement rejects all the
remaining statements in the current iteration of the loop and moves
the control back to the top of the loop.
Nested Loop

 • one loop inside another loop

You might also like