You are on page 1of 45

Course 1 - Programming Fundamentals using

Python
DAY 1
Lecture 1
Introduction to Programming
• Goal:
– Mastering the art of making a computer do what
you want to do
– Learn computational mode of thinking (not just
how to program a computer) and
– Become skillful at computational problem solving
(how could I capture a problem in a mechanical or
algorithmic steps)
So what does a computer do ?
• Fundamentally:-
– Perform Calculations.
– Remember result.
• So what calculations?
– Built in primitive(manufacturer provided basic
calculations that a computer can use).
– Creating our own method of calculating(using
those primitives in our way to perform
calculations…….our GOAL.)
Is that enough ?
• Billions of calculations per second.

• 100s of gigabytes of storage.


Are simple calculations enough ?
• Searching the World Wide Web
– Assume 45 billion pages.
– 1000 words per page
– 10 operations/ word (for finding and deciding the
right thing)
– How much time it will take ?
• So with fast computer we have to be smarter.
• Good algorithm design are needed that are
clever, intelligent and smart about
performing the task.
Are there any limit ?
• Irrespective of all these things computers have
limitations:-
– Some problems are still too complex (can be
handled as things may get improve)
• Predicting weather at local scale
• Sometimes they help in cryptography.
– Some problems are fundamentally impossible to
compute
• Finding whether a computer program will always halt
with an output for any input (Turing Halting problem)
Computational Problem Solving
• What is computation ?
– What is knowledge ?
– Declarative knowledge
• Statements of facts
– Imperative knowledge
• “how to “ methods or recipes
Algorithm
• “A finite set of instructions which if followed
accomplish a particular task.”
-------------------but----------------------
• In addition every algorithm must satisfy
following criteria:
1. Input: zero or more quantities externally
supplied.
2. Output: at least one quantity is produced.
3. Definiteness: each instruction must be clear
and unambiguous.
4. Finiteness: In all cases algorithm must
terminate after finite number of steps.
5. Effectiveness: each instruction must be
sufficiently basic.
• Remember:
“A good algorithm is like a sharp knife which does
your task but with minimum amount of effort.”

• Key features of an Algorithm


– Sequence
– Selection
– Iteration
Sequence, Selection and
iteration(loop)
• A sequence is a series of statements that do
not alter the execution path within an
algorithm.
• Selection statements evaluate one or more
alternatives. Paths are followed based on its
result.
• Loop iterates(repeats execution) a block of
code.
Algorithm representation
• There are two ways in which you can
represent a particular algorithm:
– Flow Chart
– Pseudo Code
Pseudocode
• Pseudocode is an English language like
representation of the code required for an
algorithm.
• It is partly English, partly structured code.
• The English part provides a relaxed syntax that
is easy to read.
• The code part consists of an extended version
of the basic algorithm constructs like
sequence, selection and iteration.
Pseudo code advantage
• Pseudo code is a compact and informal high-
level description of an algorithm.
• It is meant for human reading rather than
machine reading
• It helps the non-programmers to understand
the logic of the designed solution.
A simple example
Q Write pseudo code to calculate the sum of
two numbers given as input by user. After
calculating sum, it should be displayed on the
computer screen.
start
Read first number
Read second number
Calculate sum=first number + second number
Display sum
end
Basic Steps of the complete
development of an algorithm
1. Statement of the problem.
2. Development of a model.
3. Design of an algorithm.
4. Correctness of the algorithm.
5. Implementation
6. Documentation
Other parts are there but are not important for
time being.
Statement of the problem
• Do I understand the vocabulary used in the raw
formulation?
• What information has been given ?
• What do i want to find out ?
• How do I recognize a solution ?
• What information is missing and will any of this
be of use ?
• Is any of the given information worthless ?
• What assumptions have been made ?
Development of a model
• Which mathematical structures seems best-
suited for the problem ?
• Are there any other problems that have benn
solved which resemble this one ?
g g*g y/g ½(g + y/g)
3 9 8.33 5.66
5.66 32.03 4.42 5.04
5.04 25.4
Documentation
• It is an important part of the algorithm and
code.
• Golden rule:
• “Do like what you want other to be towards
you.”
Psuedo Code
Operators
• Like assignment operator, there are other operators also which can be used to perform various
operations.
• Arithmetic operators: Used for performing arithmetic operations
• Operators Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
• Relational operators: Also known as comparison operators, are used to compare values. Result of a
relational expression is always either true or false.
• Operators Description
== Equal to
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
!= Not equal to
• Logical operators are used to combine one or more relational expressions.
• Operators Description
AND Result will be true, if both the expressions are true. If any one or both the expressions
are false, the result will be false
OR Result will be true, even if one of the expression is true. If both the expressions are
false, the result will be false
NOT If the expression is true, result will be false and vice versa If A and B are two relational
expressions, say A = (Num1>2000), B= (Num2>100), the result of combining A and B using
logical operator is based on the result of A and B as shown below:

• A B A AND B
True True True
True False False
False True False
False False False
• A B A OR B
True True True
True False True
False True True
False False False
• A NOT A
True False
False True
Decision and Iteration Constructs
• In a pseudo-code, typically the instructions are
performed one by one or line by line. But
there may be situations when all the
statements in a pseudo-code are not
performed. Parts of the pseudo-code which
change the flow of instructions or in other
word, change the flow of control are called as
control structures.
• ATC takes lot of decisions as part of its air
traffic control operations.
• For example, if a flight is approaching the
runway, ATC has to check if the runway is
free. If the runway is not free, then the
flight should not land immediately. It should
circle in the air and wait for further
instructions from the ATC.
• Such decision making process can be
conveniently represented in a pseudo-code
using an if statement.
IF Else
• Sometimes, ATC may have more than one alternatives
for a given situation. For example, if the runway is free,
the flight can land. But if the flight has less fuel, then it
should be allowed an emergency landing. Otherwise, it
should circle in the air.
if (Runway=="free") then
display "Land"
else if (Fuel_Status=="low") then
display "Emergency landing"
else
display "Circle in the air"
end-if
• Immigration check needs to be done for all the passengers in the flight. Suppose
the flight had only 5 passengers, the pseudo-code can be written as follows:
display "Flight has landed"
display "Proceed for Immigration Check"

Passenger_Count=1
display "Immigration check done for passenger,", Passenger_Count

Passenger_Count=Passenger_Count+1
display "Immigration check done for passenger,", Passenger_Count

Passenger_Count=Passenger_Count+1
display "Immigration check done for passenger,", Passenger_Count

Passenger_Count=Passenger_Count+1
display "Immigration check done for passenger,", Passenger_Count

Passenger_Count=Passenger_Count+1
display "Immigration check done for passenger,", Passenger_Count

• Do you observe repetition of code? Is there a better way to write this?


• Incase of flights with more passengers, say 150, 200 etc., do you want to keep
writing these statements repeatedly?
For loop
• Sometimes, we may want to execute some
statements specific (known) number of times
as in the case of immigration check. In such
cases we can use a for loop as shown below.
No_Of_Passengers=5
for(Passenger_Count=1,Passenger_Count<=No_Of_P
assengers,Passenger_Count=Passenger_Count+1)
display "Immigration check done for passenger,",
Passenger_Count
end-for
While loop
• When we want to repeatedly execute a statement as
long as a condition is met, we can use the iteration
statement called as while loop.
display "The flight has landed"
display "Immigration check done"
display " Collect the baggage from the conveyor belt"
Baggage_Count=150
while(Baggage_Count>0) do
input No_Of_Baggage_Picked
Baggage_Count=Baggage_Count-No_Of_Baggage_Picked
end-while
Programming Language
• Pseudo-code helped us to represent the algorithms and
learn few basics of programming. But to instruct the
computer we need to write a program in a programming
language. There are many languages available in which we
can write our programs.
• If programming is about instructing computers, then why
do we have different languages? Why not instruct in one
language?
• Well, why do we have different types of flights? Why not
just one type of flight? Different languages are created for
different purposes. This involves trade-offs. For example a
large flight can carry many passengers, but also consumes
lot of fuel. Similarly different languages have different
advantages.
Guess the output of the below code
airline="AirIndia"
luggage_weight=28
AI_weight_limit=30
EM_weight_limit=35
if(airline=="AirIndia"):
if(luggage_weight<=AI_weight_limit):
print("Check-in cleared")
else:
print("Remove some luggage and come back")
elif(airline=="Emirates"):
if(luggage_weight<=EM_weight_limit):
print("Check in cleared")
else:
print("Remove some luggage and come back")
else:
print("Invalid airline")
var airline = "Emirates"
var luggageWeight = 35
AIWeightLimit = 30
EMWeightLimit = 35
if (airline == "AirIndia")
if (luggageWeight <= AIWeightLimit)
console.log("Check-in cleared")
else
console.log("Remove some luggage and come back")
else if (airline == "Emirates")
if (luggageWeight <= EMWeightLimit)
console.log("Check in cleared")
else
console.log("Remove some luggage and come back")
else
console.log("Invalid airline")
Data Types
• A program may have data belonging to
different types. Common data types used in
programming are:
Category Data Type Example
Numeric int 123
long 1237126381763
817
Numeric with float 123.45
decimal point double 123123.323453
24
Alphanumeric char A
String Hello
Boolean boolean True, False
Category Python
Numeric int
long
complex
Numeric with decimal float
point
Alphanumeric String
Boolean boolean
Variables
• Let’s have a look at the python program to display the
number of landings and number of takeoffs in an airport:
• Code Pane:
no_of_landings=356
no_of_takeoffs=245
print("Number of landings:",no_of_landings)
print("Number of takeoffs:",no_of_takeoffs)

Output:
Number of landings: 356
Number of takeoffs: 245
Static and Dynamic Typing
• Languages like Python and JavaScript are dynamically typed

• Dynamic Typing is a technique in some languages where depending on how a value is used,
the data type of the variable is dynamically and automatically assigned. Consider the below
code in Python,
num=65 #Line 1
num="A" #Line 2
In Line 1, variable num is considered to be of type int and in Line 2, it's type is reassigned to
String.
• Static Typing is used in some languages where the data type has to be declared before it is
used. Consider the below code in Go,
var num int=65; //Line 1
num="A"; //Line 2
var name string = "A"; //Line3
Here, Line 1 is a valid statement which declares a variable num of type int. But Line 2 is
invalid as we cannot assign a string value to variable num which is already declared to be of
type int. Line 3 is a valid statement where name is declared and used as a string.

• (In Python, you can find out the data type of a variable by writing type(variable_name))
Reserved words
• Any name can be given to a variable however,
we cannot use some of the built-in keywords
of the language. These keywords are known as
reserved words. Some of the reserved words
are:

• Python: if, else, for, while, def, print, raise, try,


except
Variables and Operators
• We have seen that a variable will have a name,
value, type and it will occupy memory. Apart
from these, it has two more dimensions – scope
and lifetime. Thus we can say that any variable
will have the following six dimensions.
Name
Scope (where it can be accessed)
DataType
Address (where it is stored)
Lifetime (how long it will be stored)
Value
Common Operators Python
Arithmetic Operators +,-,*,/, %,//
Relational Operators ==,!=,>,<,>=,<=
Assignment Operators =,+=,-=,*=,/=,%=
Logical Operators and,or,not

It is done based on the precedence of the operator. Precedence of an operator can


be identified based on the rule - BODMAS. Brackets followed by Orders (Powers,
Roots), followed by modulo, Division and Multiplication, followed by Addition and
Subtraction.
Brackets have the highest precedence followed by orders.
Modulo, Division and Multiplication have the same precedence. Hence if all appears
in an expression, it is evaluated from Left to Right.
Addition and Subtraction have the same precedence. Hence if both appears in an
expression, it is evaluated from Left to Right.
Coding standards
• Here are two programs implementing the same functionality.
a=356
b=245
c=89
d=a+c-b
print(d)

• '''This is a program to find the current number of flights in an airport'''


landings_count=356
takeoffs_count=245
initial_flights=89
current_flights = initial_flights + landings_count - takeoffs_count
#Displaying the current number of flights
print("Current number of flights:",current_flights)

• Coding standards are the set of guidelines that can be used to enhance the
readability and clarity of the program and make it easy to debug and maintain the
program.
Implicit and Explicit Type Conversion
• Take a look at the below JavaScript code:
num=“10”+20
The result is "1020"!
• Here, JavaScript automatically converts 20 into
a string and combines the two strings. This is
known as implicit conversion.
• What if we want to avoid this? What if we
want the output as 30?
• Take a look at the below JavaScript code:
num=Number(“10”)+20
The result will be 30.

• If we want the output as 30, then we have to explicitly


convert the string 10 into number 10. This is known as
explicit conversion. Explicit conversion involves mentioning
the data type within brackets explicitly.
• Programming languages define their own rule for implicit
and explicit conversions. For example, in JavaScript even
though number was implicitly converted to String, the
reverse did not happen. In other words, the string “10” did
not get implicitly converted to number. These rules will
change from language to language.
• Note: Python DO NOT support implicit conversions!
• We noticed that implicit conversions are dangerous
as one may encounter unexpected result. Similarly,
one has to be careful in explicit conversions as well.
For example,
• Converting a floating point value to integer would
result in loss of decimal point values.A larger data
type if converted to smaller data type will result in
loss of data as the number will be truncated.
Conversion Python
Conversion to int int()
Example:
num=int(“10”)
Value of num will be 10

Conversion to string str()


Example:
num=str(10)
Value of num will be “10”

You might also like