Unit II: Computational Thinking and Programming - 1
Familiarization with the basics of Python programming: a simple “hello world“ program, the
process of writing a program (Interactive & Script mode),running it and print statements;
simple data-types: integer, float and string.
● Features of Python, Python Character Set, Token & Identifiers, Keywords,Literals, Delimiters,
Operators.
● Comments: (Single line & Multiline/ Continuation statements), Clarity &Simplification of
expression
● Introduce the notion of a variable and methods to manipulate it (concept of L-value and R-value
even if not taught explicitly).
● Knowledge of data types and operators: accepting input from the console,assignment statement,
expressions, operators and their precedence.
● Operators & types: Binary operatos-Arithmetic, Relational Operators,Logical Operators,
Augmented Assignment Operators.
● Execution of a program, errors- syntax error, run-time error and logicalerror.
● Conditional statements: if, if-else, if-elif-else; simple programs: e.g.:absolute value, sort 3 numbers
and divisibility of a number.
● Notion of iterative computation and control flow: for(range(),len()), while,using flowcharts,
suggested programs: calculation of simple and compound interests, finding the factorial of a
positive number etc.
● Strings: Traversal, operations – concatenation, repetition, membership; functions/methods–len(),
capitalize(), title(),
upper(), lower(), count(), find(),index(), isalnum(), islower(), isupper(), isspace(), isalpha(),
isdigit(),
split(),partition(), strip(), lstrip(), rstrip(), replace(); String slicing.
● Lists: Definition, Creation of a list, Traversal of alist. Operations on a list -concatenation, repetition,
membership; functions/methods–len(), list(),append(), extend(), insert(), count(), index(), remove(),
pop(), reverse(), sort(),min(), max(), sum(); Lists Slicing; Nested lists; finding the maximum,
minimum,mean of numeric values stored in a list;
linear search on list of numbers andcounting the frequency of elements in a list.
Python Programming language
Specialities:
Python is an interpreted, high-level, general-purpose programming language.
Created by Guido van Rossum and first released in 1991.
Python's design philosophy emphasizes code readability with its notable use of significant
whitespace.
Python is a dynamic, high level, free open source and interpreted programming language
It supports object-oriented programming as well as procedural oriented programming.
In Python, we don’t need to declare the type of variable because it is a dynamically typed
language.
Easy to code.
GUI Programming Support.
Graphical User interfaces can be made using modules such as PyQt5, PyQt4, wxPython, or
Tk in python.PyQt5 is the most popular option for creating graphical apps with Python.
Python is Portable language.
Python is Integrated language.
Python has a large standard library which provides a rich set of module and functions
Applications of Python language
used to make web-applications at a rapid rate.
used in the development of interactive games
Used in Machine Learning and Artificial Intelligence with the libraries that exist
already such as Pandas, Scikit-Learn, NumPy and so many more.
visualize the data libraries such as Matplotlib, Seaborn, which are helpful in plotting
graphs and much more.
Python can be used to program desktop applications. It provides the Tkinter library
that can be used to develop user interfaces.
Python can be used to pull a large amount of data from websites which can then be
helpful in various real-world processes such as price comparison, job listings,
research and development and much more.
Python IDLE
IDLE is a simple Integrated Development Learning Environment that comes with Python.
The most important feature of IDLE is that it is a program that allows the user
to edit, run, browse and debug a python program from a single interface.
The interactive interpreter of Python is termed as Python shell. Python IDLE comprises :
Python shell(Interactive mode) and
Python Editor(Script mode).
Python Shell(Interactive mode)
The interactive mode involves running your codes directly on the Python shell which
can be accessed from the terminal of the operating system,
Python is an interpreter language.
Python provides a Python Shell (also known as Python Interactive Shell) which is
used to execute a single Python command and get the result.
Python Shell waits for the input command from the user.
As soon as the user enters the command, it executes it and displays the result.
Python script mode(Editor mode)
In the script mode, you have to create a file, give it a name with a . py the extension
then runs your code.
The file option contains options to create new file by clicking New File option. A new
window opens which is python editor where you can type or edit your code.
After typing the code save the file in the format filename.py.
To execute a Python Script file, we have to choose the ‘Run module ‘ option from the
Run menu( F5)
Tokens or Lexical units
Individual elements that are identified by programming language are called tokens
or lexical unit.
They are as follows:
Keyword:
Keywords are also called as reserved words these are having special meaning in
python language.
The words are defined in the python interpreter hence these cant be used as
programming identifiers. Eg: int,and,or,list etc
Identifier
A Python Identifier is a name given to a function, class, variable, module, or
other objects in Python program.The identifier is only used to identify an entity
uniquely in a program at the time of execution whereas, a variable is a name given to
a memory location, that is used to hold a value. Variable is only a kind of identifier,
other kinds of identifiers are function names, class names, structure names, etc.
Python naming conventions:
An identifier can be a combination of uppercase letters, lower case letters, underscores, and
digits (0-9). Following are valid identifiers: myClass, my_variable, var_1, and
print_hello_world.
The first character must be letter.
Special characters such as %, @, and $ are not allowed within identifiers.
An identifier should not begin with a number.
Python is a case-sensitive language and this behaviour extends to identifiers.
Example: Labour and labour are two distinct identifiers in Python.
You cannot use Python keywords as identifiers.
You can use underscores to separate multiple words in your identifier.
Literals
Literals are also called as constants or constant values .These are the values which never
change during the execution of program.
Types of literals
1) String Literals or Constants.
2) Numeric Literals or Constants.
3) Boolean Literals or Constants.
4) Special Literal None.
5) Literal Collections.
String literals :Sequence of letters enclosed in quotes is called string or string literal or
constant.Python supports both form of quotes i.e. ‘Hello’ “Hello”
Python supports two ways of representation of strings:
1) Single Line Strings.
2) Multi Line Strings.
Strings created using single quote or double quote must end in one line are called single line
strings For Example: Item=“Computer” (Or) Item= ‘Computer’ Strings created using
single quote or double quote and spread across multiple lines are called Multi Line Strings.
By adding backslash \ one can continue to type on next line. For instance: Item =
Key\ board’
ESCAPE SEQUENCES: Escape sequences allow you to include special characters in strings. To
do this, simply add a backslash ( \ ) before the character you want to escape.
Symbol Description Example Output
\\ Prints Backslash print "\\" \
\` Prints single-quote print "\'" '
\" Pirnts double quote print "\"" "
\a ASCII bell makes ringing the bell alert sounds ( eg. xterm ) print "\a" N/A
\b ASCII backspace ( BS ) removes previous character print "ab" + "\b" + "c" ac
\f ASCII formfeed ( FF ) print "hello\fworld" hello
world
\n ASCII linefeed ( LF ) print "hello\nworld" hello
World
Python integer literals
Any non-negative literals of the type integer, decimal, hexadecimal, octal and binary literals
belong to integer numeric literals. Some example of integer literals are: 121(integer) ,
100111(binary), 0xdeaebf(hexadecimal), 0o561(octal).
Python floating point literals
Any non-negative real number with fraction belong to floating point literals.
A floating point literals can also have an exponent form represented by the ‘e‘ character.
Unlike the integer literals, they can have leading zero. Underscore are also allowed in
floating point literals.
Python supports literal collections also such as tuple and lists ..etc It will be to
complex to discuss as we are in the beginning, subsequent chapters we will cover literal
collections.Boolean literals: True and False (not literals in older (2.x) Python versions)
Operator
Operators are tokens that trigger some computation when applied to a variable.
Punctuators are also called as separators
The Followings are used as punctuators:
Brackets [ ]
Parentheses ( )
Braces { }
Comma ,
Semicolon ;
Colon :
Asterisk *
Ellipsis …
Equal Sign =
Pound Sign #
COMMENTS : Comments are non executable statements in a program.
Single line comment always starts with # Multiline comment will be in triple quotes. For
example “’ write a program to find the simple interest “’.
Note: Triple apostrophe is called docstrings.
PYTHON PROGRAMMING CONVENTIONS
Statement Termination: python does not use any symbol to terminate the statement.
Maximum Line Length: Line Length be maximum 79 characters. Whitespaces: You should
always have whitespace around operators but not with parenthesis. Block or Code Block: A
group of statements which are part of another statement or function is called Block or Code
Block. Case Sensitive: Python is case sensitive.
Variables in Python
Variables are reserved memory locations to store values. Based on the data type of a
variable, the interpreter allocates memory and decides what can be stored in the reserved
memory.
VARIABLES AND ASSIGNMENTS
Multiple Assignments
Python is very versatile with assignment statements.
Assigning same value to multiple variables:
a=b=c=d=e=10
Dynamic Typing:
A variable pointing to a value of certain type can be made to point to a
value/object of different type this is called Dynamic Typing.
x=10
print(x)
x=“ Hello World”
print(x)
Input( ) Function
Input( ) Function is a built in function of python used to read values from the user
The general format or syntax of the input() is:
Variable=input(message)Where,variable is the label for a memory location where
the value is stored.For Example: marks=input(‘Enter the marks’)
p = input(“Enter the value”)
x = int(input(“Enter x value”))reads the value and converts it in to integer type
data or value. y=float(input(“Enter y value”))reads the value and converts it in to float type
data or value.
print( ) Function
print( ) Function is a built in function of python used to display the values on the
screen The general format or syntax of the print() is:
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
The print function can print an arbitrary number of values ("value1, value2, ..."), which are
separated by commas. These values are separated by blanks.
Eg:
print("Python is fun.")
a=5
#Two objects are passed:
print("a =", a)
b=a
# Three objects are passed:
print('a =', a, '= b‘)
Output
Python is fun.
a=5
a=5=b
Formats of different print functions in python
print()->Prints a blank line.
print(values/expression)->print an expression which can be value or string.
3. print(val1,val2,val3,sep=‘ ‘,end=‘\n’)
Example:print (5,10,20,sep='@',end='%’)
output : 5@10@20%
4. print function using format specifiers:
print(‘string%d,%f,%s’%val1,val2,val3)
Example:print('The values are%d,%f,%s'%(25,2.5,'computer science’))
The values are25,2.500000,computer science
5.print using width specifiers:
print(‘string%5d,%2.3f,%s’%val1,val2,val3)
example: print('%5d,%2.3f,%s'%(4567892,456789.7896,"computer"))
output: 4567892,456789.790,computer
6. print statement using format operator:
syntax:print( string{x }.format(x=value))
example: print('I like {x}programming language'.format(x='Python’))
output:I like Pythonprogramming language
Object oriented programming: An object-oriented programming (OOP) is a programming
language model which is organized around "objects" rather than "actions" and data rather
than logic.
A program was viewed as a logical procedure that takes input data, processes it, and
produces output. But in case of OOP a problem is viewed in terms of objects rather than
procedure for doing it.
The basic concepts related to OOP are as follows:
1. Objects
2. Classes
3. Encapsulation
4. Abstraction
5. Data Hiding
6. Polymorphism
7. Inheritance
Objects
An object is the basic key concept of Object Oriented Programming. it can be anything
around us - a person, place, any activity or any other identifiable entity.
Class A class is group of objects with same attributes and common behaviours.
EncapsulationIt is the combining of data and the functions associated with that data in a
single unit. In most of the languages including python, this unit is called a class
. Data hiding can be defined as the mechanism of hiding the data of a class from the outside
world or to be precise, from other classes.
. Abstraction The process of identifying and separating the essential features without
including the internal details is abstraction.
Inheritance is one of the most useful characteristic of object-oriented programming as it
enforces reusability of code.
Polymorphism is the ability to use an operator or function in various forms.
Operators in Python Operators are symbols that triggers an operation
Arithmetic operators
Arithmetic operators are used to perform mathematical operations like addition,
subtraction, multiplication, etc.
Operato
Meaning
r
+ Add two operands or unary plus
- Subtract right operand from the left or unary minus
* Multiply two operands
/ Divide left operand by the right one (always results into float)
% Modulus - remainder of the division of left operand by the right
Floor division - division that results into whole number adjusted to the left in the
//
number line
** Exponent - left operand raised to the power of right
Comparison operators
Comparison operators are used to compare values. It returns either True or False according
to the condition.
Operator Meaning
> Greater than - True if left operand is greater than the right
< Less than - True if left operand is less than the right
== Equal to - True if both operands are equal
!= Not equal to - True if operands are not equal
>= Greater than or equal to - True if left operand is greater than or equal to the right
<= Less than or equal to - True if left operand is less than or equal to the right
Logical operators are the and, or, not operators.
Operator Meaning
and True if both the operands are true
or True if either of the operands is true x
not True if operand is false (complements the operand) n
Bitwise operators
Bitwise operators act on operands as if they were strings of binary digits. They operate bit
by bit, hence the name.
For example, 2 is 10 in binary and 7 is 111.
In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)
Operator Meaning Example
& Bitwise AND x & y = 0 (0000 0000)
| Bitwise OR x | y = 14 (0000 1110)
~ Bitwise NOT ~x = -11 (1111 0101)
^ Bitwise XOR x ^ y = 14 (0000 1110)
>> Bitwise right shift x >> 2 = 2 (0000 0010)
<< Bitwise left shift x << 2 = 40 (0010 1000)
Assignment operators
Assignment operators are used in Python to assign values to variables.
a = 5 is a simple assignment operator that assigns the value 5 on the right to the variable a
on the left.
Operator Example Equivalent to
= x=5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x–5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x%5
//= x //= 5 x = x // 5
**= x **= 5 x = x ** 5
&= x &= 5 x=x&5
|= x |= 5 x=x|5
^= x ^= 5 x=x^5
>>= x >>= 5 x = x >> 5
<<= x <<= 5 x = x << 5
Identity operators
is and is not are the identity operators in Python. They are used to check if two values (or
variables) are located on the same part of the memory. Two variables that are equal does
not imply that they are identical.
Operator Meaning Example
is True if the operands are identical (refer to the same object) x is True
is not True if the operands are not identical (do not refer to the same object) x is not True
Membership operators
in and not in are the membership operators in Python. They are used to test whether a
value or variable is found in a sequence (string, list, tuple, set and dictionary).
In a dictionary we can only test for presence of key, not the value.
Operator Meaning Example
in True if value/variable is found in the sequence 5 in x
not in True if value/variable is not found in the sequence 5 not in x
Operator Preceden
Precedence represents the priority of evaluation of operators in an expression.
~+- ->Complement,unary plus and minus
* / % // ->multiply,divide,modulo,floor division
+- ->addition ,subtraction
<< >> ->right and left bitwise shift
& ->bitwise and
^| ->bitwise exclusive or and regular or
<= >= > < ->comparison operators
== != ->equality operators
= ->Assignment operator
is is not ->identity operators
in not in ->membership operators
not or and ->logical operators
CONTROL CONSTRUCTS
Control constructs are statements that determine the flow of execution of the program.
Flow of control through any given function is implemented with three basic types of control
structures:
Sequential: default mode. ...
Selection: used for decisions, branching -- choosing between 2 or more alternative paths. ...
Repetition: used for looping, i.e. repeating a piece of code multiple times in a row.
Sequence construct
Sequence is the default control structure; instructions are executed one after another.
Statement 1
Statement 2
Statement 3
……..
……..
……..
Selection construct
A selection statement causes the program control to be transferred to a specific flow based
upon whether a certain condition is true or not.
The selection constructs used in Python are:
1. if statement
2. if …else statement
3. if…elif statement
if statements Conditional constructs (also known as if statements) provide
a way to execute a chosen block of code based on the run-time evaluation of one or more
Boolean expressions. The general form of a conditional construct is written
as follows:
if(condition):
statements
Example: a = 33
b = 200
if b > a:
print("b is greater than a")
if-else Statement
The if-else statement is used to code the same way you would use it in the English language.
The syntax for the if-else statement is:
if(condition):
Indented statement block for when condition is TRUE
else:
Indented statement block for when condition is FALSE
Example:
score_theory = 40
score_practical = 45
if(score_theory + score_practical > 100):
print("Please check the input. Score exceeds total possible score.")
else:
print("Score validated. Your total is: ", score_theory + score_practical)
Python if...elif...else Statement
Syntax of if...elif...else
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
The elif is short for else if. It allows us to check for multiple expressions.If the condition for if
is False, it checks the condition of the next elif block and so on.If all the conditions are False,
the body of else is executed.Only one block among the several if...elif...else blocks is
executed according to the condition.The if block can have only one else block. But it can
have multiple elif blocks.
Example of if...elif...else
num = 3.4
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
--------------------------------------------------------------------------------------