0% found this document useful (0 votes)
7 views204 pages

Introduction to Python Programming

This document introduces Python programming, explaining the nature of software, development tools, and the structure of Python programs. It covers key concepts such as variables, assignment, and the differences between compilers and interpreters, along with practical examples of Python code. Additionally, it discusses debugging, profiling, and the accessibility of Python for both beginners and experienced programmers.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views204 pages

Introduction to Python Programming

This document introduces Python programming, explaining the nature of software, development tools, and the structure of Python programs. It covers key concepts such as variables, assignment, and the differences between compilers and interpreters, along with practical examples of Python code. Additionally, it discusses debugging, profiling, and the accessibility of Python for both beginners and experienced programmers.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Course Title: Programming

with Python

Chapter One
Introduction to Python
Programming
Software

• A computer program is an example of computer software. One can


refer to a program as a piece of software as if it were a tangible object,
but software is actually quite intangible. It is stored on a medium.
• A hard drive, a CD, a DVD, and a USB pen drive are all examples of
media upon which software can reside.
• The CD is not the software; the software is a pattern on the CD. In
order to be used, software must be stored in the computer’s memory.
Typically computer programs are loaded into memory from a medium
like the computer’s hard disk.
• An electromagnetic pattern representing the program is stored on the
computer’s hard drive.
• This pattern of electronic symbols must be transferred to the
computer’s memory before the program can be executed.
• The program may have been installed on the hard disk from a CD or
from the Internet.
Development Tools

• Software can be represented by printed words


and symbols that are easier for humans to
manage than binary sequences.
• Tools exist that automatically convert a higher-
level description of what is to be done into the
required lower-level code.
• Higher-level programming languages like Python
allow programmers to express solutions to
programming problems in terms that are much
closer to a natural language like English.
Cont---

• Some examples of the more popular of the


hundreds of higher-level programming
languages that have been devised over the
past 60 years include FORTRAN, COBOL,
Lisp, Haskell, C, Perl, C++, Java, and C#.
• Most programmers today, especially those
concerned with high-level applications,
usually do not worry about the details of
underlying hardware platform and its
machine language.
Cont---

• Consider the following program fragment written in the Python


programming language:
subtotal = 25
tax = 3
total = subtotal + tax

• While these three lines do constitute a proper Python program, they


more likely are merely a small piece
of a larger program.
• The lines of text in this program fragment look similar to expressions
in algebra.

• We see no sequence of binary digits. Three words, subtotal, tax, and


total, called variables, represent information.
• Mathematicians have used variables for hundreds of years before the
first digital computer was built.
Cont---

• In programming, a variable represents a value stored in the


computer’s memory. Instead of some
cryptic binary instructions meant only for the processor, we see
familiar-looking mathematical operators
(= and +).
• Since this program is expressed in the Python language, not
machine language, no computer
processor can execute the program directly. A program called an
interpreter translates the Python code into
machine code when a user runs the program.
• The higher-level language code is called source code.
• The corresponding machine language code is called the target code.
• The interpreter translates the source code
into the target machine language.
Cont---
• Programmers have a variety of tools available to enhance the
software development process. Some common tools include:
• Editors. An editor allows the programmer to enter the program
source code and save it to files.
Most programming editors increase programmer productivity by
using colors to highlight language
features. The syntax of a language refers to the way pieces of the
language are arranged to make well-formed sentences. To
illustrate, the sentence:
The tall boy runs quickly to the door.
• uses proper English syntax. By comparison, the sentence
Boy the tall runs door to quickly the.
is not correct syntactically. It uses the same words as the original
sentence, but their arrangement
does not follow the rules of English.
Cont---

• Similarly, programming languages have strict


syntax rules that programmers must follow to
create well-formed programs.
• Only well-formed programs are acceptable for
translation into executable machine code.
• Some syntax-aware editors can use colors or
other special annotations to alert programmers
of syntax errors during the editing process.
Compilers

• A compiler translates the source code to target


code. The target code may be the machine
language for a particular platform or embedded
device.
• The target code could be another source
language; for example, the earliest C++ compiler
translated C++ into C, another higher-level
language.
• The resulting C code was then processed by a C
compiler to produce an executable program.
Interpreters
• An interpreter is like a compiler, in that it translates higher-
level source code into target code (usually machine
language). It works differently, however.
• While a compiler produces an executable program that may
run many times with no additional translation needed, an
interpreter translates source code statements into machine
language each time a user runs the program.
• A compiled program does not need to be recompiled to
run, but an interpreted program must be reinterpreted
each time it executes. For this reason interpreted languages
are often referred to as scripting languages.
• The interpreter in essence reads the script, where the script
is the source code of the program.
Cont---

• In general, compiled programs execute more quickly than


interpreted programs because the translation activity
occurs only once.
• Interpreted programs, on the other hand, can run as is on
any platform with an appropriate interpreter; they do not
need to be recompiled to run on a different
platform.
• Python, for example, is used mainly as an interpreted
language, but compilers for it are available.
• Interpreted languages are better suited for dynamic,
explorative development which many people feel is ideal for
beginning programmers. Popular scripting languages include
Python, Ruby, Perl, and, for web browsers, Javascript.
Debuggers

• A debugger allows a programmer to more easily trace a


program’s execution in order to locate and correct
errors in the program’s implementation.
• With a debugger, a developer can simultaneously run a
program and see which line in the source code is
responsible for the program’s current actions.
• The programmer can watch the values of variables and
other program elements to see if their values change as
expected.
• Debuggers are valuable for locating errors (also called
bugs) and repairing programs that contain errors.
Profilers

• A profiler collects statistics about a program’s execution


allowing developers to tune appropriate parts of the program
to improve its overall performance.
• A profiler indicates how many times a portion of a program is
executed during a particular run, and how long that portion
takes to execute.
• Developers also can use profilers for testing purposes to
ensure all the code in a program is actually being used
somewhere during testing. This is known as coverage.
• It is common for software to fail after its release because
users exercise some part of the program that was not
executed anytime during testing.
• The main purpose of profiling is to find the parts of a program
that can be improved to make the program run faster.
Programming with Python

• Guido van Rossum created the Python programming language


in the late 1980s.
• In contrast to other popular languages such as C, C++, Java,
and C#, Python strives to provide a simple but powerful
syntax.
• Python is used for software development at companies and
organizations such as Google, Yahoo, Facebook, CERN,
Industrial Light and Magic, and NASA.
• Experienced programmers can accomplish great things with
Python, but Python’s beauty is that it is accessible to beginning
programmers and allows them to tackle interesting problems
more quickly than many other, more complex languages that
have a steeper learning curve.
Writing a Python Program

• The text that makes up a Python program has a particular


structure.
• The syntax must be correct, or the interpreter will generate error
messages and not execute the program. This section introduces
Python by
providing a simple example program.
A program consists of one or more statements.
• A statement is an instruction that the interpreter executes.
The following statement invokes the print function to display a
message:
print("This is a simple Python program")
We can use the statement in a program. Listing 1.1 ([Link]) is
one of the simplest Python programs that
does something:
Listing 1.1: [Link]
print("This is a simple Python program")
Cont---
• This is a Python statement. A statement is a command that the
interpreter executes. This statement
prints the message This is a simple Python program on the
screen. A statement is the fundamental unit of
execution in a Python program.
• Statements may be grouped into larger chunks called blocks,
and blocks can make up more complex statements. Higher-
order constructs such as functions and methods are composed
of blocks. The statement
print("This is a simple Python program")
makes use of a built in function named print.
• Python has a variety of different kinds of statements that we
can use to build programs, and the chapters that follow
explore these various kinds of statements.
A Longer Python program

• More interesting programs contain multiple


statements. In Listing ([Link]), six print
statements draw an arrow on the screen:
[Link]
print(“ * ")
print(" *** ")
print(" ***** ")
print(" * ")
print(“ * ")
print(“ * ")
Cont---
• We wish the output of Listing 1.2 ([Link]) to
be
*
***
*****
*
*
*
Exercises

1. What is a compiler?
2. What is an interpreter?
3. How is a compiler similar to an interpreter? How are they
different?
4. How is compiled or interpreted code different from
source code?
5. What tool does a programmer use to produce
Python source code?
6. What is necessary to execute a Python program?
7. List several advantages developing software in a
higher-level language has over developing software
in machine language.
8. How can an IDE improve a programmer’s productivity
9. What is a statement in a Python program?
Chapter Two
Values and Variables
Values and variables
• In this chapter we explore some building
blocks that are used to develop Python
programs. We experiment
with the following concepts:
• numeric values
• strings
• variables
• assignment
• identifiers
• reserved words
Integer and String Values
• The number four (4) is an example of a numeric value. In
mathematics, 4 is an integer value. Integers
are whole numbers, which means they have no
fractional parts, and they can be positive, negative, or
zero.
Examples of integers include 4, -19, 0, and -1005. In
contrast, 4.5 is not an integer, since it is not a whole
number.
Python supports a number of numeric and nonnumeric
values. In particular, Python programs can use
integer values. The Python statement
print(4)
prints the value 4.
Cont---

• The value 4 is an example of an integer expression.


• Python supports other types of expressions besides
integer expressions.
• An expression is a basic building block of a Python
statement.

• The number 4 by itself is not a complete Python


statement and, therefore, cannot be a program.
• The interpreter, however, can evaluate a Python
expression.
• You may type the enter 4 directly into the interactive
interpreter shell:
Cont---

• The interactive shell attempts to evaluate both


expressions and statements. In this case, the
expression 4 evaluates to 4.
• The shell executes what is commonly called the
read, eval, print loop. This means the
interactive shell’s sole activity consists of
1. reading the text entered by the user,
2. attempting to evaluate the user’s input in the
context of what the user has entered up that
point, and
3. printing its evaluation of the user’s input.
Cont---

• If the user enters a 4, the shell interprets it as a 4.


• If the user enters x = 10, a statement has has no
overall value itself, the shell prints nothing. If the
user then enters x, the shell prints the evaluation
of x, which is 10.
• If the user next enters y, the shell reports a error
because y has not been defined in a previous
interaction.
• Python uses the + symbol with integers to perform
normal arithmetic addition, so the interactive shell
can serve as a handy adding machine:
Cont---

• Example
>>> 3 + 4
7
>>> 1 + 2 + 4 + 10 + 3
20
>>> print(1 + 2 + 4 + 10 + 3)
20
The last line evaluated shows how we can use
the + symbol to add values within a print
statement that could be part of a Python
program.
Consider what happens if we use quote
marks around an integer:
>>> 19
19
>>> "19"
'19'
>>> '19'
'19'
Notice how the output of the interpreter is different.
The expression "19" is an example of a string value
Cont---

• A string is a sequence of characters. Strings most often contain


nonnumeric characters:
>>> "Fred"
'Fred'
>>> 'Fred'
'Fred'
Python recognizes both single quotes (') and double quotes (") as
valid ways to delimit a string value.
• The word delimit means to determine the boundaries or limits of
something.
• The left ' symbol determines the beginning of a string, and the
right ' symbol that follows specifies the end of the string.
• If a single quote marks the beginning of a string value, a single
quote must delimit the end of the string.
• Similarly, the double quotes, if used instead, must appear in
pairs.
Variables and Assignment
• In algebra, variables represent numbers. The same is true in
Python, except Python variables also can represent values other
than numbers.
x = 10
print(x)
• This is an assignment statement. An assignment statement
associates a value with a variable.
• The key to an assignment statement is the symbol = which is
known as the assignment operator. The statement assigns the
integer value 10 to the variable x. Said another way, this
statement binds the variable named x to the value 10. At this
point the type of x is int because it is bound to an integer value.
• We may assign and reassign a variable as often as necessary.
The type of a variable will change if it is reassigned an
expression of a different type.
Cont---

• print(x)

• This statement prints the variable x’s current


value. Note that the lack of quotation marks
here is very important. If x has the value 10, the
statement print(x)
• prints 10, the value of the variable x, but the
statement print('x')
• prints x, the message containing the single
letter x.
Cont---
• The meaning of the assignment operator (=) is different from
equality in mathematics. In mathematics,
= asserts that the expression on its left is equal to the
expression on its right. In Python, = makes the variable
on its left take on the value of the expression on its right. It is
best to read x = 5 as “x is assigned the value
5,” or “x gets the value 5.” This distinction is important since in
mathematics equality is symmetric: if
x = 5, we know 5 = x. In Python this symmetry does not exist;
the statement
5=x
attempts to reassign the value of the literal integer value 5, but
this cannot be done because 5 is always 5
and cannot be changed. Such a statement will produce an error.
Cont---

• >>> x = 5
>>> x
5
>>> 5 = x
File "<stdin>", line 1
SyntaxError: can't assign to literal
We can reassign different values to a
variable as needed,
• x = 10
print(x)
x = 20
print(x)
x = 30
print(x)
Cont---

• We can reassign different values to a variable as


needed
Example:
x = 10
print(x)
x = 20
print(x)
x = 30
print(x)
Cont---

• This program demonstrates that can we


cannot always predict the behavior of a
statement in isolation, especially if that
statement involves a variable. This is
because the statement’s behavior may
be dependent on the assigned values of
one or more variables that it uses.
Cont---
Output
x = 10 x = 10
print('x = ' + str(x)) x = 20
x = 30
x = 20
print('x = ' + str(x))
x = 30
print('x = ' + str(x))
uses the str function to treat x as a string so the
+ operator will use string concatenation:
print('x = ' + str(x))
The expression 'x = ' + x would not be legal; the
plus (+) operator may not be applied with mixed
string and integer operands.
Cont---

• The following Produces the same output as


mentioned above.
x = 10
print('x =', x)
x = 20
print('x =', x)
x = 30
print('x =', x)
Cont---

• This version of the print statement:


print('x =', x)
illustrates the print function accepting two parameters.
The first parameter is the string 'x =', and the second
parameter is the variable x bound to an integer value.
• The print function allows programmers to pass multiple
expressions to print, each separated by commas.
• The elements within the parentheses of the print
function comprise what is known as a comma-separated
list.
• The print function prints each element in the comma-
separated list of parameters. The print function
automatically prints a space between each element in the
list so the printed text elements do not run together.
Cont---

• A programmer may assign multiple variables in one


statement using tuple assignment.
Example
x, y, z = 100, -45, 0
print('x =', x, ' y =', y, ' z =', z)
Output
x = 100 y = -45 z = 0
Cont---

• A tuple is a comma-separated list of expressions.


• If the variables total and s are defined, the expression
total, 45, s, 0.3 represents a 4-tuple; that is, a tuple with
composed of four elements. In the assignment statement
x, y, z = 100, -45, 0
x, y, z is one tuple, and 100, -45, 0 is another tuple.
• Tuple assignment works as follows:
• The first variable in the tuple on left side of the assignment
operator is assigned the value of the first expression in the
tuple on the left side (effectively x = 100).
• Similarly, the second variable in the tuple on left side of
the assignment operator is assigned the value of the
second expression in the tuple on the left side (in effect
y = -45). z gets the value 0.
Cont---

• To see how variable bindings can change as the


computer executes a sequence of assignment
statements,
consider the following sequence of Python
statements:
a=2
b=5
a=3
a=b
b=7
Cont---

• Example on the previous slide illustrate how the


variable bindings change as the Python interpreter
executes each of the above statements.
a=b
Importantly, the statement means that a and b both are
bound to the same numeric object.
• Observe that later reassigning b does not affect a’s
value.

• Not only may a variable’s value change during its use


within an executing program; the type of a variable
Identifiers
• While mathematicians are content with giving their
variables one-letter names like x, programmers should
use longer, more descriptive variable names. Names such
as sum, height, and sub_total are much better
than the equally permissible s, h, and st.
• A variable’s name should be related to its purpose within
the program.
• Good variable names make programs more readable by
humans.
• Since programs often contain many variables, well-
chosen variable names can render an otherwise obscure
collection of symbols more understandable.
Cont ----

• Python has strict rules for variable names. A variable name is one
example of an identifier.
• An identifier is a word used to name things. One of the things an
identifier can name is a variable.
• We will see in later chapters that identifiers name other things
such as functions, classes, and methods. Identifiers have the
following form:
• An identifiers must contain at least one character.
• The first character of an identifiers must be an alphabetic letter
(upper or lower case) or the underscore
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
• The remaining characters (if any) may be alphabetic characters
(upper or lower case), the underscore, or a digit
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
_0123456789
Cont---

• No other characters (including spaces) are permitted


in identifiers
Examples of valid Python identifiers include
•x
• x2
• total
• port_22
None of the following words are valid identifiers:
• sub-total (dash is not a legal symbol in an identifier)
• first entry (space is not a legal symbol in an
identifier)
• 4all (begins with a digit)
• *2 (the asterisk is not a legal symbol in an identifier)
• class (class is a reserved word)
Cont----

• Python reserves a number of words for


special use that could otherwise be used
as identifiers, Called reserved words or
keywords, these words are special and are
used to define the structure of Python
programs and statements.
Cont---

• Python is a case-sensitive language. This means that


capitalization matters. if is a reserved word, but
none of If, IF, or iF is a reserved word.
• Identifiers also are case sensitive; the variable called Name is
different from the variable called name. Note that three of the
reserved words (False, None, and True) are capitalized.

• Programmers generally avoid distinguishing between two


variables in the same context merely by differences in
capitalization.
• Doing so is more likely to confuse human readers. For the same
reason, it is considered poor practice to give a variable the
same name as a reserved word with one or more of its letters
capitalized.
Floating-point Numbers

• Many computational tasks require numbers that have


fractional parts.
• For example, to compute the area of a circle given the
circle’s radius, we use the value p, or approximately
3.14159.
• Python supports such non-integer numbers, and they are
called floating-point numbers.
• The name implies that during mathematical calculations
the decimal point can move or “float” to various positions
within the number to maintain the proper number of
significant digits.
• The Python name for the floating-point type is float.
Cont---
• Consider the following interactive session:
>>> x = 5.62
>>> x
5.62
>>> type(x)
<class 'float'>
Cont---

• Floating-point numbers are an approximation of mathematical


real numbers.
• The range of floating-point numbers is limited, since each
value requires a fixed amount of memory.
• Floating-point numbers differ from integers in another, very
important way. An integer has an exact representation. This is
not true necessarily for a floating-point number. Consider the
real number p.
• The mathematical constant p is an irrational number which
means it contains an infinite number of digits with no pattern
that repeats.
• Since p contains an infinite number of digits, a Python program
can only approximate p’s value. Because of the limited number
of digits available to floating-point numbers.
Cont---

• Python cannot represent exactly even some


numbers with a finite number of digits; for
example, the number 23.3123400654033989
contains too many digits for the float type.
• As the following interaction sequence shows,
Python stores 23.3123400654033989 as
23.312340065403397:
>>> x = 23.3123400654033989
>>> x
23.312340065403397
Cont---

• We can express floating-point numbers in


scientific notation.
• Since most programming editors do not provide
superscripting and special symbols like ×, Python
slightly alters the normal scientific notation.
• The number 6:022×1023 is written 6.022e23. The
number to the left of the e (we can use capital E
as well) is the mantissa, and the number to the
right of the e is the exponent of 10.
• As another example, -5:1 × 10-4 is expressed in
Python as -5.1e-4.
Floating number example

• avogadros_number = 6.022e23
c = 2.998e8
print("Avogadro's number =", avogadros_number)
print("Speed of light =", c)
• The type of any literal expressed scientific notation always has
type float; for example, the Python expression 2e3 is a float, even
though conceptually we may consider it the same as integer the
2,000.
• Unlike floating-point numbers, integers are whole numbers and
cannot store fractional quantities. We can convert a floating-point
to an integer in two fundamentally different ways:
• Rounding adds or subtracts a fractional amount as necessary to
produce the integer closest to the original floating-point value.
• Truncation simply drops the fractional part of the floating-point
number, thus keeping whole number part that remains.
Cont---

• We can see how rounding and truncation differ in


Python’s interactive shell:
>>> 28.71
28.71
>>> int(28.71)
28
>>> round(28.71)
29
>>> round(19.47)
19
>>> int(19.47)
19
Cont---
• As we can see, truncation always “rounds down,” while rounding behaves as we would expect.
• We also can use the round function to round a floating-point number to a specified number of
decimal places.
• The round function accepts an optional argument that produces a floating-point rounded to fewer
decimal places.
• The additional argument must be an integer and specifies the desired number of decimal places
to round. In the shell we see
>>> x
93.34836
>>> round(x)
93
>>> round(x, 2)
93.35
>>> round(x, 3)
93.348
>>> round(x, 0)
93.0
>>> round(x, 1)
93.3
>>> type(round(x))
<class 'int'>
>>> type(round(x, 1))
<class 'float'>
>>> type(round(x, 0))
<class 'float'>
Cont---

• As we can see, the single-argument version of round produces an


integer result, but the two-argument version produces a floating-
point result.
• The second argument to the round function may be a negative
integer:
>>> x = 28793.54836
>>> round(x)
28794
>>> round(x, 1)
28793.5
>>> round(x, 2)
28793.55
>>> round(x, 0)
28794.0
>>> round(x, 1)
28793.5
>>> round(x, -1)
28790.0
>>> round(x, -2)
28800.0
>>> round(x, -3)
29000.0
Cont---

• The expression round(n, r) rounds floating-point


expression n to the 10-r decimal digit; for example,
round(n, -2) rounds floating-point value n to the
hundreds place (102).
• Similarly, round(n, 3) rounds floating-point value n to
the thousandths place (10-3).
• The round function can be useful for integer values as
well.
• If the first argument to round is an integer,
and the second argument to round is a negative integer,
the second argument specifies the number decimal
places to the left of the decimal point to round.
Cont---
•Consider the following experiments:
>>> round(65535)
65535
>>> round(65535, 0)
65535
>>> round(65535, 1)
65535
>>> round(65535, 2)
65535
>>> round(65535, -1)
65540
>>> round(65535, -2)
65500
>>> round(65535, -3)
66000
>>> round(65535, -4)
70000
>>> round(65535, -5)
100000
>>> round(65535, -6)
0
Control Codes within Strings
• The characters that can appear within strings include letters of the alphabet (A-Z,
a-z), digits (0-9), punctuation (., :, ,, etc.), and other printable symbols (#, &, %,
etc.).
• In addition to these “normal” characters, we may embed special characters
known as control codes.
• Control codes control the way the console window or a printer renders text.
• The backslash symbol (\) signifies that the character that follows it is a control
code, not a literal character. The string '\n' thus contains a single control code.
• The backslash is known as the escape symbol, and in this case we say the n
symbol is escaped.
• The \n control code represents the newline control code which moves the text
cursor down to the next line in the console window.
• Other control codes include \t for tab, \f for a form feed (or page eject) on a
printer, \b for backspace, and \a for alert (or bell).
• The \b and \a do not produce the desired results in the interactive shell, but they
work properly in a command shell.
Example

• print('A\nB\nC')
print('D\tE\tF')
print('WX\bYZ')
print('1\a2\a3\a4\a5\a6')
Output
A
B
C
D E F
WXYZ
123456
User Input

• The print function enables a Python program


to display textual information to the user.
• Programs may use the input function to
obtain information from the user.
• The simplest use of the input function
assigns a string to a variable:
x = input()
The parentheses are empty because the
input function does not require any
information to do its job.
Example

• print('Please enter some text:')


x = input()
print('Text entered:', x)
print('Type:', type(x))
Output
• Please enter some text:
My name is Rick
Text entered: My name is Rick
Type: <class 'str'>
Cont---

• The second line shown in the output is entered by the


user, and the program prints the first, third, and fourth
lines.
• After the program prints the message Please enter some
text:, the program’s execution stops and waits for the
user to type some text using the keyboard.
• The user can type, backspace to make changes, and type
some more.
• The text the user types is not committed until the user
presses the enter (or return) key.
Quite often we want to perform calculations and need
to get numbers from the user. The input function
produces only strings, but we can use the int function to
convert a properly formed string of digits into an integer.
Example
• print('Please enter an integer value:')
x = input()
print('Please enter another integer value:')
y = input()
num1 = int(x)
num2 = int(y)
print(num1, '+', num2, '=', num1 + num2)
Output
Please enter an integer value:
2
Please enter another integer value:
17
2 + 17 = 19
Cont---

• Lines two and four represent user input, while the program
generates the other lines.
• The program halts after printing the first line and does not
continue until the user provides the input.
• After the program prints the second message it again pauses to
accept the user’s second entry.
• Since user input almost always requires a message to the user
about the expected input, the input function optionally accepts a
string that it prints just before the program stops to wait for the
user to respond.
The statement
x = input('Please enter some text: ')
• prints the message Please enter some text: and then waits to
receive the user’s input to assign to x. W
Example

• x = input('Please enter an integer value: ')


y = input('Please enter another integer value: ')
num1 = int(x)
num2 = int(y)
print(num1, '+', num2, '=', num1 + num2)
Output
Cont---

• Be careful about code such as


num = int(input('Please enter a number: '))
• This statement expects the user to enter an integer value. If
the user types 3, for example, all is well.
• The variable num then will refer to the integer object 3.
• The int function can convert the string '3' to the integer
value 3.
• The word number is ambiguous, however, so the user might
attempt to enter 3.4. In this case the input statement would
return the string '3.4'.
• The int function cannot convert the string '3.4' to an
integer directly, even though it can convert the floating-
point number 3.4 to the integer 3.
The following interactive sequence demonstrates:
• >>> num = int(input('Please enter a number: '))
Please enter a number: 3
>>> num
3
>>> num = int(input('Please enter a number: '))
Please enter a number: 3.4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '3.4'
>>> int(3.4)
3
>>> int('3.4')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '3.4'
Cont---

• This example reveals that the int can convert a string to an integer
only if the string looks exactly like an
integer.
We could be more specific and simply request an integer value
from the user. If we really want an integer
from the user but want to tolerate decimal places, we could use an
additional function in our composition
of functions, as in the following:
>>> num = int(float(input('Please enter a number: ')))
Please enter a number: 3
>>> num
3
>>> num = int(float(input('Please enter a number: ')))
Please enter a number: 3.4
>>> num
3
Controlling the print Function
• we would prefer that the cursor remain at the end of the
printed line so when the user types a value it appears on
the same line as the message prompting for the values.
When the user presses the enter key to complete the input,
the cursor automatically will move down to the next line.
• The print function as we have seen so far always prints a
line of text, and then the cursor moves down
to the next line so any future printing appears on the next
line.
• The print statement accepts an additional argument that
allows the cursor to remain on the same line as the printed
text:
print('Please enter an integer value:', end='')
Cont---

• The expression end='' is known as a keyword argument. The term


keyword here means something different from the term keyword used to
mean a reserved word.
• We defer a complete explanation of keyword arguments until we have
explored more of the Python language.
• For now it is sufficient to know that a print function call of this form will
cause the cursor to remain on the same line as the printed text. Without
this
keyword argument, the cursor moves down to the next line after printing
the text.
The print statement
print('Please enter an integer value: ', end='')
means “Print the message Please enter an integer value:, and then
terminate the line with nothing rather than the normal \n newline
code.”
• Another way to achieve the same result is
print(end='Please enter an integer value: ')
Cont---

• This statement means “Print nothing, and then terminate


the line with the string 'Please enter an integer value:'
rather than the normal \n newline code. The behavior of
the two statements is indistinguishable.
The statement
print('Please enter an integer value:') is an abbreviated
form of the statement
print('Please enter an integer value:', end='\n')
that is, the default ending for a line of printed text is the
string '\n', the newline control code. Similarly,
the statement
print()
is a shorter way to express
print(end='\n')
Example

• print('A', end='')
print('B', end='')
print('C', end='')
print()
print('X')
print('Y')
print('Z')
Output
ABC
X
Y
Z
Cont---

• Another keyword argument allows us to control


how the print function visually separates the
arguments it displays.
• By default, the print function places a single
space in between the items it prints.
• Print uses a keyword argument named sep to
specify the string to use insert between items.
The name sep stands for separator.
• The default value of sep is the string ' ', a string
containing a single space.
Example

• w, x, y, z = 10, 15, 20, 25


print(w, x, y, z)
print(w, x, y, z, sep=',')
print(w, x, y, z, sep='')
print(w, x, y, z, sep=':')
print(w, x, y, z, sep='-----')
Output
10 15 20 25
10,15,20,25
10152025
[Link]
10-----15-----20-----25
String Formatting

• print(0, 10**0)
print(1, 10**1)
print(2, 10**2)
print(3, 10**3)
print(4, 10**4)
print(5, 10**5)
print(6, 10**6)
print(7, 10**7)
print(8, 10**8)
print(9, 10**9)
print(10, 10**10)
print(11, 10**11)
print(12, 10**12)
print(13, 10**13)
print(14, 10**14)
print(15, 10**15)
Output
01
1 10
2 100
3 1000
4 10000
5 100000
6 1000000
7 10000000
8 100000000
9 1000000000
10 10000000000
11 100000000000
12 1000000000000
13 10000000000000
14 100000000000000
15 1000000000000000
Observe that each number is left justified.
Example 2
print('{0} {1}'.format(0, 10**0))
print('{0} {1}'.format(1, 10**1))
print('{0} {1}'.format(2, 10**2))
print('{0} {1}'.format(3, 10**3))
print('{0} {1}'.format(4, 10**4))
print('{0} {1}'.format(5, 10**5))
print('{0} {1}'.format(6, 10**6))
print('{0} {1}'.format(7, 10**7))
print('{0} {1}'.format(8, 10**8))
print('{0} {1}'.format(9, 10**9))
print('{0} {1}'.format(10, 10**10))
print('{0} {1}'.format(11, 10**11))
print('{0} {1}'.format(12, 10**12))
print('{0} {1}'.format(13, 10**13))
print('{0} {1}'.format(14, 10**14))
print('{0} {1}'.format(15, 10**15))
Output

01
1 10
2 100
3 1000
4 10000
5 100000
6 1000000
7 10000000
8 100000000
9 1000000000
10 10000000000
11 100000000000
12 1000000000000
13 10000000000000
14 100000000000000
15 1000000000000000
Cont----

• the expression to print, namely


'{0} {1}'.format(7, 10**7)
becomes ’7 10000000’, since 7 replaces
{0} and 107 = 10000000 replaces {1}.
Exqmple

print('{0:>3} {1:>16}'.format(0, 10**0))


print('{0:>3} {1:>16}'.format(1, 10**1))
print('{0:>3} {1:>16}'.format(2, 10**2))
print('{0:>3} {1:>16}'.format(3, 10**3))
print('{0:>3} {1:>16}'.format(4, 10**4))
print('{0:>3} {1:>16}'.format(5, 10**5))
print('{0:>3} {1:>16}'.format(6, 10**6))
print('{0:>3} {1:>16}'.format(7, 10**7))
print('{0:>3} {1:>16}'.format(8, 10**8))
print('{0:>3} {1:>16}'.format(9, 10**9))
print('{0:>3} {1:>16}'.format(10, 10**10))
print('{0:>3} {1:>16}'.format(11, 10**11))
print('{0:>3} {1:>16}'.format(12, 10**12))
print('{0:>3} {1:>16}'.format(13, 10**13))
print('{0:>3} {1:>16}'.format(14, 10**14))
print('{0:>3} {1:>16}'.format(15, 10**15))
Output
0 1
1 10
2 100
3 1000
4 10000
5 100000
6 1000000
7 10000000
8 100000000
9 1000000000
10 10000000000
11 100000000000
12 1000000000000
13 10000000000000
14 100000000000000
15 1000000000000000
Multi-line Strings

• A Python string ordinarily spans a single line of text.


• The following statement is illegal:
x = 'This is a long string with several words'
• A string literal that begins with a ' or " must be terminated with
its matching ' or " on the same line in which it begins. As we
saw in Section 2.5), we can add newline control codes to
produce line breaks within
the string:
x = 'This is a long string with\nseveral words'
• This technique, however, obscures the programmer’s view of
the string within the source code. Python provides way to
represent a string’s layout more naturally within source code,
using triple quotes. The triple quotes (''' or """) delimit strings
that can span multiple lines in the source code.
Example

• x = '''
This is a multi-line
string that goes on
for three lines!
'''
print(x)
Exercises

1. Will the following lines of code print the same thing? Explain why or why not
x=6
print(6)
print("6")
2. Will the following lines of code print the same thing? Explain why or why not.
x=7
print(x)
print("x")
3. What is the largest floating-point value available on your system?
4. What is the smallest floating-point value available on your system?
5. What happens if you attempt to use a variable within a program, and that
variable has not been assigned a value?
6. What is wrong with the following statement that attempts to assign the value
ten to variable x?
10 = x
7. Once a variable has been properly assigned can its value be changed?
8. In Python can you assign more than one variable in a single statement?
Cont---

9. Classify each of the following (k) x2


as either a legal or illegal (l) Private
Python identifier:
(m) public
(a) fred
(b) if (n) $16
(c) 2x (o) xTwo
(d) -4 (p) _static
(e) sum_total
(f) sumTotal (q) _4
(g) sum-total (r) ___
(h) sum total (s) 10%
(i) sumtotal
(t) a27834
(j) While
Cont---

10. What can you do if a variable name you would like to use is the same
as a reserved word?
11. How is the value 2:45×10-5 expressed as a Python literal?
12. How can you express the literal value
0:0000000000000000000000000449 as a much more compact
Python literal?
13. How can you express the literal value
56992341200000000000000000000000000000 as a much more
compact Python literal?
14. Can a Python programmer do anything to ensure that a variable’s
value can never be changed after
its initial assignment?
15. Is "i" a string literal or variable?
16. What is the difference between the following two strings? 'n' and '\n'?
Cont---

17. Write a Python program containing exactly


one print statement that produces the
following output:
A
B
C
D
E
F
Chapter Three
Expressions and
Arithmetic
Expressions
• A literal value like 34 and a variable like x are examples
of simple expressions.
• We can use operators to combine values and variables
and form more complex expressions.
• we can use the addition
operator (+) to add two integers provided by the user.
Example
value1 = int(input('Please enter a number: '))
value2 = int(input('Please enter another number: '))
sum = value1 + value2
print(value1, '+', value2, '=', sum)
Cont---

• value1 = int(input('Please enter a number: '))


This statement prompts the user to enter some information.
• After displaying the prompt string Please
enter a number:,
• this statement causes the program’s execution to stop and
wait for the user to type in some text and then press the
enter key. The string produced by the input function is
passed off to the int function which produces an integer
value to assign to the variable value1. If the user types
the sequence 431 and then presses the enter key, value1 is
assigned the integer 431.
• value2 = int(input('Please enter another number: '))
This statement is similar to the first statement.
Cont---

• sum = value1 + value2;


• This is an assignment statement because is contains
the assignment operator (=).
• The variable sum appears to the left of the assignment
operator, so sum will receive a value when this
statement executes.
• To the right of the assignment operator is an
arithmetic expression involving two variables and the
addition operator. The expression is evaluated by
adding together the values bound to the two variables.
Once the addition expression’s value has been
determined, that value is assigned to the sum variable.
Cont---

• print(value1, '+', value2, '=', sum)


• This statement prints the values of the three variables
with some additional decoration to make the output
clear about what it is showing.
• All expressions have a value. The process of
determining the expression’s value is called evaluation.
• Evaluating simple expressions is easy. The literal value
54 evaluates to 54.
• The value of a variable named x is the value stored in
the memory location bound to x. The value of a more
complex expression is found by evaluating the smaller
expressions that make it up and combining them with
operators to form potentially new values.
Cont---
• The common arithmetic operations, addition, subtraction,
multiplication, division, and power behave in the expected
way.
• The // and % operators are not common arithmetic
operators in everyday practice, but they are very useful in
programming.
• The // operator is called integer division, and the %
operator is the modulus or remainder operator. 25/3 is
8.3333.
• Three does not divide into 25 evenly. In fact, three goes
into 25 eight times with a remainder of one. Here, eight is
the quotient, and one is the remainder. 25//3 is 8 (the
quotient), and 25%3 is 1 (the remainder).
Cont---

• All these operators are classified as binary


operators because they operate on two
operands. In the statement
x=y+z
on the right side of the assignment operator is an
addition expression y + z. The two operands of
the + operator are y and z.
• Two operators, + and -, can be used as unary
operators. A unary operator has only one
operand.
Cont----

• The - unary operator expects a single numeric


expression (literal number, variable, or more
complicated numeric expression within
parentheses) immediately to its right; it computes
the additive inverse of its operand.
• If the operand is positive (greater than zero), the
result is a negative value of the same magnitude;
if the operand is negative (less than zero), the
result is a positive value of the same magnitude.
Zero is unaffected.
Cont---
• For example, the following code sequence
x, y, z = 3, -4, 0
x = -x
y = -y
z = -z
print(x, y, z)
within a program would print
-3 4 0
The following statement
print(-(4 - 5))
within a program would print
1
Cont---

• When we apply the +, -, *, //, %, or ** operators to two integers, the


result is an integer.
• The statement:
print(25//4, 4//25)
prints
60
• The // operator produces an integer result when used with integers. In
the first case above 25 divided by 4
is 6 with a remainder of 1, and in the second case 4 divided by 25 is 0
with a remainder of 4.
• Since integers are whole numbers, the // operator discards any
fractional part of the answer.
• The process of discarding the fractional part of a number leaving only
the whole number part is called truncation.
• Truncation is not rounding; for example, 13 divided by 5 is 2.6, but 2.6
truncates to 2.
Cont---

• The modulus operator (%) computes the remainder of integer


division; thus,
print(25%4, 4%25)
prints
14
since 25 divided by 4 is 6 with a remainder of 1, and 4 divided by
25 is 0 with a remainder of 4.
• The modulus operator is more useful than it may first appear. The
following program shows how it can be used to convert a given
number of seconds to hours, minutes, and seconds.
• The / operator applied to two integers produces a floating-point
result. The statement
print(25/4, 4/25)
prints
6.25 0.16
Mixed Type Expressions
• Expressions may contain mixed integer and floating-
point elements; for example, in the following program
fragment
x=4
y = 10.2
sum = x + y
x is an integer and y is a floating-point number. What
type is the expression x + y? Except in the case of
the / operator, arithmetic expressions that involve
only integers produce an integer result.
• All arithmetic operators applied to floating-point
numbers produce a floating-point result.
Cont---

• When an operator has mixed operands—


one operand an integer and the other a
floating-point number—the interpreter
treats the integer
operand as floating-point number and
performs floating-point arithmetic.
• This means x + y is a floating point
expression, and the assignment will make
the variable sum bind to a floating-point
value.
Operator Precedence and Associativity

• When different operators appear in the same expression, the


normal rules of arithmetic apply. All Python
operators have a precedence and associativity:
• Precedence—when an expression contains two different kinds
of operators, which should be applied
first?
• Associativity—when an expression contains two operators
with the same precedence, which should
be applied first?
To see how precedence works, consider the expression
2+3*4
Should it be interpreted as
(2 + 3) * 4
(that is, 20), or rather is
2 + (3 * 4)
Cont---

• (that is, 14) the correct interpretation? As in normal arithmetic,


multiplication and division in Python have equal importance and
are performed before addition and subtraction.
• We say multiplication and division have precedence over addition
and subtraction. In the expression
2 + 3 * 4 the multiplication is performed before addition, since
multiplication has precedence over addition.
• The result is 14. The multiplicative operators (*, /, //, and %) have
equal precedence with each other, and the additive operators
(binary + and -) have equal precedence with each other.
• The multiplicative operators have precedence over the additive
operators.
Formatting Expressions
• Python offers considerable flexibility for formatting
arithmetic expressions; for example, suppose a program
is using the variables x and y to hold data, and we wish
to use those variables within a mathematical expression
like the following from algebra:
3x+2y-5
• Unlike algebra, Python has no implicit multiplication.
This means we must write 3x as 3*x. We may not
omit the * operator.
• We can print the value of the complete expression
above as follows:
print(3*x + 2*y - 5)
Cont---

• Note the lack of spaces. Most agree that this formatting, while legal Python,
is less readable by humans.
• Since people develop and read source code, human readability is important.
• Some suggest that spaces be used around all binary operators, as in the
following:
print(3 * x + 2 * y - 5)
In this case such a practice reduces the readability, since it make it appear as
the operators have equal
precedence (which they do not—spacing in an expression does not influence
operator precedence).
• The first way we wrote the expression naturally grouped together the factors
within a term, just as is common in algebra.
• The following is computationally equivalent in Python but misleading and
should be avoided:
print(3 * x+2 * y-5)
Cont---

• Again, spacing does not affect operator


precedence, but this formatting makes it appear
that the addition and the subtraction will take
place before the multiplication.
• Psychologically, the lack of space makes it
appear that + and - “bind” their operands more
tightly than does *. This is not true, and this
statement is easily misinterpreted by a human
reader.
Comments
• Good programmers annotate their code by
inserting remarks that explain the purpose
of a section of code or why they chose to
write a section of code the way they did.
• These notes are meant for human readers,
not the interpreter. It is common in
industry for programs to be reviewed for
correctness by other programmers or
technical managers.
Cont---

• Well-written comments can help


others understand new code quicker and
increase their productivity modifying old or
unfinished code.
• While it may seem difficult to believe, even
the same programmer working on her own
code months later can have a difficult time
remembering what various parts do.
Comments can help greatly.
Cont---

• Any text contained within comments is ignored by the Python


interpreter. The # symbol begins a comment in the source code.
The comment is in effect until the end of the line of code:
# Compute the average of the values avg = sum / number
• The first line here is a comment that explains what the statement
that follows it is supposed to do. The comment begins with the #
symbol and continues until the end of that line.
• The interpreter will ignore the # symbol and the contents of the
rest of the line. You also may append a short comment to the
end of a statement:
avg = sum / number # Compute the average of the values
Here, an executable statement and the comment appear on the
same line.
• The interpreter will read the assignment statement, but it will
ignore the comment.
Cont---
• How are comments best used? Avoid making a remark about the
obvious; for example:
result = 0 # Assign the value zero to the variable named result
• The effect of this statement is clear to anyone with even minimal
Python programming experience. Thus, the
audience of the comments should be taken into account; generally,
“routine” activities require no remarks.
• Even though the effect of the above statement is clear, its purpose
may need a comment. For example:
result = 0 # Ensures 'result' has a well-defined minimum value
• This remark may be crucial for readers to completely understand how
a particular part of a program works.
In general, programmers are not prone to providing too many
comments. When in doubt, add a remark.
• The extra time it takes to write good comments is well worth the
effort.
Errors

• Beginning programmers make mistakes writing


programs because of inexperience in programming
in general or due to unfamiliarity with a
programming language.
• Seasoned programmers make mistakes due to
carelessness or because the proposed solution to a
problem is faulty and the correct implementation of
an incorrect solution will not produce a correct
program.
• In Python, there are three general kinds of errors:
syntax errors, run-time exceptions, and logic errors.
Syntax Errors

• The interpreter is designed to execute all valid Python programs.


• The interpreter reads the Python source file and translates it into a
executable form. This is the translation phase. If the interpreter
detects an invalid program statement during the translation
phase, it will terminate the program’s execution and report an
error.
• Such errors result from the programmer’s misuse of the language.
• A syntax error is a common error that the interpreter can detect
when attempting to translate a Python statement into machine
language.
For example, in English one can say
The boy walks quickly.
Cont---

• This sentence uses correct syntax. However, the sentence


The boy walk quickly.
is not correct syntactically: the number of the subject (singular
form) disagrees with the number of the verb (plural form). It
contains a syntax error. It violates a grammatical rule of the
English language. Similarly, the Python statement
x=y+2
• is syntactically correct because it obeys the rules for the
structure of an assignment statement
• However, consider replacing this assignment statement with a
slightly modified version:
y+2=x
If a statement like this one appears in a program, the
interpreter will issue an error message.
Cont---

• y=5
x=y+2
y+2=x
in the above program, we get:
• File line 3
y+2=x

SyntaxError: can't assign to operator


Cont---

• # File [Link]
# Get two integers from the user
print('Please enter two numbers to divide.')
dividend = int(input('Please enter the dividend: '))
divisor = int(input('Please enter the divisor: '))
# Divide them and report the result
print(dividend, '/', divisor, "=", dividend/divisor)
The expression
dividend/divisor is potentially dangerous. If the user
enters, for example, 32 and 4, the program works nicely
Please enter two numbers to divide.
Please enter the dividend: 32
Please enter the divisor: 4
32 / 4 = 8.0
Cont---

• If the user instead types the numbers 32 and 0,


the program reports an error and terminates:
Please enter two numbers to divide.
Please enter the dividend: 32
Please enter the divisor: 0
Traceback (most recent call last):
File "C:\Users\rick\Desktop\[Link]", line
8, in <module>
print(dividend, '/', divisor, "=", dividend/divisor)
ZeroDivisionError: division by zero
Division by zero is undefined in mathematics,
and division by zero in Python is illegal.
Exercises

1. Is the literal 4 a valid Python expression?


2. Is the variable x a valid Python expression?
3. Is x + 4 a valid Python expression?
4. What affect does the unary + operator have when applied to a
numeric expression?
5. Sort the following binary operators in order of high to low
precedence: +, -, *, //, /, %, =.
6. Given the following assignment:
x=2
Indicate what each of the following Python statements would
print.
(a) print("x")
(b) print('x')
(c) print(x)
(d) print("x + 1")
(e) print('x' + 1)
(f) print(x + 1)
Cont---

7. Given the following assignments: (g) d1 + d2


i1 = 2 (h) d1 / d2
i2 = 5 (i) d2 / d1
i3 = -3 (j) d3 * d1
d1 = 2.0 (k) d1 + i2
d2 = 5.0
(l) i1 / d2
d3 = -0.5
Evaluate each of the following (m) d2 / i1
Python expressions. (n) i2 / d1
(a) i1 + i2 (o) i1/i2*d1
(b) i1 / i2 (p) d1*i1/i2
(c) i1 // i2
(d) i2 / i1
(e) i2 // i1 (f) i1 * i3
Cont---

• (q) d1/d2*i1
(r) i1*d1/d2
(s) i2/i1*d1
(t) d1*i2/i1
(u) d2/d1*i1
(v) i1*d2/d1
8. What is printed by the following statement:
#print(5/3)
9. Given the following assignments:
i1 = 2
i2 = 5
i3 = -3
d1 = 2.0
d2 = 5.0 d3 = -0.5
Evaluate each of the following Python expressions.
• (a) i1 + (i2 * i3) (k) d1 + (d2 * d3)
(b) i1 * (i2 + i3) (l) d1 + d2 * d3
(c) i1 / (i2 + i3) (m) d1 / d2 - d3
(d) i1 // (i2 + i3) (n) d1 / (d2 - d3)
(e) i1 / i2 + i3 (o) d1 + d2 + d3 / 3
(f) i1 // i2 + i3 (p) (d1 + d2 + d3) / 3
(g) 3 + 4 + 5 / 3 (q) d1 + d2 + (d3 / 3)
(h) 3 + 4 + 5 // 3 (r) 3 * (d1 + d2) * (d1 - d3)
(i) (3 + 4 + 5) / 3
(j) (3 + 4 + 5) // 3
Cont---

10. What symbol signifies the beginning of a comment in


Python?
11. How do Python comments end?
12. Which is better, too many comments or too few
comments?
13. What is printed by the following code fragment?
x1 = 2
x2 = 2
x1 += 1
x2 -= 1
print(x1)
print(x2)
Why does the output appear as it does?
Chapter Four

Conditional
Execution
Boolean Expressions

• Arithmetic expressions evaluate to numeric values; a


Boolean expression, sometimes called a predicate,
may have only one of two possible values: false or true.
• The term Boolean comes from the name of the British
mathematician George Boole.
• A branch of discrete mathematics called Boolean
algebra is dedicated to the study of the properties and
the manipulation of logical expressions.
• While on the surface Boolean expressions may appear
very limited compared to numeric expressions, they are
essential for building more interesting and useful
programs.
Cont---

• The simplest Boolean expressions in Python


are True and False.
• We see that bool is the name of the class
representing Python’s Boolean expressions.
# Assign some Boolean variables
a = True
b = False
print('a =', a, ' b =', b)
# Reassign a
a = False
print('a =', a, ' b =', b)
The Python relational operators
Cont---

• We have seen that the simplest Boolean


expressions are False and True, the Python
Boolean literals.
• A Boolean variable is also a Boolean expression.
• An expression comparing numeric expressions
for equality or inequality is also a Boolean
expression.
• The simplest kinds of Boolean expressions use
relational operators to compare two
expressions.
Cont---

• An expression like 10 < 20 is legal but of little


use, since 10 < 20 is always true; the
expression True is equivalent, simpler, and less
likely to confuse human readers.
• Since variables can change their values during
a program’s execution, Boolean expressions
are most useful when their truth values
depend on the values of one or more
variables.
Cont---
• >>> x = 10
>>> x
10
>>> x < 10
False
>>> x <= 10
True
>>> x == 10
True
>>> x >= 10
True
>>> x > 10
False
>>> x < 100
True
>>> x < 5
False
Cont---

• The first input in the shell binds the variable x to the value 10. The
other expressions experiment with the
relational operators. Exactly matching their mathematical
representations, the following expressions all are
equivalent:
• x < 10
• 10 > x
• !(x >= 10)
• !(10 <= x)
The relational operators are binary operators and are all left
associative. They all have a lower precedence than any of the
arithmetic operators; therefore, Python evaluates the expression
x + 2 < y / 10
as if parentheses were placed as so:
(x + 2) < (y / 10)
The Simple if Statement

• Example
• print('Please enter two numbers to divide.')
dividend = int(input('Please enter the first
number to divide: '))
divisor = int(input('Please enter the second
number to divide: '))
# If possible, divide them and report the result
if divisor != 0:
print(dividend, '/', divisor, "=", dividend/divisor)
Output

• The program may not always execute the print statement.


In the following run
Please enter two numbers to divide.
Please enter the first number to divide: 32
Please enter the second number to divide: 8
32 / 8 = 4.0
the program executes the print statement, but if the user
enters a zero as the second number:
Please enter two numbers to divide.
Please enter the first number to divide: 32
Please enter the second number to divide: 0
• the program prints nothing after the user enters the
values.
The general form of the if statement is:

The reserved word if begins a if statement.


• The condition is a Boolean expression that determines whether or not the
body will be executed. A
colon (:) must follow the condition.
• The block is a block of one or more statements to be executed if the
condition is true. The statements
within the block must all be indented the same number of spaces from the left.
The block within an if must be indented more spaces than the line that begins
the if statement. The block technically is
part of the if statement. This part of the if statement is sometimes called the
body of the if.
Cont---

• Python requires the block to be indented. If the block contains


just one statement, some programmers will place it on the
same line as the if; for example, the following if statement that
optionally assigns y:
if x < 10:
y=x
could be written
if x < 10: y = x
but may not be written as
if x < 10:
y=x
because the lack of indentation hides the fact that the
assignment statement optionally is executed. Indentation is
how Python determines which statements make up a block.
Cont---

• How many spaces should you indent?


• Python requires at least one, some programmers
consistently usetwo, four is the most popular number,
but some prefer a more dramatic display and use
eight.
• A four space indentation for a block is the
recommended Python style. This text uses the
recommended four spaces to set off each enclosed
block. In most programming editors you can set the
Tab key to insert spaces automatically so you need not
count the spaces as you type. Whichever indent
distance you choose, you must use this same distance
consistently throughout a Python program.
Example

• # Get two integers from the userdividend =


int(input('Please enter the number to divide: '))
divisor = int(input('Please enter dividend: '))# If
possible, divide them and report the resultif
divisor != 0:
quotient = dividend/divisor
print(dividend, '/', divisor, "=", quotient)
print('Program finished')
Cont---

• The assignment statement and first printing statement


are both a part of the block of the if.
• Given the truth value of the Boolean expression divisor !=
0 during a particular program run, either both statements
will be executed or neither statement will be executed.
• The last statement is not indented, so it is not part of the
if block. The program always prints Program finished,
regardless of the user’s input.

• Remember when checking for equality, as in


if x == 10:
print('ten')
Cont---

• to use the relational equality operator (==), not the


assignment operator (=).
As a convenience to programmers, Python’s notion
of true and false extends beyond what we ordinarily
would consider Boolean expressions. The statement
if 1:
print('one')
always prints one, while the statement
if 0:
print('zero')
Cont---

• never prints anything. Python considers the integer


value zero to be false and treats every other integer
value, positive and negative, to be true. Similarly, the
floating-point value 0.0 is false, but any other
floating-point
value is true. The empty string ('' or "") is considered
false, and any nonempty string is interpreted as true.
Any Python expression can serve as the condition for
an if statement. In later chapters we will explore
additional kinds of expressions and see how they
relate to Boolean conditions.
Example
The if/else Statement

• The if statement has an optional else block that is


executed only if the Boolean condition
is false.
Example
# Get two integers from the user
dividend = int(input('Please enter the number to divide: '))
divisor = int(input('Please enter dividend: '))
# If possible, divide them and report the result
if divisor != 0:
print(dividend, '/', divisor, "=", dividend/divisor)
else:
print('Division by zero is not allowed')
Output
Please enter the number to divide: 32
Please enter dividend: 0
Division by zero is not allowed
• The else block contains an alternate block of
code that the program executes when the
condition is false.
If else flow chart
Cont---

• Another application may handle the


situation in a different way; for example, it may
substitute some default value for divisor
instead of zero.
The general form of an if/else statement is
Cont---
• The reserved word if begins the if/else statement.
The condition is a Boolean expression that determines whether
or not the if block or the else block will be executed. A colon (:)
must follow the condition.
• The if-block is a block of one or more statements to be executed
if the condition is true. As with all blocks, it must be indented
one level deeper than the if line. This part of the if statement is
sometimes called the body of the if.
• The reserved word else begins the second part of the if/else
statement. A colon (:) must follow the else.
• The else-block is a block of one or more statements to be
executed if the condition is false. It must be indented one level
deeper than the line with the else. This part of the if/else
statement is sometimes called the body of the else.
• The else block, like the if block, consists of one or more
statements indented to the same level.
Example

• Some programmers prefer to use the parentheses as


shown here even though they are not required. The
parentheses improve the readability of complex
expressions, and the interpreted code is no less
efficient.
Python allows an expression like:
x <= y and y <= z
which means x ≤ y ≤ z to be expressed more naturally:
x <= y <= z
Similarly, Python allows a programmer to test the
equivalence of three variables as
if x == y == z:
print('They are all the same')
Example

• The following section of code assigns the indicated values to a bool:

x != y
and
not (x == y)
and
x < y or x > y
x=10 b=(x==10 or y==20)
y=20 Print(b)
b=(x==10) b=(x!=10 or y==20)
print(b) print(b)
b=(x!=10) b=(x==10 or y!=20)
b=(x==10 and y==20) print(b)
print(b)
b=(x!=10 or y!=20)
b=(x!=10 and y==20)
print(b)
print(b)
b=(x==10 and y!=20)
print(b)
b=(x!=10 and y!=20)
print(b)
The pass Statement

• Some beginning programmers attempt to


use an if/else statement when a simple if
statement is more appropriate; for example,
in the following code fragment the
programmer wishes to do nothing if the
value of the variable x is less than zero;
otherwise, the programmer wishes to print
x’s value:
Cont---

• if x < 0:
# Do nothing (This will not work!)
else:
print(x)

• If the value of x is less than zero, this section of code should print
nothing.
• Unfortunately, the code fragment above is not legal Python.
• The if/else statement contains an else block, but it does not contain
an if block.
• The comment does not count as a Python statement.
• Both if and if/else statements require an if block that contains at
least one statement.
• Additionally, an if/else statement requires an else block that
contains at least one statement
Cont---
• Python has a special statement, pass, that means do nothing. We may
use the pass statement in our code in places where the language
requires a statement to appear but we wish the program to take no
action whatsoever. We can make the above code fragment legal by
adding a pass statement:
if x < 0:
pass # Do nothing
else:
print(x)
While the pass statement makes the code legal, we can express its logic
better by using a simple if statement. In mathematics, if the expression
x < y is false, it must be the case that x ≥ y. If we invert the truth
value of the relation within the condition, we can express the above
code more succinctly as
if x >= 0:
print(x)
Cont---

• So, if you ever feel the need to write an if/else statement with
an empty if body, do the following instead:
1. invert the truth value of the condition
2. make the proposed else body the if body
3. eliminate the else
In situations where you may be tempted to use a non-functional
else block, as in the following:
if x == 2:
print(x)
else:
pass # Do nothing if x is not equal to 2
do not alter the condition but simply eliminate the else and the
else block altogether:
if x == 2:
print(x) # Print only if x is equal to 2
Cont---

• The pass statement in Python is useful for


holding the place for code to appear in the
future; for
example, consider the following code fragment:
if x < 0:
pass # TODO: print an appropriate warning
message to be determined
else:
print(x)
Cont---

• In this code fragment the programmer intends to


provide an if block, but the exact nature of the
code in the if block is yet to be determined. The
pass statement serves as a suitable placeholder
for the future code.
• The included comment documents what is
expected to appear eventually in place of the
pass statement.
• We will see other uses of the pass statement as
we explore Python more deeply.
Floating-point Equality

• The equality operator (==) checks for


exact equality. This can be a problem
with floating-point numbers,
since floating-point numbers
inherently are imprecise.
• The following example demonstrates
the perils of using the equality
operator with floating-point numbers.
Example

In mathematics, we expect the following equality


to hold:
1.11-1.10 = 0.01 = 2.11-2.10
Cont---

• The output of the first print statement in in the


example above reminds us of the imprecision
of floating-point numbers:
d1 = 0.010000000000000009
d2 = 0.009999999999999787
Since the expression
d1 == d2
checks for exact equality, the program reports
that d1 and d2 are different.
Cont---

• The solution is not to check floating-point


numbers for exact equality, but rather see if the
values “close enough” to each other to be
considered the same.
• If d1 and d2 are two floating-point numbers, we
need to check if the absolute value of the d1 -
d2 is a very small number.
Example
Cont---
Nested Conditionals
• The statements in the block of the if or the
else may be any Python statements,
including other if/else statements.
• We can use these nested if statements to
develop arbitrarily complex program logic.
Consider the next example that
determines if a number is between 0 and
10, inclusive.
Example

value=int(input("Please enter an Integer value in the


range of 0 to 10:"))
if value>=0:
if value<=10:
print("The value you entered is in range.")
print("Well Done")
Cont---
• The above example behaves as follows:

• The executing program checks first condition. If value is less than


zero, the program does not evaluate the second condition and it
continues its execution with the statement following the outer if.
The statement after the outer if simply prints Done.

• If the executing program finds the value variable to be greater


than or equal to zero, it executes the
statement within the if-block. This statement is itself an if
statement.
• The program thus checks the second (inner) condition. If the
second condition is satisfied, the program displays the In range
message; otherwise, it does not.
• Regardless, the program eventually prints the Done message.
Cont---

• We say that the second if (with the comment Second check) is nested
within the first if (First check).

• We call the first if the outer if and the second if the inner if. Notice the
entire inner if statement is indented one level relative to the outer if
statement. This means the inner if’s block, the print("In range")
statement, is indented two levels deeper than the outer if statement.
• Remember that if you use four spaces as the distance for a
indentation level, you must consistently use this four space distance
for each indentation level throughout the program.

• Both conditions of this nested if construct must be met for the In


range message to be printed. Said another way, the first condition and
the second condition must be met for the program to print the In
range message.
Example
Cont---

• The above example provides a more


specific message instead of a simple
notification of acceptance.
• Exactly one of three messages is printed
based on the value of the variable.
• A single if or if/else statement cannot
choose from among more than two
different execution paths.
Binary conversion example

# Get number from the user


value = int(input("Please enter an integer value in the range 0...1023:
"))
# Create an empty binary string to build upon
binary_string = ''
# Integer must be less than 1024
if 0 <= value < 1024:
if value >= 512:
binary_string += '1’
value %= 512
else:
binary_string += '0'
if value >= 256:
binary_string += '1’
value %= 256
else:
binary_string += '0'
C o n t-

binary_string += '1’ else:


value %= 128 binary_string += '0'
else:
if value >= 4:
binary_string += '0'
if value >= 64: binary_string += '1’
binary_string += '1’ value %= 4
value %= 64 else:
else: binary_string += '0'
binary_string += '0' if value >= 2:
if value >= 32:
binary_string += '1’
binary_string += '1’
value %= 32 value %= 2
else: else:
binary_string += '0' binary_string += '0’
if value >= 16: binary_string +=
binary_string += '1’ str(value)
value %= 16 # Display the results
else:
binary_string += '0'
if binary_string != ‘’:
if value >= 8: print(binary_string)
binary_string += '1’ else:
value %= 8 print('Cannot convert')
Cont---

• The outer if checks to see if the value the user provides is


in the proper range.
• The program works only for numbers in the range 0 ≤
value < 1, 024.
• Each inner if compares the user-supplied entered integer
against decreasing powers of two. If the
number is large enough, the program:
– prints appends the digit (actually character) 1 to the
binary string under construction, and
– removes via the remainder operator that power of
two’s contribution to the value.
If the number is not at least as big as the given power of
two, the program concatenates a 0 instead and moves on
without modifying the input value.
Simpler binary conversion

# Get number from the user


value = int(input("Please enter an integer value
in the range 0...1023: "))
# Initial binary string is empty
binary_string = ''
# Integer must be less than 1024
if 0 <= value < 1024:
binary_string += str(value//512)
value %= 512
binary_string += str(value//256)
Cont--

value %= 256
binary_string += str(value//128)
value %= 128
binary_string += str(value//64)
value %= 64
binary_string += str(value//32)
value %= 32
binary_string += str(value//16)
value %= 16
binary_string += str(value//8)
value %= 8
binary_string += str(value//4)
value %= 4
binary_string += str(value//2)
value %= 2
binary_string += str(value)
# Report results
if binary_string != '':
print(binary_string)
else:
print('Unable to convert')
Cont---

• The sole if statement in the above


example ensures that the user
provides an integer in the proper
range.
• A clever sequence of integer
arithmetic operations replace the
original conditional logic.
Chapter Five

Iteration
Cont---

• Iteration repeats the execution of a


sequence of code.
• Iteration is useful for solving many
programming problems.
• Iteration and conditional execution
form the basis for algorithm
construction.
The while Statement
• The following program counts to five by printing
a number on each output line.
print(1)
print(2)
print(3)
print(4)
print(5)
Cont---
• When executed, this program displays
1
2
3
4
5
Cont---
• How would you write the code to count to 10,000? Would
you copy, paste, and modify 10,000 printing statements?
• You could, but that would be impractical! Counting is such
a common activity, and computers routinely count up to
very large values, so there must be a better way.
• What we really would like to do is print the value of a
variable (call it count), then increment the variable (count
+= 1), and repeat this process until the variable is large
enough (count == 5 or maybe count == 10000).
• This process of executing the same section of code over
and over is known as iteration, or looping. Python has two
different statements, while and for, that enable iteration.
Example

count = 1 # Initialize counter


while count <= 5: # Should we continue?
print(count) # Display counter, then
count += 1 # Increment counter
Cont----
• The while statement in Listing 5.2 ([Link]) repeatedly
displays the variable count. The program executes the following block of
statements five times:
print(count)
count += 1
• After each redisplay of the variable count, the program increments it by
one. Eventually (after five iterations),
• the condition count <= 5 will no longer be true, and the block is no longer
executed.
• to count up to 10,000—just change the literal value 5 to 10000.
• The line while count <= 5:
• begins the while statement. The expression following the while keyword
is the condition that determines if the statement block is executed or
continues to execute. As long as the condition is true, the program
executes the code block over and over again. When the condition
becomes false, the loop is finished. If the condition is false initially, the
program will not execute the code block within the body of the loop at all.
The while statement has the general form:

• The reserved word while begins the while statement.


• The condition determines whether the body will be (or will
continue to be) executed.
• A colon (:) must follow the condition.
• block is a block of one or more statements to be executed as long
as the condition is true. As a block, all the statements that comprise
the block must be indented one level deeper than the line that
begins the while statement. The block technically is part of the
while statement.
Cont---

• Except for the reserved word while instead of if,


while statements look identical to if statements.
• Sometimes beginning programmers confuse the
two or accidentally type if when they mean
while or vice-versa. Usually the very different
behavior of the two statements reveals the
problem immediately;
• however, sometimes, especially in nested,
complex logic, this mistake can be hard to
detect.
Cont---
Cont---

• The executing program checks the condition before


executing the while block and then checks the
condition again after executing the while block.
• As long as the condition remains truth, the program
repeatedly executes the code in the while block.
• If the condition initially is false, the program will not
execute the code within the while block.
• If the condition initially is true, the program executes
the block repeatedly until the condition becomes
false, at which point the loop terminates.
Example
Output of the above program
Cont----

• entry != 'N' and entry != 'n'


• The above program is a program that
allows a user to enter any number of
nonnegative integers.
• When the user enters a negative value,
the program no longer accepts input, and
it displays the sum of all the nonnegative
values. If a negative number is the first
entry, the sum is zero.
Cont----

• The following incorporates a while statement so


that the program’s execution continues until the
problem is resolved or its resolution is beyond
the capabilities of the program.
Cont---

• We can use a while statement to make thimgs


more convenient for the user.
• Recall that the computer troubleshooting program
forces the user to rerun the program once a
potential program has been detected (for
example, turn on the power switch, then run the
program again to see what else might be wrong).
• A more desirable decision logic is shown on the
next slide that incorporates a while statement so
that the program’s execution continues until the
problem is resolved or its resolution is beyond the
capabilities of the program.
Example
Example Continued------
Cont---

• The Boolean variable done controls the loop; as long as done


is false, the loop continues.
• A Boolean variable like done used in this fashion is often
called a flag. You can think of the flag being down when the
value is false and raised when it is true.
• In this case, when the flag is raised, it is a signal that the loop
should terminate.
• It is important to note that the expression not done ofthe
while statement’s condition evaluates to the opposite truth
value of the variable done; the expression does not affect the
value of done.
• In other words, the not operator applied to a variable does
not modify the variable’s value. In order to actually change
the variable done, you would need to reassign it, as in done =
not done # Invert the truth value
Cont---

• In the above example, we have no need to invert done’s value. We ensure that done’s value
is False initially and then make it True when the user has exhausted the program’s options.
In Python, sometimes it is convenient to use a simple value as conditional expression in an
if or while statement. Pythoninterpretstheintegervalue0andfloating-
pointvalue0.0bothasFalse. Allotherinteger and floating-point values, both positive and
negative, are considered True. This means the following code:
• x = int(input()) # Get integer from user while x: print(x) # Print x only if x is nonzero x -= 1 #
Decrement x
• is equivalent to
• x = int(input()) # Get integer from user while x != 0: print(x) # Print x only if x is nonzero x -=
1 # Decrement x
• we have no need to invert done’s value. We ensure that done’s value is False initially and
then make it True when the user has exhausted the program’s options. In Python,
sometimes it is convenient to use a simple value as conditional expression in an if or while
statement. Pythoninterpretstheintegervalue0andfloating-pointvalue0.0bothasFalse.
Allotherinteger and floating-point values, both positive and negative, are considered True.
This means the following code:
• x = int(input()) # Get integer from user while x: print(x) # Print x only if x is nonzero x -= 1 #
Decrement x
• is equivalent to
• x = int(input()) # Get integer from user while x != 0: print(x) # Print x only if x is nonzero x -=
1 # Decrement x
The for Statement
• The for statement iterates over a sequence of values. One way to
express a sequence is via a tuple, as shown here:
– for n in 1, 2, 3, 4, 5, 6, 7, 8, 9, 10:
– print(n)
• This code behaves identically to the while loop above. The print
statement here executes exactly 10 times. The code first prints 1, then 2,
then 3, etc.
• The final value it prints is 10. During the iteration the variable n thus
assumes, in order, all the values that make up the tuple.
• It usually is cumbersome to explicitly list all the elements of a tuple,and
often it is impractical. Consider iterating over all the integers from 1 to
1,000—writing out all the tuple’s elements would be unwieldy.
• Fortunately, Python provides a convenient way to express a sequence of
integers that follow a regular pattern. The following code uses a range
expression to print the integers 1 through 10:
– for n in range(1, 11):
– print(n)
Cont---

• The expression range(1, 11) creates a range object that


allows the for loop to assign to the variable n the
values 1, 2, ..., 10.
• Conceptually, the expression range(1, 11) represents
the sequence of integers 1,2,3,4,5,6,7,8,9,10.
• The line for n in range(1, 11): is best read as “For each
integer n in the range 1≤n < 11.”
• During the first iteration of the loop, n’s value is 1
within the block.
• In the loop’s second iteration, n has the value of 2.
• Each time through the loop, n’s value increases by one.
The code within the block will use the values of n up to
10.
Cont---
• The general form of the range expression is
– range( begin,end,step )
where
• begin is the first value in the range; if omitted, the default
value is 0 • end is one past the last value in the range; the end
value is always required and may not be omitted • step is the
amount to increment or decrement; if the step parameter is
omitted, it defaults to 1(counts up by ones)
• begin, end, and step must all be integer expressions; floating-
point expressions and other types are not allowed. The
arguments in the range expression may be literal numbers
(like 10), variables (like x, if x is bound to an integer), and
arbitrarily complex integer expressions. The range expression
is very flexible. Consider the following loop that counts down
from 21 to 3 by threes: for n in range(21, 0, -3): print(n, end='
')
Cont---

• It prints
– 21 18 15 12 9 6 3
• Thus range(21, 0, -3) represents the sequence
21,18,15,12,9,6,3.
• The expression range(1000) produces the
sequence 0,1,2,...,999.
– The following code computes and prints the sum
of all the positive integers less than 100:
– sum = 0 # Initialize sum
– for i in range(1, 100):
– sum += i print(sum)
Example

• for i in range(16):
• print('{0:3} {1:16}'.
• format(i, 10**i))
Nested Loops

You might also like