Module 1 - Why Should You Learn To Write Programs - NOTES

Download as pdf or txt
Download as pdf or txt
You are on page 1of 34

PYTHON APPLICATION PROGRAMMING

MODULE 1
CHAPTER 1

WHY SHOULD YOU LEARN TO WRITE PROGRAMS?

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?”

FIGURE 1: Personal Digital Assistant

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

Take the file name from the input


Take the file name from the output

Take=2, the=4, file=2 , name=2 , from =2 input=1, output=1

Compile: python words.py


Input: Enter file:words.txt
Output: The=4

Our “personal information analysis assistant” quickly told us that the word “the” was
used four times in the statement.

Geethalakshmi N M, Assistant Professor, Page 1


Acharya IT
PYTHON APPLICATION PROGRAMMING
Creativity and motivation
Building useful, elegant, and clever programs for others to use is a very creative
activity. Your computer or Personal Digital Assistant (PDA) usually contains many
different programs from many different groups of programmers, each competing for
your attention and interest. They try their best to meet your needs and give you a great
user experience in the process.

If we think of programs as the creative output of groups of programmers, perhaps the


following figure is a more sensible version of our PDA

Figure 2: Programmers talking to you

Computer hardware architecture

Figure 3: Computer Hardware architecture

 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.

Examples of secondary memory are disk drives or flash memory (typically


found in USB sticks and portable music players).

 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.

 Network Connection to retrieve information over a network. We can think of


the network as a very slow place to store and retrieve data that might not always
be “up”. So in a sense, the network is a slower and at times unreliable form of
Secondary Memory.

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.

Figure 4: Where are you?

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.

Geethalakshmi N M, Assistant Professor, Page 3


Acharya IT
PYTHON APPLICATION PROGRAMMING
Understanding programming
In a sense, you need two skills to be a programmer:

 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.

Words and sentences


Unlike human languages, the Python vocabulary is actually pretty small. We call this
“vocabulary” the “reserved words”. These are words that have very special meaning to
Python. When Python sees these words in a Python program, they have one and only
one meaning to Python.

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:

And del global not with


as elif if or yield
assert else import pass break
except in raise class finally
is return continue for lambda
try def from Nonloca while
l

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!')

Geethalakshmi N M, Assistant Professor, Page 4


Acharya IT
PYTHON APPLICATION PROGRAMMING

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.

Conversing with Python


Before you can converse with Python, you must first install the Python software on your
computer and learn how to start Python on your computer. At some point, you will be
in a terminal or command window and you will type python and the Python interpreter will
start executing in interactive mode and appear somewhat as follows:

Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:54:25) [MSC


v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

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.

TO Print a Hello word

>>> print ('Hello world!')


Hello world!

>>> 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
^

SyntaxError: Missing parentheses in call to 'print'

Geethalakshmi N M, Assistant Professor, Page 5


Acharya IT
PYTHON APPLICATION PROGRAMMING

How to Quit from the python interpreter

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

Error – Not a correct method

>>> if you don't mind, I need to leave

File "<stdin>", line 1


if you don't mind, I need to leave
^

Error: SyntaxError: invalid syntax

>>> quit ()

Correct method to Quit from the python interpreter

The proper way to say “good-bye” to Python is to enter quit () at the interactive chevron
>>> prompt.

Terminology: interpreter and compiler


Python is a high-level language intended to be relatively straightforward for humans to
read and write and for computers to read and process.

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
...

Geethalakshmi N M, Assistant Professor, Page 6


Acharya IT
PYTHON APPLICATION PROGRAMMING
Since machine language is tied to the computer hardware, machine language is not
portable across different types of hardware. Programs written in high-level languages can
be moved between different computers by using a different interpreter on the new
machine or recompiling the code to create a machine language version of the program
for the new machine.

These programming language translators fall into two general categories:


(1) interpreters
(2) compilers.

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

Geethalakshmi N M, Assistant Professor, Page 7


Acharya IT
PYTHON APPLICATION PROGRAMMING
It is not easy to read or write machine language, so it is nice that we have interpreters
and compilers that allow us to write in high-level languages like Python or C.

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:

csev$ cat hello.py


print('Hello world!')
csev$ python hello.py
Hello world!
csev$

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:

1. A simple program that displays “Hello, World!”.

print('Hello, world!')

2. Add two numbers and display it using print () function.

num1 = 1.5
num2 = 6.3

# Add two numbers


sum = float(num1) + float(num2)

# Display the sum


print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))

Geethalakshmi N M, Assistant Professor, Page 8


Acharya IT
PYTHON APPLICATION PROGRAMMING
3. Largest Among Three Numbers

num1 = 10
num2 = 14
num3 = 12

# uncomment following lines to take three numbers from user


#num1 = float(input("Enter first number: "))
#num2 = float(input("Enter second number: "))
#num3 = float(input("Enter third number: "))

if (num1 >= num2) and (num1 >= num3):


largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3

print("The largest number etween",num1,",",num2,"and",num3,"is",largest)

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

Write a Python program to count the words than it would be to


manually scan the words.

name = input('Enter file:')


handle = open(name, 'r')
counts = dict()
for line in handle:
words = line.split()
for word in words:
counts[word] = counts.get(word, 0) + 1
bigcount = None
bigword = None
for word, count in list(counts.items()):
if bigcount is None or count > bigcount:
bigword = word
bigcount = count
print(bigword, bigcount)

Geethalakshmi N M, Assistant Professor, Page 9


Acharya IT
PYTHON APPLICATION PROGRAMMING
The building blocks of programs
There are some low-level conceptual patterns that we use to construct programs. These
constructs are not just for Python programs, they are part of every programming
language from machine language up to the high-level languages.

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.

What could possibly go wrong?


Beginning programmers often take the fact that Python leaves no room for errors as
evidence that Python is mean, hateful, and cruel. While Python seems to like
everyone else, Python knows them personally and holds a grudge against them.
Because of this grudge, Python takes our perfectly written programs and rejects them as
“unfit” just to torment us.

>>> primt 'Hello world!' >>> primt ('Hello world')


File "<stdin>", line 1 Traceback (most recent call last):
primt 'Hello world!' File "<stdin>", line 1, in <module>
^
SyntaxError: invalid syntax NameError: name 'primt' is not defined

>>> 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

Geethalakshmi N M, Assistant Professor, Page 10


Acharya IT ^
SyntaxError: invalid syntax
PYTHON APPLICATION PROGRAMMING
As your programs become increasingly sophisticated, you will encounter three general
types of errors:

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.

Geethalakshmi N M, Assistant Professor, Page 11


Acharya IT
PYTHON APPLICATION PROGRAMMING
CHAPTER 2

VARIABLES, EXPRESSIONS, AND STATEMENTS

Values and types


A value is one of the basic things a program works with, like a letter or a number. The
values we have seen so far are 1, 2, and “Hello, World!”

values belong to different types:


 is an integer,
 “Hello, World!” is a string, so called because it contains a “string” of letters.
You (and the interpreter) can identify strings because they are enclosed in quotation
marks. The print statement also works for integers.

We use the python command to start the interpreter.

python
>>> print(4)
4

If you are not sure what type a value has, the interpreter can tell you.

>>> type('Hello, World!')


<class 'str'>
>>> type(17)
<class 'int'>

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.

Geethalakshmi N M, Assistant Professor, Page 12


Acharya IT
PYTHON APPLICATION PROGRAMMING

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.

An assignment statement creates new variables and gives them values:

>>> message = 'My Name is Chethan '


>>> n = 17
>>> pi = 3.1415926535897931

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.

To display the value of a variable, you can use a print statement:


>>> print(n)
17
>>> print(pi)
3.141592653589793
>>> print(message)
My Name is
Chethan

The type of a variable is the type of the value it refers to.


>>> type(message)
<class 'str'>
>>> type(n)
<class 'int'>
>>> type(pi)
<class 'float'>

Geethalakshmi N M, Assistant Professor, Page 13


Acharya IT
PYTHON APPLICATION PROGRAMMING
Variable names and keywords
Variable names can be arbitrarily long. They can contain both letters and numbers, but
they cannot start with a number. It is legal to use uppercase letters, but it is a good
idea to begin variable names with a lowercase letter.

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.

If you give a variable an illegal name, you get a syntax error:

>>> 76trombones = 'big parade'


SyntaxError: invalid syntax

>>> more@ = 1000000


SyntaxError: invalid syntax

>>> class = 'Advanced Theoretical Zymurgy'


SyntaxError: invalid syntax

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.

Python reserves 33 keywords:


And del from None True
As elif global nonlocal try
assert else if not while
break except import or with
class False in pass yield
continue finally is raise def
for lambda return

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.

A script usually contains a sequence of statements. If there is more than one


statement, the results appear one at a time as the statements execute.

Geethalakshmi N M, Assistant Professor, Page 14


Acharya IT
PYTHON APPLICATION PROGRAMMING

For example, the script

print(1)
x = 2
print(x)

produces the output

1
2

The assignment statement produces no output.

Operators and operands

Operators are special symbols that represent computations like addition and
multiplication.
The values the operator is applied to are called operands.

The operators +, -, *, /, and ** perform addition, subtraction, multiplication, division,


and exponentiation, as in the following examples:

20+32 hour-1 hour*60+minute minute/60 5**2 (5+9)*(15-7)

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

Geethalakshmi N M, Assistant Professor, Page 15


Acharya IT
PYTHON APPLICATION PROGRAMMING
Order of operations

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:

 Parentheses have the highest precedence and can be used to force an


expression to evaluate in the order you want.

Example:
1. 2 * (3-1)
4
2. (1+1)**(5-2)
8.

 Exponentiation has the next highest precedence,

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.

Geethalakshmi N M, Assistant Professor, Page 16


Acharya IT
PYTHON APPLICATION PROGRAMMING

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
(%).

The syntax is the same as for other operators:


>>> quotient = 7 // 3
>>> print(quotient)
2
>>> remainder = 7 % 3
>>> print(remainder)
1

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

Asking the user for input


Python provides a built-in function called input that gets input from the keyboard.

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.

>>> inp = input()


Some silly
Geethalakshmi N M, Assistant Professor, Page 17
Acharya IT
PYTHON APPLICATION PROGRAMMING
stuff
>>> print(inp)
Some silly stuff

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:

>>> name = input('What is your name?\n')


What is your name?
GETHA
>>> print(name)
GEETHA

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:

# compute the percentage of the hour that has elapsed


percentage = (minute * 100) / 60

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.

Choosing mnemonic variable names


As long as you follow the simple rules of variable naming, and avoid reserved words,
you have a lot of choice when you name your variables.

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:

for word in words:


print(word)

What is happening here? Which of the tokens (for, word, in, etc.) are reserved words
and which are just variable names?

The following code is equivalent to the above code:


for slice in pizza:
print(slice)

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.

Geethalakshmi N M, Assistant Professor, Page 19


Acharya IT
PYTHON APPLICATION PROGRAMMING
If you put a space in a variable name, Python thinks it is two operands without an
operator:

>>> bad name = 5


SyntaxError: invalid syntax

>>> month = 09
File "<stdin>", line
1 month = 09
^
SyntaxError: invalid token

For syntax errors, the error messages don’t help much.

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:

>>> principal = 327.68


>>> interest = principle * rate
NameError: name 'principle' is not defined

Geethalakshmi N M, Assistant Professor, Page 20


Acharya IT
PYTHON APPLICATION PROGRAMMING

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'>

The == operator is one of the comparison operators; the others are: x


!= y # x is not equal to y
x > y # x is greater than y
x < y # x is less than y
x >= y # x is greater than or equal to y
x <= y # x is less than or equal to y
x is y # x is the same as y
x is not y # x is not the same as y

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,

x > 0 and x < 10


is true only if x is greater than 0 and less than 10.

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.

Geethalakshmi N M, Assistant Professor, Page 21


Acharya IT
PYTHON APPLICATION PROGRAMMING

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.

Figure 3.1: If Logic


If the logical condition is true, then the indented statement gets executed. If the logical
condition is false, the indented statement is skipped.

Occasionally, it is useful to have a body with no statements (usually as a place holder


for code you haven’t written yet). In that case, you can use the pass statement, which does
nothing.

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:

Geethalakshmi N M, Assistant Professor, Page 22


Acharya IT
PYTHON APPLICATION PROGRAMMING

>>> 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.

Figure 3.2: If-then-Else Logic


Chained conditionals
Sometimes there are more than two possibilities and we need more than two
branches. One way to express a computation like that is a chained conditional:

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.

Geethalakshmi N M, Assistant Professor, Page 23


Acharya IT
PYTHON APPLICATION PROGRAMMING

Figure 3.3: If-Then-Elseif Logic


Nested conditionals
One conditional can also be nested within another. We could have written the three-
branch example like this:
if x == y:
print('x and y are equal')
else:
if x < y:
print('x is less than y')
else:
print('x is greater than y')

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.

Figure 3.4 : Nested –If Statement


Geethalakshmi N M, Assistant Professor, Page 24
Acharya IT
PYTHON APPLICATION PROGRAMMING
Catching exceptions using try and except

Sample program to convert a Fahrenheit temperature to a Celsius temperature:


inp = input('Enter Fahrenheit Temperature: ') fahr
= float(inp)
cel = (fahr - 32.0) * 5.0 / 9.0
print(cel)
# Code: http://www.py4e.com/code3/fahren.py

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.

We can rewrite our temperature converter as follows:


inp = input('Enter Fahrenheit Temperature:')
try:
fahr = float(inp)
cel = (fahr - 32.0) * 5.0 / 9.0
print(cel)
except:
print('Please enter a number')
# Code: http://www.py4e.com/code3/fahren2.py

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.

Geethalakshmi N M, Assistant Professor, Page 25


Acharya IT
PYTHON APPLICATION PROGRAMMING
python fahren2.py

Enter Fahrenheit Temperature:72

22.22222222222222

python fahren2.py
Enter Fahrenheit Temperature: Fred
please enter a number

Handling an exception with a try statement is called catching an exception. In this


example, the except clause prints an error message. In general, catching an exception
gives you a chance to fix the problem, or try again, or at least end the program
gracefully.

Short-circuit evaluation of logical expressions


When Python detects that there is nothing to be gained by evaluating the rest of a logical
expression, it stops its evaluation and does not do the computations in the rest of the
logical expression. When the evaluation of a logical expression stops because the
overall value is already known, it is called short-circuiting the evaluation.

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

Geethalakshmi N M, Assistant Professor, Page 26


Acharya IT
PYTHON APPLICATION PROGRAMMING
The third calculation failed because Python was evaluating (x/y) and y was zero,
which causes a runtime error. But the second example did not fail because the first
part of the expression x >= 2 evaluated to False so the (x/y) was not ever executed
due to the short-circuit rule and there was no error.

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.

Geethalakshmi N M, Assistant Professor, Page 27


Acharya IT
PYTHON APPLICATION PROGRAMMING

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:

>>> max('Hello world')


'w'
>>> min('Hello world')
''
The max function tells us the “largest character” in the string (which turns out to be
the letter “w”) and the min function shows us the smallest character (which turns out to
be a space).

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

Type conversion functions


Python also provides built-in functions that convert values from one type to another. The
int function takes any value and converts it to an integer, if it can, or complains

Geethalakshmi N M, Assistant Professor, Page 28


Acharya IT
PYTHON APPLICATION PROGRAMMING

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 converts integers and strings to floating-point numbers:


>>> float(32)
32.0

>>> float('3.14159')
3.14159

Finally, str converts its argument to a string:


>>> str(32)
'32'

>>> 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.

Geethalakshmi N M, Assistant Professor, Page 29


Acharya IT
PYTHON APPLICATION PROGRAMMING

To see a sample, run this loop:

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:

>>> import math

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.

>>> ratio = signal_power / noise_power


>>> decibels = 10 * math.log10(ratio)
>>> radians = 0.7
>>> height = math.sin(radians)
Geethalakshmi N M, Assistant Professor, Page 30
Acharya IT
PYTHON APPLICATION PROGRAMMING

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

Adding new functions


So far, we have only been using the functions that come with Python, but it is also
possible to add new functions. A function definition specifies the name of a new
function and the sequence of statements that execute when the function is called.

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,

to repeat the previous refrain, we could write a function called repeat_lyrics:


def repeat_lyrics():
print_lyrics()
print_lyrics()
And then call repeat_lyrics:
Geethalakshmi N M, Assistant Professor, Page 31
Acharya IT
PYTHON APPLICATION PROGRAMMING

>>> 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.

Definitions and uses


Pulling together the code fragments from the previous section, the whole program looks
like this:

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

This program contains two function definitions: print_lyrics and repeat_lyrics.


Function definitions get executed just like other statements, but the effect is to create
function objects. The statements inside the function do not get executed until the
function is called, and the function definition generates no output.

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

Parameters and arguments


Inside the function, the arguments are assigned to variables called parameters.
Example of a user-defined function that takes an argument:

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:

>>> print_twice('Spam '*4)


Spam Spam Spam Spam
Spam Spam Spam Spam
>>> print_twice(math.cos(math.pi))
-1.0
-1.0

Fruitful functions and void functions


Some of the functions we are using, such as the math functions, yield results;for lack
of a better name, I call them fruitful functions. Other functions, like print_twice,
perform an action but don’t return a value. They are called void functions.

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.

>>> result = print_twice('Bing')


Bing
Bing
>>> print(result)
None
The value None is not the same as the string “None”. It is a special value that has its
own type:

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.

def addtwo(a, b):


added = a + b
return added
x = addtwo(3, 5)
print(x)

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.

Geethalakshmi N M, Assistant Professor, Page 34


Acharya IT

You might also like