0% found this document useful (0 votes)
1 views80 pages

Programming Essentials in Python

The document serves as a comprehensive guide to Programming Essentials in Python, covering fundamental concepts such as computer basics, programming languages, and the Python environment. It includes chapters on writing Python programs, basic data types, operators, mathematical functions, and control structures like selections and loops. The aim is to equip readers with the necessary skills to effectively use Python for various applications, regardless of their prior programming experience.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views80 pages

Programming Essentials in Python

The document serves as a comprehensive guide to Programming Essentials in Python, covering fundamental concepts such as computer basics, programming languages, and the Python environment. It includes chapters on writing Python programs, basic data types, operators, mathematical functions, and control structures like selections and loops. The aim is to equip readers with the necessary skills to effectively use Python for various applications, regardless of their prior programming experience.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Notes about Programming Essentials in Python

1
Table of Content

Contents
Notes about Programming Essentials in Python ................................................ 1
Chapter 1: Introduction to Computers, Programs, and Python ............................. 4
1. What is a computer? ...................................................................................... 5
2. Programming Languages............................................................................... 6
2.1 Machine Language ............................................................................................. 6
2.2 High-Level Language ......................................................................................... 7
2.3 Getting Started with Python ................................................................................. 9
The Problem Analysis–Coding–Execution Cycle ........................................... 9
Python Tools for development. ..................................................................... 13
Creating Python Source Code Filest ...................................................................... 14
Using Python to Perform Mathematical Computations ................................ 16
Programming Errors ........................................................................................... 16
2.4 End of chapter Questions............................................................................... 18
Chapter 2: Write your first Python program ....................................................... 23
1. First Python Program .................................................................................. 23
2. Python Comments ....................................................................................... 23
3. Variables ...................................................................................................... 24
4. Rules for Valid Variable Names ................................................................. 26
4. Descriptive names are better than short names ........................................... 27
2.4 End of chapter Questions............................................................................... 28
Chapter 3: Basic data types and operators........................................................... 32
3.1 Operators................................................................................................... 32
3.2 Standard Data Types................................................................................. 32
Numbers ......................................................................................................... 33
2
String .............................................................................................................. 35
List ................................................................................................................. 40
Tuple .............................................................................................................. 41
Dictionary ...................................................................................................... 44
3.3 End of Chapter Questions ......................................................................... 45
Chapter 4: Mathematical functions, strings ......................................................... 46
4.1 Common Python Functions ........................................................................... 46
4.2 Reading Strings from the Console .......................................................... 49
4.3 End of Chapter Questions ........................................................................ 50
Chapter 5: Selections ........................................................................................... 52
if Statements ..................................................................................................... 52
Two-Way if-elseStatements ............................................................................... 54
Nested if and Multi-Way if-elif-else Statements .................................. 58
Common Errors in Selection Statements ................................................................ 60
End of Chapter Questions ................................................................................. 62
Chapter 6: Loops.................................................................................................. 65
6.1 The while Loop .............................................................................................. 66
6.2 The for Loop ................................................................................................. 69
6.3 Nested Loops ................................................................................................. 70
6.4 Keywords break and continue ......................................................................... 71
6.5 End of Chapter Questions ........................................................................... 76
References ............................................................................................................ 80

3
Chapter 1: Introduction to Computers,
Programs, and Python

This book provides an introduction to the Python programming language. Python is

a popular open source programming language used for both standalone programs

and scripting applications in a wide variety of domains. It is free, portable,

powerful, and remarkably easy and fun to use. Programmers from every corner of

the software industry have found Python’s focus on developer productivity and

software quality to be a strategic advantage in projects both large and small.

Whether you are new to programming or are a professional developer, this book’s

goal is to bring you quickly up to speed on the fundamentals of the core Python

language.

The benefits of using Python Some common terms you should know to get started

How to download Python and the other programs you will need to get started Some

of the basic functions and commands with Python Learning what comments are as

well as strings and more functions Learning what variables are and how they can

help you do in Python Getting started in programming can be scary, but Python

makes it easy. After reading this book, you will know enough about Python to

apply it in whatever application domains you choose to explore.


4
1. What is a computer?
A computer includes both hardware and software. In general, hardware comprises the

visible, physical elements of the computer, and software provides the invisible instructions

that control the hardware and make it perform specific tasks. Knowing computer

hardware isn’t essential to learning a programming language, but it can help you better

understand the effects that a program’s instructions have on the computer and its

components. This section introduces com- puter hardware components and their functions.

A computer consists of the following major hardware components (Figure 1):

■ A central processing unit (CPU)

■ Memory (main memory)

■ Storage devices (such as disks and CDs)

■ Input devices (such as the mouse and keyboard)

■ Output devices (such as monitors and printers)

■ Communication devices (such as modems and network interface cards)

5
2. Programming Languages
Computers do not understand human languages, so programs must be written in a

language a computer can use. There are hundreds of programming languages, and they were

developed to make the programming process easier for people. However, all programs

must be converted into a language the computer can understand.

2.1 Machine Language


A computer’s native language, which differs among different types of computers, is its

machine language—a set of built-in primitive instructions. These instructions are in the
6
form of binary code, so if you want to give a computer an instruction in its native language,

you have to enter the instruction as binary code. For example, to add two numbers, you

might have to write an instruction in binary code, like this:

1101101010011010

2.2 High-Level Language


There are many high-level programming languages, and each was designed for a

specific purpose. Table 1 lists some popular ones.

A program written in a high-level language is called a source program or source code.

Because a computer cannot understand a source program, a source program must be

7
translated into machine code for execution. The translation can be done using another

programming tool called an interpreter or a compiler.

• An interpreter reads one statement from the source code, translates it to the

machine code or virtual machine code, and then executes it right away.

• A compiler translates the entire source code into a machine-code file, and the

machine code file is then executed.

Figure An interpreter translates and executes a program one statement at a time. (b) A compiler
translates the entire source program into a machine-language file for execution.

8
2.3 Getting Started with Python

• Python is one of the world's most popular programming languages.

• Python is a high-level language that can be used to create high-performance

applications.

• Simple, Easy to learn, and open source.

• Its syntax is clear and emphasizes readability.

• Python has a large and comprehensive standard library.

The Problem Analysis–Coding–Execution Cycle

9
How to Download and Install Python?

Steps to Download Python on Windows 10.

Step 1: First and foremost step is to open a browser and type

[Link]

Step 2: Underneath the Python Releases for Windows find the Latest Python 3 Release

– Python 3.11.2 (the latest stable release as of now is Python 3.11.2).

Python installation

10
Step 3: On this page move to Files and click on Windows x86-64 executable

installer for 64-bit or Windows x86 executable installer for 32-bit.

Here we are providing the installation process of Python 3.11.2 on

Windows

• Run the Python Installer for how to install Python on the

Windows downloads folder

• Make sure to mark Add Python 3.11 to PATH otherwise you

will have to do it explicitly. It will start installing Python on

Windows.

11
• After installation is complete click on Close. Now go to Windows and type
IDLE.

Python Shell

12
• This is Python Interpreter also called Python Shell. I printed Hello geeks, python

is working smoothly.

• The three greater than >>> sign is called the Python command prompt, where we

write our program and with a single enter key, it will give results so instantly.

Python Tools for development.


➢ Compiler.

✓ Python 3

➢ Text Editor

✓ Atom, Sublime, Notepad++

➢ Editor with the compiler:

Fig. 1 Python Tools for development.

13
Creating Python Source Code Filest
Entering Python statements at the statement prompt >>> is convenient, but the statements

are not saved. To save statements for later use, you can create a text file to store the

statements and use the following command to execute the statements in the file:

python [Link]

The text file can be created using a text editor such as Notepad. The text file, filename, is

called a Python source file or script file, or module. By convention, Python files are named

with the extension .py.

Running a Python program from a script file is known as running Python in script mode.

Typing a statement at the statement prompt >>> and executing it is called running Python

in interactive mode.

1 # Display two messages

2 print("Welcome to Python")

3 print("Python is fun")

When the Python interpreter sees #, it ignores all text after # on the same line.

When it sees ''', it scans for the next ''' and ignores any text between the

triple quotation marks. Here are examples of comments:

# This program displays Welcome to Python


''' This program displays Welcome to Python andPython is
fun
14
'''
# Display two messages print("Welcome to Python")
print("Python is fun")

Python programs are case sensitive. It would be wrong, for example, to replace print in

the program with Print. You have seen several special characters (#, ", ()) in the

program. They are used in almost every program. Table 2 summarizes their uses.

15
Using Python to Perform Mathematical Computations
Python programs can perform all sorts of mathematical computations and display the
result. To display the addition, subtraction, multiplication, and division of two numbers, x
and y, use the following code:
print(x + y)
print(x – y)
print(x * y)
print(x / y)

Programming Errors
Programming errors can be categorized into three types: syntax errors, runtime errors,
and logic errors.

1- Syntax Errors

The most common error you will encounter are syntax errors. Like any programming
language, Python has its own syntax, and you need to write code that obeys the syntax
rules. If your program violates the rules—for example, if a quotation mark is missing or a
word is misspelled—Python will report syntax errors.
Syntax errors result from errors in code construction, such as mistyping a statement, incor-
rect indentation, omitting some necessary punctuation, or using an opening parenthesis
with- out a corresponding closing parenthesis. These errors are usually easy to detect,
16
because Python tells you where they are and what caused them. For example, the following
print statement has a syntax error.

2- Runtime Errors

Runtime errors are errors that cause a program to terminate abnormally. They occur while

a program is running if the Python interpreter detects an operation that is impossible to

carry out. Input mistakes typically cause runtime errors. An input error occurs when the

user enters a value that the program cannot handle. For instance, if the program expects to

read in a number, but instead the user enters a string of text, this causes data-type errors to

occur in the program.

Another common source of runtime errors is division by zero. This happens when the
divisor is zero for integer divisions. For example, the expression 1 / 0 in the following
statement would cause a runtime error.

17
3- Logic Errors
Logic errors occur when a program does not perform the way it was intended to. Errors of

this kind occur for many different reasons. For example, suppose you wrote the program

to convert a temperature (35 degrees) from Fahrenheit to Celsius.

2.4 End of chapter Questions


Q) Choose the best answers

18
19
20
21
22
Chapter 2: Write your first Python program
1. First Python Program
"Hello, World!" is a simple program that outputs Hello, World! on the screen.

1. Create a file and save it with .py extension and then write the following
code.
2. type the word print followed by a set of parentheses with the text "Hello,
World" inside:
>> print("Hello, World")

The output will be → Hello, World


3. You can display any number of items in a print statement using the
following syntax:
print(item1, item2, ..., item k)

2. Python Comments
Comments in Python are the lines in the code that are ignored by the interpreter during the
execution of the program. Comments enhance the readability of the code and help the
programmers to understand the code very carefully. Types of comments in Python:
1. Single line Comments:

Python single-line comment starts with the hashtag symbol (#) with no white spaces and
lasts till the end of the line. If the comment exceeds one line then put a hashtag on the next
line and continue the Python Comments. Python’s single-line comments are proved useful
for supplying short explanations for variables, function declarations, and expressions. For
example
23
# Print “GeeksforGeeks !” to console

print("GeeksforGeeks")

Output
GeeksforGeeks

2. Multiline Comments:

Python does not provide the option for multiline comments. However, there are different
ways through which we can write multiline comments. Multiline comments using multiple
hashtags (#). We can multiple hashtags (#) to write multiline comments in Python. Each
and every line will be considered as a single-line comment. For example
# Python program to demonstrate

# multiline comments

print("Multiline comments")

Output
Multiline comments

Comments can be used to explain Python code. It can be used to make the code
more readable. Comments can be used to prevent execution when testing code.

3. Variables
In Python, variables are names that can be assigned a value and then used to refer
to that value throughout your code. Variables are fundamental to programming for
two reasons:

1. Variables keep values accessible: For example, you can assign the result of
some time-consuming operation to a variable so that your program doesn’t
have to perform the operation each time you need to use the result.

24
2. Variables give values context: The number 28 could mean lots of different
things, such as the number of students in a class, the number of times a user has
accessed a website, and so on. Giving the value 28 a name like num_students
makes the meaning of the value clear.

In this section, you’ll learn how to use variables in your code, as well as some of
the conventions Python programmers follow when choosing names for variables.

Values are assigned to variable names using a special symbol called the
assignment operator (=) . The = operator takes the value to the right of the operator
and assigns it to the name on the left.

Let’s modify the hello_world.py file from the previous section to assign some text
in a variable before printing it to the screen:

On the first line, you create a variable named greeting and assign it the value "Hello,
World" using the = operator.

print(greeting) displays the output Hello, World because Python looks for the name
greeting, finds that it’s been assigned the value "Hello, World", and replaces the
variable name with its value before calling the function. If you hadn’t executed
greeting = "Hello, World" before executing (greeting), then you would have seen a
NameError like you did when you tried to execute print(Hello, World) in the
previous section.

25
Variable names are case sensitive, so a variable named greeting is not the same as a
variable named Greeting. For instance, the following code produces a NameError:

4. Rules for Valid Variable Names


Variable names can be as long or as short as you like, but there are a few rules that
you must follow. Variable names may contain uppercase and lowercase letters (A–
Z, a–z), digits (0–9), and underscores (_), but they cannot begin with a digit.

26
For example, each of the following is a valid Python variable name:

➢ string1

➢ _a1p4a

➢ list_of_names

The following aren’t valid variable names because they start with a digit:

➢ 9lives

➢ 99_balloons

➢ 2beOrNot2Be

4. Descriptive names are better than short names

Descriptive variable names are essential, especially for complex programs. Writing
descriptive names often requires using multiple words. Don’t be afraid to use long
variable names.
In the following example, the value 3600 is assigned to the variable s:

s = 3600

27
The name s is totally ambiguous. Using a full word makes it a lot easier to
understand what the code means:
seconds = 3600

seconds is a better name than s because it provides more context. But it still doesn’t
convey the full meaning of the code. Is 3600 the number of seconds it takes for a
process to finish, or is it the length of a movie?

There’s no way to tell. The following name leaves no doubt about what the code
means:

seconds_per_hour = 3600

When you read the above code, there’s no question that 3600 is the number of
seconds in an hour. seconds_per_hour takes longer to type than both the single
letter s and the word seconds, but the payoff in clarity is massive.

Although naming variables descriptively means using longer variable names, you
should avoid using excessively long names. A good rule of thumb is to limit
variable names to three or four words maximum.

2.4 End of chapter Questions


Q) Choose the best answers

28
29
30
31
Chapter 3: Basic data types and operators
Python, a widely used high-level programming language, offers various built-in
data types and operators. Here's a brief overview of both.

3.1 Operators
These are special symbols which help the user to carry out operations like addition,
subtraction, etc. Python provides following type of operators:

Arithmetic operators: +, –, *, /, %, ** and //.

Assignment operators: =, + =, – =, *=, /=, %=, **= and //=

Logical operators: or, and, and not

Relational operators: <, <=, >, >=, != or < > and ==.

3.2 Standard Data Types


Data types are the classification or categorization of data items. It represents the
kind of value that tells what operations can be performed on a particular data.
Since everything is an object in Python programming, data types are actually
classes and variables are instances (object) of these classes. The data stored in
memory can be of many types. Python has five main standard data types:

➢ Numbers

➢ String

➢ List

32
➢ Tuple

➢ Dictionary

Numbers

Number data types store numeric values. Number objects are created when you assign a
value to them.
Python supports different numerical types:
➢ int for integer numbers : Int, or integer, is a whole number, positive or negative,
without decimals, of unlimited length.

➢ float for decimal numbers: Float, or "floating point number" is a number, positive or
negative, containing one or more decimals.

➢ complex for complex numbers: Complex numbers are written with a "j" as the
imaginary part:

Variables of numeric types are created when you assign a value to them. For example

x = 1 # int
y = 2.8 # float
z = 1j # complex

for example:

33
34
String
A string is a collection of one or more characters put in a single quote, double-
quote, or triple-quote. In python there is no character data type, a character is a
string of length one. It is represented by str class.

Creating String: Strings in Python can be created using single quotes or double
quotes or even triple quotes.

As you’ve already seen, you can create a string by surrounding some text with
quotation marks:

➢ string1 = 'Hello, World'

➢ string2 = "1234"

You can use either single quotes (string1) or double quotes (string2) to create a
string as long as you use the same type at the beginning and end of the string.

35
Whenever you create a string by surrounding text with quotation marks, the string
is called a string literal. The name indicates that the string is literally written out in
your code. All the strings you’ve seen thus far are string literals. A string is
organized as an array of characters. For example:

Strings (Access character):

Example 1:

Example 2:

36
Example 3:

To access a substring from a string, we use a string variable name followed by


square brackets with starting index and ending index of the required substring.

37
For example:

Strings (+, * operators)

38
Strings (Functions)
Example 1:

Example 2:
39
List
Python Lists are just like dynamically sized arrays. A list is a collection of things,
enclosed in [ ] and separated by commas. The list is a sequence data type which is used to
store the collection of data. Tuples and String are other types of sequence data types.

For example:
Here we are creating Python List using [].
Var = ["Geeks", "for", "Geeks"]
print(Var)
Output:
["Geeks", "for", "Geeks"]

40
Tuple
A Tuple is a sequence, just like a list. The differences between tuples and lists are:

➢ the tuples cannot be changed unlike lists

➢ tuples use parentheses (), whereas lists use square brackets [].

➢ Parentheses are optional in tuples.

Creating Python Tuples:

How to access elements from tuple?

41
How to remove the entire tuple?

Tuples (+, * operators)

42
Lists (Functions)

Exercises: Lists & Tuples

43
Dictionary
Dictionary in Python is a collection of keys values, used to store data values like a
map, which, unlike other data types which hold only a single value as an element.

For example:

Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}

print(Dict)

44
3.3 End of Chapter Questions

Write program for the following questions.

45
Chapter 4: Mathematical functions, strings
The focus of this chapter is to introduce functions, strings, and objects, and to use
them to develop programs.

4.1 Common Python Functions


A function is a group of statements that performs a specific task. Python, as well as other
programming languages, provides a library of functions. You have already used the func-
tions eval, input, print, and int. These are built-in functions and they are always avail- able
in the Python interpreter. You don’t have to import any modules to use these functions.
Additionally, you can use the built-in functions abs, max, min, pow, and round, as shown in
Table.

46
Many programs are created to solve mathematical problems. The Python math module
provides the mathematical functions listed in Table.

47
48
4.2 Reading Strings from the Console
To read a string from the console, use the input function. For example, the
following code reads three strings from the keyboard:

s1 = input("Enter a string: ") s2 = input("Enter a string: ") s3 = input("Entera


string: ")print("s1 is " + s1)
print("s2 is " + s2)print("s3 is " + s3)

49
4.3 End of Chapter Questions

50
51
Chapter 5: Selections

In Python, the selection statements are also known as Decision control statements or

branching statements. The selection statement allows a program to test several conditions

and execute instructions based on which condition is true.

if Statements
A one-way if statement executes the statements if the condition is true. Python has several

types of selection statements: one-way if statements, two-way if- else statements, nested if

statements, multi-way if-elif-else statements and conditional expressions. This section

introduces one-way ifstatements.

A one-way if statement executes an action if and only if the condition is true. The syntax

for a one-way if statement is:

if boolean-expression:

statement(s) # Note that the statement(s) must be indented

The statement(s) must be indented at least one space to the right of the if keyword and each

statement must be indented using the same number of spaces.

52
53
Two-Way if-elseStatements

A two-way if-else statement decides which statements to execute based on whether the
condition is true or false. A one-way if statement takes an action if the specified condition
is True. If the condition is False, nothing is done. But what if you want to take one or
more alternative actions when the condition is False? You can use a two-way if-else
statement. The actions that a two-way if-else statement specifies differ based on whether
the condition is True or False.

Here is the syntax for a two-way if-else statement:

if boolean-expression: statement(s)-for-the-true-case
else:
statement(s)-for-the-false-case

The flowchart of the statement is shown in Figure

54
Figure An if-else statement executes statements for the true case if the Boolean expression

evaluates to True; otherwise, statements for the false case are executed.

If the boolean-expression evaluates to True, the statement(s) for the true case are exe-

cuted; otherwise, the statement(s) for the false case are executed. For example, consider

the following code:

if radius >= 0:

area = radius * radius * [Link]

print("The area for the circle of radius", radius, "is", area)

else:

print("Negative input")

If radius >= 0 is true, area is computed and displayed; if it is false, the message

Negative input is displayed.

Here is another example of the if-else statement. This one determines whether a num-

ber is even or odd, as follows:

if number % 2 == 0: print(number, "is even.")

else:

55
print(number, "is odd.")

Suppose you want to develop a program for a first grader to practice subtraction. The pro-

gram randomly generates two single-digit integers, number1 and number2, with

number1 >= number2 and asks the student a question such as "What is 9 – 2? " After the

student enters the answer, the program displays a message indicating whether it is correct.

The program may work as follows:

Step 1: Generate two single-digit integers for number1 and number2.

Step 2: If number1 < number2, swap number1 with number2.

Step 3: Prompt the student to answer, “What is number1 – number2?”

Step 4: Check the student’s answer and display whether the answer is correct. The

complete program is shown here:

56
57
Nested if and Multi-Way if-elif-else Statements

One if statement can be placed inside another if statement to form a nested if

statement.

The statement in an if or if-else statement can be any legal Python statement, including

another if or if-else statement. The inner if statement is said to be nested inside the outer if

statement. The inner if statement can contain another if statement; in fact, there is no limit

to the depth of the nesting. For example, the following is a nested if statement:

if i > k:

if j > k:

print("i and j are greater than k")

The nested if statement can be used to implement multiple alternatives. The statement given

in Figure below, for instance, assigns a letter value to the variable grade according to the

score, with multiple alternatives.

58
59
This style, called multi- way if statements, avoids deep indentation and makes the program

easier to read. The multi-way if statements uses the syntax if-elif-else; elif (short for else if )

is a Python keyword.

Common Errors in Selection Statements

60
61
End of Chapter Questions

62
63
64
Chapter 6: Loops
A loop can be used to tell a program to execute statements repeatedly. Suppose that you

need to display a string (e.g., Programming is fun!) 100 times. It would be tedious to type

the statement 100 times:

So, how do you solve this problem?

Python provides a powerful construct called a loop, which controls how many times in

succession an operation (or a sequence of operations) is performed. By using a loop

statement, you don’t have to code the print statement a hundred times; you simply tell the

computer to display a string that number of times. The loop statement can be written as

follows:

count = 0
while count < 100: print("Programming is fun!")
count = count + 1

The variable count is initially 0. The loop checks whether count < 100 is true. If so, it

executes the loop body—the part of the loop that contains the statements to be repeated—

to display the message Programming is fun! and increments count by 1. It repeatedly exe-
65
cutes the loop body until count < 100 becomes false (i.e., when count reaches 100). At this

point the loop terminates and the next statement after the loop statement is executed.

A loop is a construct that controls the repeated execution of a block of statements. The con-

cept of looping is fundamental to programming. Python provides two types of loop state-

ments: while loops and for loops. The while loop is a condition-controlled loop; it is

controlled by a true/false condition. The for loop is a count-controlled loop that repeats a

specified number of times.

6.1 The whileLoop

A while loop executes statements repeatedly as long as a condition remains true. The

syntax for the while loop is:

while loop-continuation-condition:# Loop body

Statement(s)

Figure below shows the while-loop flowchart. A single execution of a loop body is called

an iteration (or repetition) of the loop. Each loop contains a loop-continuation-condition, a

Boolean expression that controls the body’s execution. It is evaluated each time to determine if

the loop body should be executed. If its evaluation is True, the loop body is executed;

otherwise, the entire loop terminates and the program control turns to the statement that

follows the whileloop. The loop that displays Programming is fun!100 times is an

66
example of a whileloop. Its flowchart is shown in Figure b. The loop-continuation-

condition is count <100 and the loop body contains two statements:

FIGURE The while loop repeatedly executes the statements in the loop body as long as

the loop-continuation-condition evaluates to True.

67
Here is another example illustrating how a loop works:

68
6.2 The for Loop

A Python for loop iterates through each value in a sequence. Often you know exactly how
many times the loop body needs to be executed, so a control variable can be used to count
the executions. A loop of this type is called a counter-controlled loop. In general, the loop
can be written as follows:
i = initialValue # Initialize loop-control variable
while i < endValue:# Loop body
...
i += 1 # Adjust loop-control variable

A for loop can be used to simplify the preceding loop:

for i in range(initialValue, endValue):# Loop body

In general, the syntax of a for loop is:

for var in sequence:# Loop body

A sequence holds multiple items of data, stored one after the other. Later in the book,

we will introduce strings, lists, and tuples. They are sequence-type objects in Python. The

vari- able vartakes on each successive value in the sequence, and the statements in the body

of the loop are executed once for each value.

The function range(a, b)returns the sequence of integers a, a + 1, ..., b - 2, and b

For example,

69
6.3 Nested Loops
A loop can be nested inside another loop. Nested loops consist of an outer loop and one or

more inner loops. Each time the outer loop is repeated, the inner loops are reentered and

started anew. This example presents a program that uses nested for loops to display a

multiplication table.

70
The program displays a title (line 1) on the first line in the output. The first for loop

(lines 4–5) displays the numbers 1 through 9 on the second line. A line of dashes (-) is dis-

played on the third line (line 7).

The next loop (lines 10–15) is a nested for loop with the control variable i in the outer

loop and j in the inner loop. For each i, the product i * j is displayed on a line in the inner

loop, with j being 1, 2, 3, . . ., 9.

To align the numbers properly, the program formats i * j using format(i * j, "4d")

(line 14). Recall that "4d" specifies a decimal integer format with width 4.

Normally, the print function automatically jumps to the next line. Invoking print(item,

end = '') (lines 3, 5, 11, and 14) prints the item without advancing to the next line.

6.4 Keywords break and continue

71
The break and continue keywords provide additional controls to a loop. You can use the

keyword break in a loop to immediately terminate a loop. Listing presents a program to

demonstrate the effect of using break in a loop.

The program adds integers from 1 to 20 in this order to sum until sum is

greater than or equal to 100. Without lines 7–8, this program would

calculate the sum of the numbers from 1 to 20. But with lines 7–8, the loop

terminates when sumbecomes greater than or equal to 100. Without lines 7–

8, the output would be:

You can also use the continue keyword in a loop. When it is encountered, it ends

the cur- rent iteration and program control goes to the end of the loop body. In other

72
words, continuebreaks out of an iteration, while the break keyword breaks out of a

loop. The program shows the effect of using continuein a loop.

The program adds all the integers from 1 to 20 except 10 and 11 to sum. The continue

statement is executed when number becomes 10 or 11. The continue statement ends the

current iteration so that the rest of the statement in the loop body is not executed;

therefore, number is not added to sum when it is 10 or 11. Without lines 6 and 7, the

output would be as follows:

In this case, all the numbers are added to sum, even when number is 10 or 11. Therefore,

the result is 210.

73
You can always write a program without using break or continue in a loop. In general, it

is appropriate to use break and continue if their use simplifies coding and makes

programs easy to read.

Suppose you need to write a program to find the smallest factor other than 1 for an

integer n (assume n >= 2). You can write a simple and intuitive code using the

break statement as follows:

n = eval(input("Enter an integer >= 2: "))factor = 2


while factor <= n:
if n % factor == 0:break
factor += 1
print("The smallest factor other than 1 for", n, "is", factor)

You may rewrite the code without using break as follows:

n = eval(input("Enter an integer >= 2: "))found = False


factor = 2
while factor <= n and not found:
if n % factor == 0:found = True
else:
factor += 1
print("The smallest factor other than 1 for", n, "is", factor)

Obviously, the break statement makes the program simpler and easier to read in this

example. However, you should use break and continue with caution. Too many break

74
and continue statements will produce a loop with many exit points and make the pro-

gram difficult to read.

75
6.5 End of Chapter Questions

76
77
78
79
References
[Link]

[Link]
language/?ref=l

[Link]
sources/Python%[Link]

[Link]
science/[Link]

[Link]
[Link]

80

You might also like