UNIT 2:
COMPUTATIONAL THINKING AND
PROGRAMMING - I
Chapter 2:
Familiarization with the basics of Python
programming
OR
Python Fundamentals
CHARACTER SET
Character Set-is a group of letters or signs which are specific to a
language.
Character set includes letters, sign, numbers, symbols.
Letters:A-Z, a-z
Digits:0-9
Special Symbols:_, +, -, *, /, (, ), {, }...Etc.
White Spaces: blank space, tab, carriage return, newline, formfeed etc.
Other characters:Python can process all characters of UNICODE.
TOKENS
Token- is the smallest unit of any programming
language. It is also known as Lexical Unit.
TYPES OF TOKENS
• Keywords
• Identifiers
• Literals
• Operators
• punctuators
KEYWORDS
• Keywords are those words which provides a special meaning to
interpreter
• These are reserved for specific functioning
• These cannot be used as identifiers ,variable names or any other
purpose
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.
Rules of Identifiers
• An identifier may be a combination of letters and numbers.
• An identifier must begin with an alphabet or an underscore (_).
• Subsequent letters may be numbers(0-9).
• Python is case sensitive. Uppercase characters are distinct from lowercase
characters (P and p are different for interpreter).
• Length of an Identifier is unlimited.
• Keywords can not be used as an identifier.
• Space and special symbols are not permitted in a identifier name except an
underscore(_) sign.
EXAMPLES FOR VALID AND INVALID
IDENTIFIERS
• Myfile
• Document5
• 67file
• _bank
• Break
• If
• [Link]
• Data-rec
• _98file
LITERALS/CONSTANTS
Python permits following types of literals :-
• String literals-"Pankaj"
• Numeric literals -10, 13.5, 3+5i
• Boolean literals -True or False
• Special Literal -None
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.
• In python, string is of 2 types-
Single line string
• Text = "Hello World" or Text = 'Hello World'
Multi line string
• Text = 'hello\ world’
or
• Text =‘’’hello
word”’
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, 0x2A4, 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
A= True
B=False
SPECIAL LITERALS
None, which means nothing (no value).
X = None
VARIABLES IN PYTHON
• Variable is a name given to a memory location.
• In Python, there is no need to specify the
datatype of variable.
• Python automatically get variable datatype
depending upon the value assigned to the
variable.
VARIABLES ARE NOT STORAGE
CONTAINERS IN PYTHON
• Memory has values at defined memory locations,
and each memory location has a memory address.
When you give statement rank = 25, variable rank will be
created as a label pointing to memory location where
value 25 is stored
And when you give rank=30, the label rank will not
having the same location as earlier.
It will now refer to value 30, which is at different
location.
ASSIGNING VALUES TO VARIABLE
sub = 'python' # String Data Type
var = None # a variable without value
a1 = 23 # Integer
b2 = 6.2 # Float
MULTIPLE ASSIGNMENT
Assigning same value to multiple variables
a = b = c = 1 # single value to multiple variable
Assigning multiple values to multiple variables
a, b = 1, 2 # multiple value to multiple variable
a,b = b,a # value of a and b is swapped
DYNAMIC TYPING
Data type of a variable depend/change upon the value assigned to a
variable on each next statement
x = 65 # integer type
X = "Python" # x variable data type change to string on just next line
Now programmer should be aware that not to write like this:
Y = X / 5 # error!! String cannot be divided.
QUESTIONS BASED ON PYTHON
FUNDAMENTALS
1. What is the difference between a keyword and an identifier ?
2. How many strings are supported in Python ?
3. What are the rules to declare an identifier?
4. What is the error in the following Python Program with one
statement
print("My Name is: ",name)
5. What will be the output of the following code :
x, y = 2, 6
x, y = y, x + 2
print(x,y)
6. Predict the output of the following :
x, y = 7, 2
x, y, x = x + 1, y + 3, x + 10
print(x,y)
7. From the following, find out which assignment statement will produce error.
State reasons too.
(i) x = 55
(ii) y = 037
(iii) z=0o98
(iv) 56thNumber
(v) length = 450.17
vi) !Taylor = 'Instant’
(vii) this variable = 8.7E02
(viii) float = 017E-03
INPUT()
• input() function is used to take input from a user.
• Input function always returns a value of string type.
Syntax:
Variable To Hold Value = input (<prompt to be displayed>)
PRINT()
• print() function is used to display a string on the console.
Syntax:
print(objects, [sep=' ' or <separator string> end='\n' or <end string>)
FEATURES OF PRINT()
• It auto-converts the items into string
• It inserts spaces between items automatically because
default value of sep argument is space.
• It appends a new line character at the end of a line unless
you give your own end argument.
OPERATORS
OPERATORS AND OPERANDS
The symbols that trigger the action /operation on data, are called
Operators.
The data on which operation is being carried out are called
Operands.
ARITHMETIC OPERATOR
RELATIONAL OPERATOR
LOGICAL OPERATOR
IDENTITY OPERATOR
There are few cases where Python creates two different objects that
both store the same value. These are:
• Input of string from the console.
• Very big integers.
• Writing floating point and complex numbers.
MEMBERSHIP OPERATOR
AUGMENTED ASSIGNMENT OPERATOR
BITWISE OPERATOR
Operators Description
Parentheses
Exponentiation
Positive, Negative
Multiplication, Division, Floor Division, Remainder
Addition, Subtraction
Comparison and Identity Operators
Logical NOT
LOGICAL AND
Logical or
DATA HANDLING IN PYTHON
DATA TYPES
• Data type in Python specifies the type of data we
are going to store in any variable and the type of
operation we can perform on a variable. Data can
be of many types e.g. character, integer, real, string
etc.
IMMUTABILITY VS MUTABILITY
Immutable Data types Mutable Data Types
The immutable types are Change their value in place.
those that can never change E.g.
their value in place. • List
E.g. • Dictionary
• Integers
• Floating Point Numbers
• Booleans
• Strings
• Tuples
DATA TYPES IN CLASS 11 AND 12:
• Numbers (int, float, complex)
• String
• List
• Tuple
• Dictionary
NUMBERS
Number data types are used to store
numeric values.
Numbers in Python can be of following
types:
• Integers
• Integers(signed)
• Booleans
• Floating point numbers
• Complex Numbers
INTEGERS
• Integers allows to store whole numbers only. They have no
fractional parts.
• Integers can be positive and negative e.g. 100, 250, -12, +50
TYPES OF INTEGERS
1) Integers(signed): it is normal integer representation of whole numbers.
Integers in python can be on any length, it is only limited by memory
available. In Python int data type can be used to store big or small
integer value whether it is +ve or -ve.
2) Booleans: it allows to store only two values True and False.
The internal value of Boolean value True and False is 1 and o resp.
We can get Boolean value from o and 1 using bool() function.
FLOATING POINT NUMBERS
It allows to store numbers with decimal points. For e.g. 2.14. The decimal point indicate that
it is not an integer but a float value. 100 is an integer but 100.5 is a float value.
1. Fractional Form: 200.50, 0.78, -12.787
2. Exponent Form: it is represented with mantissa and exponent.
5.67 X 103
Mantissa = 5.67
Exponent = 3
Floating point numbers have two advantage over integers:
• they can represent values between the integers.
• they can represent a much greater range of values.
But floating point numbers suffers from one disadvantage also:
• Floating point operations are usually slower than integer
operations.
COMPLEX NUMBERS
Python represent complex numbers in the form A + Bj . To represent
imaginary numbers, Python uses j or J in place of i.
e.g.
a = o + 6j
b = 2.5 + 3J
>>> a = 4 + 5j
>>print (a) # (4 + 5j)
>> b = 0 + 2j # (2j)
• Python allows to retrieve real and imaginary
• part of complex number using attributes:
real and imag
• If the complex number is a then we can write
[Link] or [Link]
Example
>>>a=1+3.54j
>>>print([Link]) #1.0
>>>print([Link]) #3.54
STRING
1. String is a collection of any valid characters in a quotation marks
(‘ or " or ‘’’ or """)
2. Each character of String in Python is a Unicode character.
3. Strings are used to store information like name, address,
descriptions. Etc
For example:
"hello", “””welcome”””, ”world” etc..
FLOW OF CONTROL
STATEMENTS
Statements are the instructions given to the
computer to perform any kind of action.
EMPTY STATEMENT
• Empty statement is a statement that does nothing.
• Represented by a keyword pass.
• Useful in those cases, where the syntax of a
language requires the presence of a statement but
where the logic of the program does not.
SIMPLE STATEMENT
• Any single executable statement is a statement in
Python.
• Example:
Name=input("Enter your name:")
print(Name)
COMPOUND STATEMENT
• A compound statement represents a group of
statements executed as a unit.
• <compound statement header> :
<indented body containing single
or compound statements >
STATEMENT FLOW CONTROL
• Flow of control means to determine
the next statement to be executed.
It can be
• Sequential
• Selection
• Iteration
SEQUENTIAL
SELECTION
EXAMPLES
• If the age of a person is above 18, then he/she is eligible for
Voting.
• If the total percentage of a student is above 33, then he/she is
eligible to take admission in next class.
• If traffic Signal is light is Red, STOP ..... For Yellow, WAIT...... For
Green.... GO...
ITERATION
• The iteration construct means repetition of statements depending
upon a condition test.
• The statements will be executed till the condition is True.
• As soon as the condition becomes False, the repetition stops.
IF STATEMENTS
• The if statements are conditional statements in Python
and these implement Selection Constructs or
Decision Constructs.
• The simplest form of if statement tests a condition
and if the condition evaluates to True, it carries out
some instructions and does nothing in case condition
evaluates to False.
SYNTAX AND FLOWCHART OF
IF STATEMENT
if < conditional expression> :
statements to be executed
………………………….
………………………….
FOR ANY NON ZERO VALUES
FOR ZERO VALUES
IF - ELSE STATEMENT
This form of if statement tests a condition and if
the condition evaluates to True, it carries out the
statements indented below and in case, condition
evaluates to False, it carries out statements
indented below else.
SYNTAX AND FLOWCHART OF IF ELSE
STATEMENT
EXAMPLE
IF - ELIF STATEMENT
If out of multiple statements, it is
required to select one statement for
processing on the basis of a condition,
if-elif statement is to be used.
SYNTAX
FLOW CHART
EXAMPLE
NESTED - IF STATEMENT
A nested if is an if that has another if in it's if's
body or in else's body.
SYNTAX
EXAMPLE
PRACTICE PROGRAMS
• To check the given number is greater than 200 using if statement
• To check the given number is greater than 200 using if else statement
• To find positive or negative number using if else statement
• To print positive difference of two numbers using if else statement
• To find positive or negative number or zero using if elif statement
• To display the name of the day according to the number given by the user using if elif statement
• To read two numbers and an arithmetic operator and display the result using
if elif statement
• To display appropriate message as per the colour of signal at the road crossing using if elif statement
ITERATION /LOOPING
• The iteration statements or repetition statements
allow a set of instructions to be performed
repeatedly until a certain condition is fulfilled.
• The iteration statements are also called as Loops
or Looping Statements.
WHILE LOOP
A while loop is a conditional loop that will repeat
the instructions within itself as long as the condition
remains True.
A WHILE LOOP HAS FOUR ELEMENTS
THAT HAVE DIFFERENT PURPOSES
• Initialization Expression
• Test Expression
• Body of loop
• Update of expression
SYNTAX AND EXAMPLE
INFINITE LOOP / ENDLESS LOOP
An infinite loop is a looping construct that
does not terminate the loop and executes
the loop forever.
RANGE() FUNCTION
• range() function returns a sequence of numbers,
starting from 0 by default, increments by 1 (by default), and
stops before a specified number.
Start - Optional Argument. An integer number specifying at which
position to start. Default is 0.
Stop- Required Argument. An integer number specifying at which
position to stop. Last value not included.
Step- Optional Argument. An integer number specifying the
incrementation. Default is 1.
FOR LOOP
The for loop of a Python is designed to process the items
of any sequence, such as a list or a string, one by one.
Start = 0 (by Default)
Stop = 5 (not included)
Step - 1 (be default)
• The loop - variable is assigned a first value in a sequence.
• All the statements in the body of for loop are executed with
assigned value of loop variable.
• Once step 2 is over, the loop variable is assigned a next value in
the sequence, and the loop body is executed, with new value of
loop variable.
• This continues until all the values in the sequences are processed.
JUMP STATEMENTS AND LOOP ELSE
CLAUSE
Python offers two jump statements to be used within
loops to jump out of loop iterations.
• break
• continue
SYNTAX
SYNTAX USING FOR LOOP
BREAK STATEMENT
• The break statement enables a program skip over a part of the
code.
• A break statement terminates the loop it lies within.
• Execution resumes at the statement immediately following the
body of terminated statement.
CONTINUE STATEMENT
• Instead of forcing termination, the continue statement forces the next
iteration of the loop to take place, skipping any code in between.
• The continue statement skips the rest of the loop statements and causes the
next iteration of the loop to take place.
SYNTAX USING WHILE AND FOR LOOP
EXAMPLE USING FOR LOOP
DIFFERENCE BETWEEN BREAK AND CONTINUE
LOOP ELSE STATEMENT
The else clause of a Python loop executes only when the loop
ends normally, not when the loop is terminating because of a
break statement.
SYNTAX
EXAMPLE 1
EXAMPLE 2