Module 1 - Why Should You Learn To Write Programs - NOTES
Module 1 - Why Should You Learn To Write Programs - NOTES
Module 1 - Why Should You Learn To Write Programs - NOTES
MODULE 1
CHAPTER 1
Writing programs (or programming) is a very creative and rewarding activity. You can
write programs for many reasons, ranging from making your living to solving a
difficult data analysis problem to having fun to helping someone else solve a problem.
The hardware in our current-day computers is essentially built to continuously ask us the
question, “What would you like me to do next?”
Programmers add an operating system and a set of applications to the hardware and we
end up with a Personal Digital Assistant that is quite helpful and capable of helping us
do many different things.
For example: Finding the most commonly used word and how many times the word
is used
Statement: words.py
Our “personal information analysis assistant” quickly told us that the word “the” was
used four times in the statement.
The Central Processing Unit (or CPU) is the part of the computer that is built
to be obsessed with “what is next?”.
Example: If your computer is rated at 3.0 Gigahertz, it means that the CPU will
ask “What next?” three billion times per second.
The Main Memory is used to store information that the CPU needs in a hurry.
The main memory is nearly as fast as the CPU. But the information stored in the
main memory vanishes when the computer is turned off.
Geethalakshmi N M, Assistant Professor, Page 2
Acharya IT
PYTHON APPLICATION PROGRAMMING
The Secondary Memory is also used to store information, but it is much slower
than the main memory. The advantage of the secondary memory is that it can
store information even when there is no power to the computer.
The Input and Output Devices are simply our screen, keyboard, mouse,
microphone, speaker, touchpad, etc. They are all of the ways we interact with
the computer.
As a programmer you will mostly be “talking” to the CPU and telling it what to do
next. Sometimes you will tell the CPU to use the main memory, secondary memory,
network, or the input/output devices.
You need to be the person who answers the CPU’s “What next?” question. So instead,
you must write down your instructions in advance. We call these stored instructions a
program and the act of writing these instructions down and getting the instructions to be
correct programming.
First Step:
Know the programming language (Python) - you need to know the
vocabulary and the grammar. You need to be able to spell the words in this
new language properly and know how to construct well-formed “sentences”
in this new language.
Second Step:
“Tell a story”. In writing a story, you combine words and sentences to
convey an idea to the reader. There is a skill and art in constructing the story,
and skill in story writing is improved by doing some writing and getting
some feedback. In programming, our program is the “story” and the
problem you are trying to solve is the “idea”.
The new programming language has very different vocabulary and grammar but the
problem-solving skills will be the same across all programming languages.
Later as you write programs you will make up your own words that have meaning to
you called variables. You will have great latitude in choosing your names for your
variables, but you cannot use any of Python’s reserved words as a name for a variable.
The reserved words in the language where humans talk to Python include the following:
The nice thing about telling Python to speak is that we can even tell it what to say by
giving it a message in quotes:
print('Hello world!')
And we have even written our first syntactically correct Python sentence. Our sentence
starts with the function print followed by a string of text of our choosing enclosed in
single quotes.
The >>> prompt is the Python interpreter’s way of asking you, “What do you want me
to do next?” Python is ready to have a conversation with you.
>>> print('You must be the legendary god that comes from the sky')
You must be the legendary god that comes from the sky
>>> print('We have been waiting for you for a long time')
We have been waiting for you for a long time
>>> print('Our legend says you will be very tasty with mustard')
Our legend says you will be very tasty with mustard
Error Statement:
>>> print 'We will have a feast tonight unless you say
File "<stdin>", line 1
print 'We will have a feast tonight unless you say
^
Before we leave our first conversation with the Python interpreter, you should
probably know the proper way to say “good-bye” when interacting with the
inhabitants of Planet Python:
>>> good-bye
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'good' is not defined
>>> quit ()
The proper way to say “good-bye” to Python is to enter quit () at the interactive chevron
>>> prompt.
The actual hardware inside the Central Processing Unit (CPU) does not understand
any of these high-level languages. The CPU understands a language we call machine
language. Machine language is very simple and frankly very tiresome to write because
it is represented all in zeros and ones:
Example: 001010001110100100101010000001111
11100110000011101010010101101101
...
An interpreter reads the source code of the program as written by the programmer,
parses the source code, and interprets the instructions on the fly. Python is an
interpreter and when we are running Python interactively, we can type a line of Python
(a sentence) and Python processes it immediately and is ready for us to type another
line of Python.
Some of the lines of Python tell Python that you want it to remember some value for
later. We need to pick a name for that value to be remembered and we can use that
symbolic name to retrieve the value later. We use the term variable to refer to the
labels we use to refer to this stored data.
>>> x = 6
>>> print(x)
6
>>> y = x * 7
>>> print(y)
42
A compiler needs to be handed the entire program in a file, and then it runs a process
to translate the high-level source code into machine language and then the compiler
puts the resulting machine language into a file for later execution.
If you have a Windows system, often these executable machine language programs
have a suffix of “.exe” or “.dll” which stand for “executable” and “dynamic link
library” respectively. In Linux and Macintosh, there is no suffix that uniquely marks a
file as executable.
If you were to open an executable file in a text editor, it would look completely crazy
and be unreadable:
^?ELF^A^A^A^@^@^@^@^@^@^@^@^@^B^@^C^@^A^@^@^@\xa0\x82
^D^H4^@^@^@\x90^]^@^@^@^@^@^@4^@ ^@^G^@(^@$^@!^@^F^@
^@^@4^@^@^@4\x80^D^H4\x80^D^H\xe0^@^@^@\xe0^@^@^@^E
^@^@^@^D^@^@^@^C^@^@^@^T^A^@^@^T\x81^D^H^T\x81^D^H^S
^@^@^@^S^@^@^@^D^@^@^@^A^@^@^@^A\^D^HQVhT\x83^D^H\xe
Writing a program
When we want to write a program, we use a text editor to write the Python instructions
into a file, which is called a script. By convention, Python scripts have names that end
with .py.
To execute the script, you have to tell the Python interpreter the name of the file. In a Unix
or Windows command window, you would type python hello.py as follows:
What is a program?
It might be easiest to understand what a program is by thinking about a problem that a
program might be built to solve, and then looking at a program that would solve that
problem.
Example:
print('Hello, world!')
num1 = 1.5
num2 = 6.3
num1 = 10
num2 = 14
num3 = 12
Look at the following text about a clown and a car. Look at the text and figure out the most
common word and how many times it occurs.
the clown ran after the car and the car ran into the tent and
the tent fell down on the clown and the car
input Get data from the “outside world”. This might be reading data from a file, or
even some kind of sensor like a microphone or GPS. In our initial programs, our input
will come from the user typing data on the keyboard.
output Display the results of the program on a screen or store them in a file or perhaps
write them to a device like a speaker to play music or speak text.
sequential execution Perform statements one after another in the order they are
encountered in the script.
conditional execution Check for certain conditions and then execute or skip a
sequence of statements.
repeated execution Perform some set of statements repeatedly, usually with some
variation.
reuse Write a set of instructions once and give them a name and then reuse those
instructions as needed throughout your program.
>>> I hate you Python! >>> if you come out of there, I would teach you a
File "<stdin>", line 1 lesson
I hate you Python! File "<stein>", line 1
^ if you come out of there, I would teach you a lesson
SyntaxError: invalid syntax
Syntax errors These are the first errors you will make and the easiest to fix. A syntax
error means that you have violated the “grammar” rules of Python. Python does its
best to point right at the line and character where it noticed it was confused.
Logic errors A logic error is when your program has good syntax but there is a mistake
in the order of the statements or perhaps a mistake in how the statements relate to one
another.
Semantic errors A semantic error is when your description of the steps to take is
syntactically perfect and in the right order, but there is simply a mistake in the
program.
The program is perfectly correct but it does not do what you intended for it to do.
python
>>> print(4)
4
If you are not sure what type a value has, the interpreter can tell you.
Not surprisingly, strings belong to the type str and integers belong to the type int.
Less obviously, numbers with a decimal point belong to a type called float,
because these numbers are represented in a format called floating point.
>>> type(3.2)
<class 'float'>
What about values like “17” and “3.2”? They look like numbers, but they are in
quotation marks like strings.
>>> type('17')
<class 'str'>
>>> type('3.2')
<class 'str'>
They’re strings.
When you type a large integer, you might be tempted to use commas between groups
of three digits, as in 1,000,000. This is not a legal integer in Python, but it is legal:
>>> print(1,000,000) 1
00
Well, that’s not what we expected at all! Python interprets 1,000,000 as a comma
separated sequence of integers, which it prints with spaces between.
This is the first example we have seen of a semantic error: the code runs without
producing an error message, but it doesn’t do the “right” thing.
Variables
One of the most powerful features of a programming language is the ability to manipulate
variables. A variable is a name that refers to a value.
This example makes three assignments. The first assigns a string to a new variable
named message; the second assigns the integer 17 to n; the third assigns the
(approximate) value of Pie to pi.
The underscore character (_) can appear in a name. It is often used in names with
multiple words, such as my_name or airspeed_of_unladen_swallow.
Variable names can start with an underscore character, but we generally avoid doing
this unless we are writing library code for others to use.
It turns out that class is one of Python’s keywords. The interpreter uses keywords to
recognize the structure of the program, and they cannot be used as variable names.
Statements
A statement is a unit of code that the Python interpreter can execute. We
have seen two kinds of statements:
print being an expression statement and assignment.
print(1)
x = 2
print(x)
1
2
Operators are special symbols that represent computations like addition and
multiplication.
The values the operator is applied to are called operands.
Expressions
An expression is a combination of values, variables, and operators. A value all by
itself is considered an expression, and so is a variable, so the following are all legal
expressions (assuming that the variable x has been assigned a value):
17
x
x + 17
If you type an expression in interactive mode, the interpreter evaluates it and displays
the result:
>>> 1 + 1
2
>>> 10-2
8
When more than one operator appears in an expression, the order of evaluation
depends on the rules of precedence.
For mathematical operators, Python follows mathematical convention. The acronym
PEMDAS is a useful way to remember the rules:
Example:
1. 2 * (3-1)
4
2. (1+1)**(5-2)
8.
Example:
1. 2**1+1
3,
2. 3*1**3
3
Multiplication and Division have the same precedence, which is higher than
Addition and Subtraction, which also have the same precedence.
Example:
1. 2*3-1
5
2. 6+4/2
8.0
Operators with the same precedence are evaluated from left to right.
Example:
1. 5-3-1
1
Solution: 5-3-1 is 1, not 3, because the 5-3 happens first and then 1 is
subtracted from 2.
Modulus operator
The modulus operator works on integers and yields the remainder when the first
operand is divided by the second. In Python, the modulus operator is a percent sign
(%).
You can also extract the right-most digit or digits from a number. For example, x %
10 yields the right-most digit of x (in base 10). Similarly, x % 100 yields the last two
digits.
String operations
The + operator works with strings, but it is not addition in the mathematical sense.
Instead it performs concatenation, which means joining the strings by linking them
end to end. For example:
>>> first = 10
>>> second = 15
>>> print(first+second)
25
>>> first = '100'
>>> second = '150'
>>> print(first + second)
100150
The output of this program is 100150
When this function is called, the program stops and waits for the user to type
something. When the user presses Return or Enter, the program resumes and input
returns what the user typed as a string.
Before getting input from the user, it is a good idea to print a prompt telling the user
what to input. You can pass a string to input to be displayed to the user before pausing
for input:
The sequence \n at the end of the prompt represents a newline, which is a special
character that causes a line break. That’s why the user’s input appears below the
prompt.
Comments
it is a good idea to add notes to your programs to explain in natural language what the
program is doing. These notes are called comments, and in Python they start with the #
symbol:
In this case, the comment appears on a line by itself. You can also put comments at the
end of a line:
percentage = (minute * 100) / 60 # percentage of an hour
Everything from the \# to the end of the line is ignored; it has no effect on the
program.
For example, the following three programs are identical in terms of what they
accomplish, but very different when you read them and try to understand them.
a = 35.0
b = 12.50
c = a * b
print(c)
Geethalakshmi N M, Assistant Professor, Page 18
Acharya IT
PYTHON APPLICATION PROGRAMMING
hours = 35.0
rate = 12.50
pay = hours * rate
print(pay)
x1q3z9ahd = 35.0
x1q3z9afd = 12.50
x1q3p9afd = x1q3z9ahd * x1q3z9afd
print(x1q3p9afd)
We call these wisely chosen variable names “mnemonic variable names”. The word
mnemonic means “memory aid”. We choose mnemonic variable names to help us
remember why we created the variable in the first place.
Take a quick look at the following Python sample code which loops through some
data. We will cover loops soon, but for now try to just puzzle through what this means:
What is happening here? Which of the tokens (for, word, in, etc.) are reserved words
and which are just variable names?
It is easier for the beginning programmer to look at this code and know which parts are
reserved words defined by Python and which parts are simply variable names chosen
by the programmer. It is pretty clear that Python has no fundamental understanding of
pizza and slices and the fact that a pizza consists of a set of one or more slices. But if
our program is truly about reading data and looking for words in the data, pizza and
slice are very un-mnemonic variable names. Choosing them as variable names
distracts from the meaning of the program.
Many text editors are aware of Python syntax and will color reserved words differently
to give you clues to keep your variables and reserved words separate.
Debugging
At this point, the syntax error you are most likely to make is an illegal variable name,
like class and yield, which are keywords, or odd~job and US$, which contain illegal
characters.
>>> month = 09
File "<stdin>", line
1 month = 09
^
SyntaxError: invalid token
The runtime error you are most likely to make is a “use before def;” that is, trying to
use a variable before you have assigned a value. This can happen if you spell a
variable name wrong:
CHAPTER 3
CONDITIONAL EXECUTION
Boolean expressions
A boolean expression is an expression that is either true or false. The following
examples use the operator ==, which compares two operands and produces True if
they are equal and False otherwise:
>>> 5 == 5
True
>>> 5 == 6
False
True and False are special values that belong to the class bool; they are not strings:
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>
Logical operators
There are three logical operators: and, or, and not. The semantics (meaning) of these
operators is similar to their meaning in English. For example,
n%2 == 0 or n%3 == 0 is true if either of the conditions is true, that is, if the number is
divisible by 2 or 3.
Finally, the not operator negates a boolean expression, so not (x > y) is true if x > y is
false; that is, if x is less than or equal to y.
Strictly speaking, the operands of the logical operators should be boolean expressions,
but Python is not very strict. Any nonzero number is interpreted as “true.”
>>> 17 and True
True
This flexibility can be useful, but there are some subtleties to it that might be
confusing. You might want to avoid it until you are sure you know what you are doing
Conditional execution
In order to write useful programs, we almost always need the ability to check
conditions and change the behavior of the program accordingly. Conditional
statements give us this ability. The simplest form is the if statement:
if x > 0 :
print('x is positive')
The boolean expression after the if statement is called the condition. We end the if
statement with a colon character (:) and the line(s) after the if statement are indented.
if x < 0 :
pass # need to handle negative values!
If you enter an if statement in the Python interpreter, the prompt will change from
three chevrons to three dots to indicate you are in the middle of a block of statements,
as shown below:
>>> x = 3
>>> if x < 10:
... print('Small')
...
Small
>>>
Alternative execution
A second form of the if statement is alternative execution, in which there are two
possibilities and the condition determines which one gets executed. The syntax looks
like this:
if x%2 == 0 :
print('x is even')
else :
print('x is odd')
Since the condition must either be true or false, exactly one of the alternatives will be
executed. The alternatives are called branches, because they are branches in the flow
of execution.
if x < y:
print('x is less than y')
elif x > y:
print('x is greater than y')
else:
print('x and y are equal')
elif is an abbreviation of “else if.” Again, exactly one branch will be executed.
The outer conditional contains two branches. The first branch contains a simple
statement. The second branch contains another if statement, which has two branches of
its own. Those two branches are both simple statements, although they could have
been conditional statements as well.
If we execute this code and give it invalid input, it simply fails with an unfriendly
error message:
python fahren.py
Enter Fahrenheit Temperature:72
22.22222222222222
python fahren.py
Enter Fahrenheit Temperature:fred
Traceback (most recent call last):
File "fahren.py", line 2, in <module>
fahr = float(inp)
ValueError: could not convert string to float: 'fred'
There is a conditional execution structure built into Python to handle these types of
expected and unexpected errors called “try / except”. The idea of try and except is
that you know that some sequence of instruction(s) may have a problem and you want to
add some statements to be executed if an error occurs. These extra statements (the except
block) are ignored if there is no error. You can think of the try and except feature in
Python as an “insurance policy” on a sequence of statements.
Python starts by executing the sequence of statements in the try block. If all goes
well, it skips the except block and proceeds. If an exception occurs in the try block,
Python jumps out of the try block and executes the sequence of statements in the except
block.
22.22222222222222
python fahren2.py
Enter Fahrenheit Temperature: Fred
please enter a number
While this may seem like a fine point, the short-circuit behavior leads to a clever technique
called the guardian pattern. Consider the following code sequence in the Python
interpreter:
>>> x = 6
>>> y = 2
>>> x >= 2 and (x/y) > 2
True
>>> x = 1
>>> y = 0
>>> x >= 2 and (x/y) > 2
False
>>> x = 6
>>> y = 0
>>> x >= 2 and (x/y) > 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
Debugging
The traceback Python displays when an error occurs contains a lot of information, but it
can be overwhelming. The most useful parts are usually:
• What kind of error it was, and
• Where it occurred.
Syntax errors are usually easy to find, but there are a few gotchas. Whitespace errors
can be tricky because spaces and tabs are invisible and we are used to ignoring them.
>>> x = 5
>>> y = 6
File "<stdin>", line
1y = 6
^
IndentationError: unexpected indent
In general, error messages tell you where the problem was discovered, but that is often
not where it was caused.
CHAPTER 4
FUNCTIONS
Function calls
In the context of programming, a function is a named sequence of statements that
performs a computation. When you define a function, you specify the name and the
sequence of statements. Later, you can “call” the function by name. We have already
seen one example of a function call:
>>> type(32)
<class 'int'>
The name of the function is type. The expression in parentheses is called the argument
of the function. The argument is a value or variable that we are passing into the function
as input to the function. The result, for the type function, is the type of the argument.
It is common to say that a function “takes” an argument and “returns” a result. The
result is called the return value.
Built-in functions
Python provides a number of important built-in functions that we can use without
needing to provide the function definition. The creators of Python wrote a set of
functions to solve common problems and included them in Python for us to use. The
max and min functions give us the largest and smallest values in a list, respectively:
Another very common built-in function is the len function which tells us how many
items are in its argument. If the argument to len is a string, it returns the number of
characters in the string.
>>> len('Hello world')
11
otherwise:
>>> int('32')
32
>>> int('Hello')
ValueError: invalid literal for int() with base 10: 'Hello'
int can convert floating-point values to integers, but it doesn’t round off; it chops off
the fraction part:
>>> int(3.99999)
3
>>> int(-2.3)
-2
>>> float('3.14159')
3.14159
>>> str(3.14159)
'3.14159'
Random numbers
Given the same inputs, most computer programs generate the same outputs every time,
so they are said to be deterministic.
Making a program truly nondeterministic turns out to be not so easy, but there are
ways to make it at least seem nondeterministic. One of them is to use algorithms that
generate pseudorandom numbers. Pseudorandom numbers are not truly random
because they are generated by a deterministic computation, but just by looking at
the numbers it is all but impossible to distinguish them from random.
The random module provides functions that generate pseudorandom numbers .The
function random returns a random float between 0.0 and 1.0 (including 0.0 but not
1.0). Each time you call random, you get the next number in a long series.
import random
for i in range(10):
x = random.random()
print(x)
This program produces the following list of 10 random numbers between 0.0 and up
to but not including 1.0.
0.11132867921152356
0.5950949227890241
0.04820265884996877
0.841003109276478
0.997914947094958
0.04842330803368111
0.7416295948208405
0.510535245390327
0.27447040171978143
0.028511805472785867
Math functions
Python has a math module that provides most of the familiar mathematical functions.
Before we can use the module, we have to import it:
This statement creates a module object named math. If you print the module object,
you get some information about it:
>>> print(math)
<module 'math' (built-in)>
The module object contains the functions and variables defined in the module. To
access one of the functions, you have to specify the name of the module and the name
of the function, separated by a dot (also known as a period). This format is called dot
notation.
If you know your trigonometry, you can check the previous result by comparing it to
the square root of two divided by two:
>>> math.sqrt(2) / 2.0
0.7071067811865476
Once we define a function, we can reuse the function over and over throughout our
program.
Example:
def print_lyrics():
print("I'm a lumberjack, and I'm okay.")
print('I sleep all night and I work all day.')
def is a keyword that indicates that this is a function definition. The name of the
function is print_lyrics. The rules for function names are the same as for variable
names: letters, numbers and some punctuation marks are legal, but the first character
can’t be a number. You can’t use a keyword as the name of a function, and you should
avoid having a variable and a function with the same name.
The empty parentheses after the name indicate that this function doesn’t take any
arguments. Later we will build functions that take arguments as their inputs.
The first line of the function definition is called the header; the rest is called the body.
The value of print_lyrics is a function object, which has type “function”. The syntax for
calling the new function is the same as for built-in functions:
>>> print_lyrics()
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
Once you have defined a function, you can use it inside another function. For
example,
>>> repeat_lyrics()
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
But that’s not really how the song goes.
def print_lyrics():
print("I'm a lumberjack, and I'm okay.")
print('I sleep all night and I work all day.')
def repeat_lyrics():
print_lyrics()
print_lyrics()
repeat_lyrics()
# Code: http://www.py4e.com/code3/lyrics.py
Flow of execution
In order to ensure that a function is defined before its first use, you have to know the order
in which statements are executed, which is called the flow of execution.
Execution always begins at the first statement of the program. Statements are executed
one at a time, in order from top to bottom.
Function definitions do not alter the flow of execution of the program, but remember
that statements inside the function are not executed until the function is called.
A function call is like a detour in the flow of execution. Instead of going to the next
statement, the flow jumps to the body of the function, executes all the statements
there, and then comes back to pick up where it left off.
Fortunately, Python is good at keeping track of where it is, so each time a function
completes, the program picks up where it left off in the function that called it. When it
gets to the end of the program, it terminates
Geethalakshmi N M, Assistant Professor, Page 32
Acharya IT
PYTHON APPLICATION PROGRAMMING
def print_twice(bruce):
print(bruce)
print(bruce)
This function assigns the argument to a parameter named bruce. When the function is
called, it prints the value of the parameter (whatever it is) twice.
This function works with any value that can be printed.
>>> print_twice('Spam')
Spam
Spam
>>> print_twice(17)
17
17
>>> import math
>>> print_twice(math.pi)
3.141592653589793
3.141592653589793
The same rules of composition that apply to built-in functions also apply to user-
defined functions, so we can use any kind of expression as an argument for
print_twice:
When you call a fruitful function, you almost always want to do something with the
result; for example, you might assign it to a variable or use it as part of an expression:
x = math.cos(radians)
golden = (math.sqrt(5) + 1) / 2
When you call a function in interactive mode, Python displays the result:
Geethalakshmi N M, Assistant Professor, Page 33
Acharya IT
PYTHON APPLICATION PROGRAMMING
>>> math.sqrt(5)
2.23606797749979
oid functions might display something on the screen or have some other effect, but
they don’t have a return value. If you try to assign the result to a variable, you get a
special value called None.
To return a result from a function, we use the return statement in our function.
For example, we could make a very simple function called addtwo that adds two numbers
together and returns a result.
Why functions?
It may not be clear why it is worth the trouble to divide a program into functions. There are
several reasons:
• Creating a new function gives you an opportunity to name a group of statements, which
makes your program easier to read, understand, and debug.
• Functions can make a program smaller by eliminating repetitive code. Later, if you make
a change, you only have to make it in one place.
• Dividing a long program into functions allows you to debug the parts one at a time and
then assemble them into a working whole.
• Well-designed functions are often useful for many programs. Once you write and debug
one, you can reuse it.
Debugging
If you are using a text editor to write your scripts, you might run into problems with
spaces and tabs. The best way to avoid these problems is to use spaces exclusively (no
tabs). Most text editors that know about Python do this by default, but some don’t.