Introduction To Programming
Introduction To Programming
Computer Programming I
1 1
Contents
What is python
Why learn python
Where is python used
Python popular framework and libraries
Python basic syntax
Python Data Type
Data Type Conversion
2
What is python?
Python is a simple, general purpose, high level, and object-
oriented programming language.
Guido Van Rossum is the founder of Python programming.
Python is an interpreted language, which means
Code is executed line-by-line and does not need to be compiled
before running.
This makes it easy to write, test, and debug code.
Python is also cross-platform means
It can run on a variety of operating systems, including Windows,
macOS, and Linux.
3
Cont’d
Python is an easy-to-learn yet powerful and versatile language, which
makes it attractive for Application Development.
Python makes development and debugging fast because no
compilation step is included, and edit-test-debug cycle is very fast.
In Python, code readability and maintainability are important.
As a result, even if the code was developed by someone else, it is
easy to understand and adapt by some other developer.
4
Why learn python ?
Python provides many useful features to the programmer. These
features make it the most popular and widely used language.
Easy to use and Learn: Python has a simple and easy-to-understand syntax,
unlike traditional languages like C, C++, Java, etc., making it easy for
beginners to learn.
Object-Oriented Language: It supports object-oriented
programming, making writing reusable and modular code easy.
Learn Standard Library: Python's standard library contains many
modules and functions that can be used for various tasks, such as
string manipulation, web programming, and more.
5
Cont’d
Open Source Language: Python is open source and free to use, distribute
and modify.
6
Where is Python used?
Data Science: Data Science is a vast field, and Python is an
important language for this field because of its simplicity, ease of use,
and availability of powerful data analysis and visualization libraries
like NumPy, Pandas, and Matplotlib.
Artificial Intelligence: AI is an emerging Technology, and Python is a
perfect language for artificial intelligence and machine learning
because of the availability of powerful libraries such as TensorFlow,
Keras, and PyTorch.
Machine Learning: Python is widely used for machine learning due to
its simplicity, ease of use, and availability of powerful machine
learning libraries.
7
Cont’d
Computer Vision or Image Processing Applications: Python can be used for
computer vision and image processing applications through powerful libraries
such as OpenCV and Scikit-image.
Education: Python's easy-to-learn syntax and availability of many resources
make it an ideal language for teaching programming to beginners.
Software Development: Python is considered one of the best software-making
languages. Python is easily compatible with both from Small Scale to Large
Scale software.
8
Python Popular Frameworks and Libraries
Machine Learning - TensorFlow, PyTorch, Scikit-learn, Matplotlib, Scipy, etc.
9
Basic Syntax
There is no use of braces or semicolon in Python. It is English-like
language.
But Python uses indentation to define a block of code.
Indentation is nothing but adding whitespace before the statement
when it is needed. For example -
def func():
statement 1
statement 2
…………………
…………………
statement N
10
Cont’d
statements that are same level to the right belong to the function.
Generally, we can use four whitespaces to define indentation.
For example, 'name' and 'Name' are two different variables in Python.
11
Python Comment
comment is programmer-readable explanation in Python source code.
They are added with the purpose of making the source code easier for
humans to understand, and are ignored by Python interpreter.
12
Cont’d
In Python, comments can be added using the '#' symbol. Any text written after
'#' symbol is considered a comment and is ignored by the interpreter.
A hash sign (#) that is not inside a string literal begins a comment.
All characters after the # and up to end of the physical line are part of
comment and Python interpreter ignores them.
13
Identifier
Is a name used to identify a variable, function, class, module or other
object.
14
Cont’d
Here are naming conventions for Python identifiers −
Python Class names start with an uppercase letter. All other identifiers start with a lowercase
letter. Example: Class Car.
Starting an identifier with a single leading underscore indicates that the identifier is private
identifier. Example def _get_birth_year(self):
Starting an identifier with two leading underscores indicates a strongly private identifier.
Example _ _age, _Person_ _age
If the identifier also ends with two trailing underscores, the identifier is a language-defined
special name. Example _ _str_ _
15
Reserved Words
The following list shows the Python keywords.
These are reserved words and you cannot use them as constant or
variable or any other identifier names.
16
Lines and Indentation
Python provides no braces to indicate blocks of code for class and
function definitions or flow control.
Blocks of code are denoted by line indentation
The number of spaces in the indentation is variable, but all
statements within the block must be indented the same amount.
For example −
if True:
print ("True")
else:
print ("False")
17
Multi-Line Statements
Statements in Python typically end with a new line.
Python does, however, allow the use of the line continuation character (\) to denote
that the line should continue.
For example −
total = item_one + \
item_two + \
item_three
Statements contained within the [], {}, or () brackets do not need to use the line
continuation character. For example following statement works well in Python −
days = ['Monday', 'Tuesday', 'Wednesday','Thursday', 'Friday']
18
Quotations
Python accepts single ('), double (") and triple (''' or """) quotes to denote string
literals, as long as the same type of quote starts and ends the string.
The triple quotes are used to span the string across multiple lines.
word = 'word "
sentence = "This is a sentence. "
paragraph = """This is a paragraph. It is made up of multiple lines and
sentences.""“
Multiple Statements on a Single Line
The semicolon ( ; ) allows multiple statements on the single line given that neither
statement starts a new code block. Here is a sample snip using the semicolon −
import sys; x = 'foo’; sys.stdout.write (x + '\n’)
19
Variables
Are reserved memory locations used to store values in Program.
When you create a variable you reserve some space in the memory.
The operand to the left of the = operator is the name of the variable
and the operand to the right of the = operator is the value stored in
counter = 100 # Creates an integer variable
the variable. For example − miles = 1000.0 # Creates a floating point
variable name = "Zara Ali" # Creates a string
variable
20
Printing Variables
Once we create a Python variable and assign a value to it, we can print it using
print() function.
Following is the extension of previous example and shows how to print different
variables in Python: A variable is a name that refers to a value which is used to
refer to the value later
x=3
counter = 100 # integer message = ‘hello’
variable Programmers get to choose the names of the variables
miles = 1000.0 # floating point You can change the contents of a variable in a later statement
name = "Zara Ali" # string Rules
print (counter) Must start with a letter or underscore _
print (miles) Must consist of letters and numbers and underscores
print (name) Case Sensitive
Good: spam eggs spam23 _speed
Bad: 23spam #sign var.12
21
Different: spam Spam SPAM
Multiple Assignment
Python allows you to assign a single value to several variables
a = b = c = 100
print (a)
print (b)
print (c)
Here, an integer object is created with the value 1, and all three
variables are assigned to the same memory location. You can also
assign multiple objects to multiple variables.
a = b = c = 100
print (a)
print (b)
print (c)
22
Variable Names
There are rules which should be taken care while naming variable:
A variable name must start with a letter or the underscore character
A variable name cannot start with a number or any special character like
$, (, * % etc.
A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
Python variable names are case-sensitive which means Name and NAME
are two different variables in Python.
Python reserved keywords cannot be used naming the variable.
23
Cont’d
Local Variable
Defined inside a function.We can not access variable outside function.
A Python functions is a piece of reusable code: Example
def sum(x,y): x=5
sum = x + y y = 10
return sum def sum():
print(sum(5, 10)) sum = x + y
return sum
print(sum())
Global Variable
24
Named Constants
They are similar to variables: a memory location that’s been given a
name.
>>> PI = 3.14
Literals
Literal/unnamed constant/magic number: not given a name, the
value that you see is literally the value that you have.
17
x +17
Sentences or Lines
26
Assignment statement
An assignment statement assigns a value to a variable
Basic Form
<variable> = <expr>
We assign a value to a variable using the assignment statement (=)
An assignment statement consists of an expression on the right hand side and a
variable to store the result
27
Numeric Expressions
Because of the lack of mathematical symbols on
Asterisk is multiplication
28
Cont’d
>>> xx = 2
>>> >>> print xx >>> jj = 23
4 >>> kk = jj % 5
>>> yy = 440 * 12 >>> print(kk)
>>> print(yy) 3
5280 >>>print(4 ** 3)
>>> zz = yy / 1000 64
>>> print(zz)
xx = xx + 2
5
29
Order of Evaluation
When we string operators together - Python must know
which one to do first
x = 1 + 2 * 3 - 4 / 5 ** 6
30
Operator Precedence Rules
Highest precedence rule to lowest precedence rule
Parenthesis are always respected
32
What does “Type” Mean?
In CS and programming, data type(simply type) is a classification of
data which tells the compiler or interpreter how the programmer
intends to use the data.
Example: Boolean(true or false), string(“hello”,”ABC”), int(1,2,5)
Python Data Types are used to define the type of a variable.
It defines what type of data we are going to store in a variable.
The data stored in memory can be of many types.
Number objects are created when you assign value. For example:
var1 = 1
var2 = 10
var3 = 10.023
33
Cont’d
34
Types in Python
35
String Data Type
Strings are contiguous set of characters represented in quotation marks.
Python allows for either pairs of single or double quotes.
The plus (+) sign is string concatenation operator and asterisk (*) is
repetition operator in Python.
str = 'Hello World!’
36
Python Boolean Data Types
Python Boolean type is one of built-in data types which represents one of the two
values either True or False.
Python bool() function allows you to evaluate the value of any expression and returns
either True or False based on the expression.
Examples
This produce the following result
a = True # display the value of a true
<class 'bool'>
print(a) # display the data type of a
print(type(a))
37
Several Types of Numbers
Numbers have two main types
Integers are whole numbers: -14, -2, 0, 1,
100, 401233 >>> xx = 1
>>> type (xx)
Floating Point Numbers have decimal parts: <type 'int'>
-2.5 , 0.0, 98.6, 14.0 >>> temp = 98.6
>>> type(temp)
There are other number types - they <type 'float'>
38
Mixing Integer and Floating
39
Type Matters
40
Python Data Type Conversion
To convert data between different Python data types, you simply use
the type name as a function.
Conversion to int
print (a)
print (b)
print (c)
42
List Data Type
Lists are the most versatile compound data types.
Contains items separated by commas and enclosed within square brackets [].
Values stored in a Python list can be accessed using slice operator ([ ] and [:]) with
indexes starting at 0 in the beginning of the list and working their way to end -1.
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john’]
print (list) # Prints complete list
print (list[0]) # Prints first element of the list
print (list[1:3]) # Prints elements starting from 2nd till 3rd
print (list[2:]) # Prints elements starting from 3rd element
print (tinylist * 2) # Prints list two times
print (list + tinylist) # Prints concatenated lists
43
Python Tuple Data Type
Tuple is another sequence data type that is similar to a list.
Tuple consists of a number of values separated by commas.
44
Cont’d
Example
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john’)
print (tuple) # Prints the complete tuple
print (tuple[0]) # Prints first element of the tuple
print (tuple[1:3]) # Prints elements of the tuple starting from 2nd till 3rd
print (tuple[2:]) # Prints elements of the tuple starting from 3rd element
print (tinytuple * 2) # Prints the contents of the tuple twice
print (tuple + tinytuple) # Prints concatenated tuples
45
Python Ranges
Python range() is an in-built function in Python which returns a sequence of numbers
starting from 0 and increments to 1 until it reaches a specified number.
We use range() function with for and while loop to generate a sequence of numbers.
Following is the syntax of the function:
range(start, stop, step)
Here is the description of the parameters used:
start: Integer number to specify starting position, (Its optional, Default: 0)
stop: Integer number to specify starting position (It's mandatory)
step: Integer number to specify increment, (Its optional, Default: 1)
46
Python Ranges
Examples
47
Boolean Expressions
<class 'bool'>
True
False
48
Boolean Expressions
Boolean expressions are expressions that evaluate to one of two Boolean values: True or
False. >>> 2 <3
Some languages use 0 or 1 True
>>> 3 <2
Others have a data type
False
Python has literals True and False >>> 5 -1>2+1
>>> 3 <= 4 True
True >>> 3 == 3
>>> 3 >= 4 True
False >>> 3 + 5 == 4 + 4
>>> 3 != 4 True
True >>> 3 == 5 - 3
49 False
Comparison operators
True
False
50
Logical Operators
Boolean expressions can be combined together using Boolean
operators and, or, and not to form larger Boolean expressions.
Boolean Expressions
>>> 2 < 3 and 4 > 5
False
True
51
Operator Precedence
a and b or c
(a and b) or c
Not
a and (b or c)
52
CH-4:Function
Function is a named sequence of statements that performs a
computation.
53
Function components
Name of the function
Function types
There are two kinds of functions in Python.
54
Built-in Functions
abs(-2)
max(7,8,12)
“Calling” functions
55
Arguments
An argument is a value we pass into the function as its input when
we call the function
56
Modules
Import
>>> math.sqrt(20)
Math module
>>> math.exp(math.log(10))
>>> math.cos(60)
57
Definitions and Uses
Once we have defined a function, we can call (or invoke) it as many
times as we like
58
Cont’d
def square(num):
print(num*num)
>>> square()
>>> square(3)
59
CH-5:Conditionals
Flow of Execution
Function definitions do not alter the flow of execution of the program, but
statements inside the function are not executed until the function is called.
60
Flowcharts
Flowcharts are used to plan programs before they are created.
61
Branching programs
A Boolean expression is an expression that evaluates to produce a
result which is a Boolean value.
62
Truth tables
63
Till now
Straight line programs:
Executed one statement after another in order in which they appear and stop
when they are out of statements
64
Conditionals
Branching programs :
The simplest branching statement is a conditional
65
Conditional Execution
Writing programs, we almost always need the ability to check conditions and change
the behavior of the program accordingly.
Conditional statements
A test: an expression that evaluates to True/False
A block of code that is executed to True
[Optional] block of code that is executed if the test evaluates to False
66
Simple conditional statement
Syntax: if(<conditional statements>):
<block of code>
67
Indentation
Python uses indentation to delineate blocks of code
Most other programming languages use {}
Example
Divisible by two Pseudocode
Accept integer input from user
If input divisible by two:
output ‘YES’
>>> dividend, divisor = eval(input(‘Enter number: ’))
>>> print(dividend/divisor)
68
Cont’d
>>> dividend, divisor = eval(input(‘Enter number: ’))
>>> if (divisor != 0):
print(dividend/divisor) Cases
69
Alternative Executions
if(<conditional statements>):
<if block>
else:
<else block>
Odd–Even program
Input: x
if (x is divisible by 2):
print(‘x is even’)
else:
print(‘x is odd’)
70
Chained conditionals
71
Nested Conditionals
if(<conditional statements>):
if(<conditional statements>):
<if block>
else:
<else block>
else:
<else block>
if 0 < x:
if x % 2 == 0:
print(‘x is positive even number’)
72
Common Errors
if((Value > 0) or (Value <= 10)):
print(Value)
73
Floating point
if((1.11 - 1.10) == (2.11 -2.10)):
print(‘’)
74
Conditional Execution
Writing programs, we almost always need the ability to check conditions and change
the behavior of the program accordingly.
75
Grade
Score >=85 ==> A
Score >=70 but <85 ==> B
Score >=50 but <70 ==> C
Score >=40 but <50 ==> D
Score < 40 ==> F
76
Defensive Programming
Defensive programming is a form of defensive design intended to ensure the
continuing function of a piece of software under unforeseen circumstances.
Input
77
Updating variables
>>> x = 5
# increment by one
>>> x = x + 1 >>> x += 1
# decrement by one
>>> x = x - 1
>>> x -= 1
78
Chapter Six: Iteration
Computers/ Robots/ Computing machines are often used to automate repetitive
tasks.
79
Repetition Structures
The repetition structure causes a statement or set of statements to execute
repeatedly.
Iteration
A generic iteration mechanism begins with a test.
If the test evaluates to True, program executes the body once and then goes back to
reevaluate the test.
80
loops
A loop repeats a sequence of statements
Two types
while loop
for loop
81
The while loop
The while Loop is a Pretest Loop, which means it tests its condition before
performing an iteration.
while(condition):
<statements>
82
Cont’d
More formally, here is the flow of execution for a while statement:
I. Evaluate the condition, yielding True or False.
II. If the condition is false, exit the while statement and continue
execution at the next statement.
III. If the condition is true, execute the body
Example 1: Print numbers from 1 to 10
83
break statement
Sometimes you don’t know it’s time to end a loop until you get
half way through the body.
continue statement
When continue statement is executed, the current loop iteration is
skipped and the loop execution resumes with the next iteration of the
current, innermost loop statement.
84
pass statement
In Python, every def statement, if statement, or loop statement must have a body (i.e.,
a nonempty indented code block). Continue example
85
Infinite loops
Writing programs, we almost always need the ability to check conditions and change
the behavior of the program accordingly. For Loop
while(True):
print(‘hi’)
x=1
while(x > 0):
x += 1
86
Unintentional infinite loop
Off-by-one error(OB1)
A logic error that occurs in programming when an iterative loop iterates one
time too many or too few.
OB1
Arises when programmer makes mistakes such as
Fails to take account that a sequence starts at zero rather than one
Using “less than or equal to” in place of “less than” …
87
Sentinel Loops
A sentinel loop continues to process data until reaching a special value that signals the
end.
This special value is called the sentinel.
88
The for Loop
The loop variable picks up the next value in a sequence on each pass through the loop
The expression range(n) generates a sequence of ints from 0 through n – 1
89
Counting from x through n
The expression range(low, high) generates a sequence of ints from low through
high – 1
total += n
90
Nested loops
91
Break & continue
92
Chapter 7:Functions
To Be Cont’d
93