Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Unit 1 Notes Python

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

SEC-BSC III YEAR

[UNIT-I] Chapter-1:PYTHON INTRODUCTION


A program is a set of instructions that a computer follows to perform a task. Programs are commonly
referred to as software. Software is essential to a computer because it controls everything the computer does.
I.Hardware and Software:
Hardware: The physical devices that a computer is made of are referred to as the computer’s hardware.
The term hardware refers to all of the physical devices, or components, that a computer is made of. A typical
computer system consists of the following major components:
● The central processing unit (CPU)
● Main memory
● Secondary storage devices
● Input devices
● Output devices
Software: The programs that run on a computer are referred to as software.

The CPU
The central processing unit, or CPU, is the part of a computer that actually runs programs. The CPU is
the most important component in a computer because without it, the computer could not run software. CPUs are
small chips known as microprocessors

The Main Memory


memory is commonly known as random-access memory, or RAM. It is called this because the CPU is
able to quickly access data stored at any random location in RAM. This is where the computer stores a program
while the program is running, as well as the data that the program is working with

Secondary Storage Devices


storage is a type of memory that can hold data for long periods of time, even when there is no power to
the computer. Programs are normally stored in secondary memory and loaded into main memory as needed.
The most common type of secondary storage device is the disk drive. Optical devices such as the CD (compact
disc) and the DVD (digital versatile disc) are also popular for data storage.

Input Devices
Input is any data the computer collects from people and from other devices. The component that collects
the data and sends it to the computer is called an input device. Common input devices are the keyboard, mouse,
scanner, microphone, and digital camera.

Output Devices
Output is any data the computer produces for people or for other devices. It might be a sales report, a list
of names, or a graphic image. The data is sent to an output device, which formats and presents it. Common
output devices are video displays and printers.

Software:
The programs that run on a computer are referred to as software. There are two general categories of
software: system software and application software.

System Software:
The programs that control and manage the basic operations of a computer are generally referred to as
system software. System software typically includes the following types of programs:
i. Operating Systems: An operating system is the most fundamental set of programs on a computer. The
operating system controls the internal operations of the computer’s hardware, manages all of the devices
connected to the computer, allows data to be saved to and retrieved from storage devices, and allows other
programs to run on the computer.

ii. Utility Programs: A utility program performs a specialized task that enhances the computer’s operation or
safeguards data. Examples of utility programs are virus scanners, file compression programs, and data backup
programs.

iii. Software Development Tools: Software development tools are the programs that programmers use to create,
modify, and test software. Assemblers, compilers, and interpreters are examples of programs that fall into this
category.

Application software
Programs that make a computer useful for everyday tasks are known as application software. These are
the programs that people normally spend most of their time running on their computers.

II. HOW A PROGRAM WORKS:


CPU is the most important component in a computer because it is the part of the computer that runs
programs. In particular, the CPU is designed to perform operations such as the following:
● Reading a piece of data from main memory
● Adding two numbers
● Subtracting one number from another number
● Multiplying two numbers
● Dividing one number by another number
● Moving a piece of data from one memory location to another
● Determining whether one value is equal to another value

A program is nothing more than a list of instructions that cause the CPU to perform operations. CPUs
only understand instructions that are written in machine language, and machine language instructions always
have an underlying binary structure. A machine language instruction exists for each operation that a CPU is
capable of performing. The entire set of instructions that a CPU can execute is known as the CPU’s instruction
set. Program to contain thousands or even millions of machine language instructions.

Programs are usually stored on a secondary storage device such as a disk drive. It has to be copied into
main memory, or RAM, each time the CPU executes it.

When a CPU executes the instructions in a program, it is engaged in a process that is known as the
fetch-decode-execute cycle. This cycle, which consists of three steps, is repeated for each instruction in the
program. The steps are

1. Fetch A program is a long sequence of machine language instructions. The first step of the cycle is to fetch,
or read, the next instruction from memory into the CPU.

2. Decode A machine language instruction is a binary number that represents a command that tells the CPU to
perform an operation. In this step the CPU decodes the instruction that was just fetched from memory, to
determine which operation it should perform.

3. Execute The last step in the cycle is to execute, or perform, the operation.
From Machine Language to Assembly Language:
assembly language was created in the early days of computing as an alternative to machine language.
Instead of using binary numbers for instructions.
assembly language uses short words that are known as mnemonics. A special program known as an
assembler is used to translate an assembly language program to a machine language program.

High-Level Languages:
A high-level language allows you to create powerful and complex programs without knowing how the
CPU works and without writing large numbers of low-level instructions. In addition, most high-level languages
use words that are easy to understand. Eg: Ada,Java, C++ etc.

III. Key Words, operators, and syntax: An overview


Keywords: Keywords are reserved words. Each key word has a specific meaning, and cannot be used for any
other purpose.

Operators
Programming languages have operators that perform various operations on data. For example, all
programming languages have math operators that perform arithmetic.

Syntax:
In Python, as well as most other languages, the + sign is an operator that adds two numbers. The
following adds 12 and 75: 12 + 75
Each language also has its own syntax, which is a set of rules that must be strictly followed when writing
a program. The syntax rules dictate how keywords, operators, and various punctuation characters must be used
in a program. When you are learning a programming language, you must learn the syntax rules for that
particular language.
The individual instructions that you use to write a program in a high-level programming language are
called statements. A programming statement can consist of keywords, operators, punctuation, and other
allowable programming elements, arranged in proper sequence to perform an operation.
Compilers and Interpreters
Generally the CPU understands only machine language instructions, programs that are written in a high-
level language must be translated into machine language. Depending on the language that a program has been
written in, the programmer will use either a compiler or an interpreter to make the translation.

A compiler is a program that translates a high-level language program into a separate machine language
program. The machine language program can then be executed any time it is needed.

The Python language uses an interpreter, which is a program that both translates and executes the
instructions in a high-level language program. As the interpreter reads each individual instruction in the
program, it converts it to machine language instructions and then immediately executes them. This process
repeats for every instruction in the program.

A syntax error is a mistake such as a misspelled key word, a missing punctuation character, or the
incorrect use of an operator. When this happens the compiler or interpreter displays an error message indicating
that the program contains a syntax error.

USING PYTHON
The python Interpreter
Python is an interpreted language. When you install the Python language on your computer, one of the
items that is installed is the Python interpreter. The Python interpreter is a program that can read Python
programming statements and execute them.

You can use the interpreter in two modes: interactive mode and script mode.
In interactive mode, the interpreter waits for you to type Python statements on the keyboard.
Script mode, the interpreter reads the contents of a file that contains Python statements. Such a file is known as
a Python program or a Python script. The interpreter executes each statement in Python program as it reads it.

Interactive mode example:


>>> print ('Python programming is fun!')
After typing the statement, you press the Enter key, and the Python interpreter executes the statement, as shown
here:
>>> print ('Python programming is fun!')
Output: Python programming is fun!
>>>
Writing python programs and Running Them in script Mode
The statements that you enter in interactive mode are not saved as a program. They are simply executed
and their results displayed on the screen. If you want to save a set of Python statements as a program, you save
those statements in a file. Then, to execute the program, you use the Python interpreter in script mode.
For example, suppose you want to write a Python program that displays the following three lines of text:
Ramesh
Sirisha
How are you?
To write the program you would use a simple text editor like Notepad (which is installed on all Windows
computers) to create a file containing the following statements:
print('Ramesh')
print('sirisha')
print('hello how are you?')
When you save a Python program, you give it a name that ends with the .py extension, which identifies it as a
Python program.

The IDLE programming environment:


IDLE stands for Integrated DeveLopment Environment. IDLE also has a built-in text editor with
features specifically designed to help you write Python programs. In IDLE you can write programs, save them
to disk, and execute them.
The >>> prompt appears in the IDLE window, indicating that the interpreter is running in interactive mode.
You can type Python statements at this prompt and see them executed in the IDLE window.

Chapter-2:
I. INPUT, PROCESSING, AND OUTPUT
Computer programs typically perform the following three-step process:
1. Input is received.
2. Some process is performed on the input.
3. Output is produced.
Input is any data that the program receives while it is running. One common form of input is data that is typed
on the keyboard. Once input is received, some process, such as a mathematical calculation, is usually performed
on it. The results of the process are then sent out of the program as output.
Displaying Output with The Print Function:
We use the print function to display output in a Python program. A function is a piece of prewritten
code that performs an operation. Python has numerous built-in functions that perform various operations.
Perhaps the most fundamental built-in function is the print function, which displays output on the screen. Here
is an example of a statement that executes the print function:
print('Hello world')

In interactive mode, if you type this statement and press the Enter key, the message Hello world is displayed.
Here is an example:
>>> print('Hello world')
Hello world
>>>
When programmers execute a function, they say that they are calling the function. When you call the print
function, you type the word print, followed by a set of parentheses. Inside the parentheses, you type an
argument, which is the data that you want displayed on the screen.

Ex-1 Program: (prg1.py)


print('Kate Austen')
print(“123 Full Circle Drive”)
print('Asheville, NC 28899')
Program output
Kate Austen
123 Full Circle Drive
Asheville, NC 28899

Strings and String Literals:


In programming terms, a sequence of characters that is used as data is called a string. When a string
appears in the actual code of a program it is called a string literal. In Python code, string literals must be
enclosed in quote marks. In Python you can enclose string literals in a set of single-quote marks (') or a set of
double- quote marks ("). See ex-1 program

III. COMMENTS
Comments are part of the program, but the Python interpreter ignores them. Comments are short notes
placed in different parts of a program, explaining how those parts of the program work. Comments are intended
for any person reading a program's code, not the computer.

In Python you begin a comment with the # character. When the Python interpreter sees a # character, it
ignores everything from that character to the end of the line. Large and complex programs can be almost
impossible to read and understand if they are not properly commented.
Ex-2 Program: (comment.py)
Variables:
A variable is a name that represents a value stored in the computer’s memory. Programs use variables to
access and manipulate data that is stored in memory. A program that calculates the distance between two cities
might use the variable name distance to represent that value in memory. When a variable represents a value in
the computer’s memory, we say that the variable references the value.

Creating Variables with Assignment statements:


You use an assignment statement to create a variable and make it reference a piece of data. Here is an example
of an assignment statement:
age = 25
An assignment statement is written in the following general format:
variable = expression
The equal sign (=) is known as the assignment operator. In the general format, variable is the name of a
variable and expression is a value, or any piece of code that results in a value.

When you pass a variable as an argument to the print function, you do not enclose the variable name in quote
marks. To demonstrate why, look at the following interactive session:
>>> print('width')
width
>>> print(width)
10
As shown in the following interactive session, an error occurs if the item on the left side of the = operator is not
a variable:
>>> 25 = age
SyntaxError: can't assign to literal
>>>

Variable naming Rules:


Although you are allowed to make up your own names for variables, you must follow these rules:
• You cannot use one of Python’s keywords as a variable name.
• A variable name cannot contain spaces.
• The first character must be one of the letters a through z, A through Z, or an underscore character (_).
• After the first character you may use the letters a through z or A through Z, the digits 0 through 9,
or underscores.
• Uppercase and lowercase characters are distinct. This means the variable name ItemsOrdered is not the
same as itemsordered.
Table lists several sample variable names and indicates whether each is legal or illegal in Python.

Numeric Data Types and Literals


Python uses data types to categorize values in memory. When an integer is stored in memory, it is
classified as an int, and when a real number is stored in memory, it is classified as a float.
room = 503 integer data
dollars = 2.75 float data
A number that is written into a program’s code is called a numeric literal. When the Python interpreter
reads a numeric literal in a program’s code, it determines its data type according to the following rules:
• A numeric literal that is written as a whole number with no decimal point is considered an int.
Examples are 7, 124, and −9.
• A numeric literal that is written with a decimal point is considered a float.
Examples are 1.5, 3.14159, and 5.0.

Storing Strings with the str Data Type


In addition to the int and float data types, Python also has a data type named str, which is used for storing
strings in memory. The code in Program shows how strings can be assigned to variables.

Reading Input From The Keyboard:


Programs commonly need to read input typed by the user on the keyboard. We will use the Python
functions to do this.
Python has built-in input function to read input from the keyboard. The input function reads a piece of
data that has been entered at the keyboard and returns that piece of data, as a string, back to the program. You
normally use the input function in an assignment statement that follows this general format:
SYNTAX: variable = input(prompt)
prompt is a string that is displayed on the screen. The string’s purpose is to instruct the user to enter a
value; variable is the name of a variable that references the data that was entered on the keyboard. Here is an
example of a statement that uses the input function to read data from the keyboard:
name = input('What is your name? ')
To demonstrate, look at the following interactive session:
>>> name = input('What is your name? ')
What is your name? Holly (input given by the user)
>>> print(name)
Holly
>>>

Reading Numbers With The Input Function:


The input function always returns the user’s input as a string, even if the user enters numeric data. For
example, suppose you call the input function, type the number 72, and press the Enter key. The value that is
returned from the input function is the string '72'. This can be a problem if you want to use the value in a math
operation. Math operations can be performed only on numeric values, not strings.
Fortunately, Python has built-in functions that you can use to convert a string to a numeric type. Table
summarizes two of these functions.

Type conversions or Data Conversion Functions:

Performing Calculations:
Python has numerous operators that can be used to perform mathematical calculations. A programmer’s
tools for performing calculations are math operators. Table lists the math operators that are provided by the
Python language.
Table python operators

Floating-Point and integer Division


Python has two different division operators. The / operator performs floating-point division, and the //
operator performs integer division. Both operators divide one number by another. The difference between them
is that the / operator gives the result as a floating-point value, and the // operator gives the result as an integer.
Let’s use the interactive mode interpreter to demonstrate:
Example:
>>> 5 / 2
2.5
>>> 5 // 2
2
>>>
Operator Precedence:
First, operations that are enclosed in parentheses are performed first. Then, when two operators share an
operand, the operator with the higher precedence is applied first. The precedence of the math operators, from
highest to lowest, are:
1. Exponentiation: **
2. Multiplication, division, and remainder: * / // %
3. Addition and subtraction: + −

Notice that the multiplication (*), floating-point division (/), integer division
(//), and remainder (%) operators have the same precedence. The addition (+) and
subtraction (−) operators also have the same precedence. When two operators
with the same precedence share an operand, the operators execute from left to
right.

Table Some expressions

The exponent operator


Two asterisks written together (**) is the exponent operator, and its purpose it to raise a number to a power
Example:
>>> 4**2
16
>>> 5**3
125

The Remainder operator


In Python, the % symbol is the remainder operator. (This is also known as the modulus operator.) The
remainder operator performs division, but instead of returning the quotient, it returns the remainder.

Example Program:
# Get a number of seconds from the user.
total_seconds = float(input('Enter a number of seconds: '))
# Get the number of hours.
hours = total_seconds // 3600
# Get the number of remaining minutes.
minutes = (total_seconds // 60) % 60
# Get the number of remaining seconds.
seconds = total_seconds % 60
# Display the results.
print('Here is the time in hours, minutes, and seconds:')
print('Hours:', hours)
print('Minutes:', minutes)
print('Seconds:', seconds)

Program output (with input shown in bold)


Enter a number of seconds: 11730
Here is the time in hours, minutes, and seconds:
Hours: 3.0
Minutes: 15.0
Seconds: 30.0

Grouping with Parentheses


Parts of a mathematical expression may be grouped with parentheses to force some operations to be performed
before others. In the following statement, the variables a and b are added together, and their sum is divided by
4:
result = (a + b) / 4
Without the parentheses, however, b would be divided by 4 and the result added to a.

MIXED-TYPE EXPRESSIONS AND DATA TYPE CONVERSION


When you perform a math operation on two operands, the data type of the result will depend on the data type of
the operands. Python follows these rules when evaluating mathematical expressions:
• When an operation is performed on two int values, the result will be an int.
• When an operation is performed on two float values, the result will be a float.
• When an operation is performed on an int and a float, the int value will be temporarily converted to a
float and the result of the operation will be a float. (An expression that uses operands of different data
types is called a mixed-type expression.)

Mixed-type expressions:
my_number = 5 * 2.0
When this statement executes, the value 5 will be converted to a float (5.0) and then multiplied by 2.0.
The result, 10.0, will be assigned to my_number.
The int to float conversion that takes place in the previous statement happens implicitly. If you need to
explicitly perform a conversion, you can use either the int() or float() functions. For example, you can use the
int() function to convert a floating-point value to an integer, as shown in the following code:
fvalue = 2.6
ivalue = int(fvalue)
The first statement assigns the value 2.6 to the fvalue variable. The second statement passes fvalue as an
argument to the int() function. The int() function returns the value 2, which is assigned to the ivalue variable.

MORE ABOUT DATA OUTPUT


you will learn more details about the Python print function, and you’ll see techniques for formatting
output in specific ways Suppressing the print Function’s Ending Newline The print function normally displays a
line of output. For example, the following three statements will produce three lines of output:
print('One')
print('Two')
print('Three')

Each of the statements shown here displays a string and then prints a newline character. You do not see
the newline character, but when it is displayed, it causes the output to advance to the next line.

If you do not want the print function to start a new line of output when it finishes displaying its output,
you can pass the special argument end=' ' to the function, as shown in the following code:
print('One', end=' ')
print('Two', end=' ')
print('Three')

Notice that in the first two statements, the argument end=' ' is passed to the print function. This specifies
that the print function should print a space instead of a newline character at the end of its output. Here is the
output of these statements:
One Two Three

Specifying an Item Separator


You can also use this special argument to specify a character other than the space to separate multiple
items. Here is an example:
>>> print('One', 'Two', 'Three', sep='*')
One*Two*Three

Escape Characters
An escape character is a special character that is preceded with a backslash (\), appearing inside a string
literal. When a string literal that contains escape characters is printed, the escape characters are treated as
special commands that are embedded in the string.
For example, \n is the newline escape character. When the \n escape character is printed, it isn’t
displayed on the screen. Instead, it causes output to advance to the next line.

For example, look at the following statement: print('One\nTwo\nThree')


When this statement executes, it displays One
Two
Three
Python recognizes several escape characters.

Chapter-3: Decision Structures and Boolean Logic


A sequence structure is a set of statements that execute in the order that they appear. For example, the
following code is a sequence structure because the statements execute from top to bottom.
name = input('What is your name? ')
age = int(input('What is your age? '))
print('Here is the data you entered:')
print('Name:', name)
print('Age:', age)

A control structure is a logical design that controls the order in which a set of statements execute. The
following are the various control structures or decision structures
1. The if Statement
2. The if-else Statement
3. Comparing Strings
4. Nested Decision Structures and
5. the if-elif-else Statement
6. Logical Operators
7. Boolean Variables

The if Statement:
The if statement is used to create a decision structure, which allows a program to have more than one
path of execution. The if statement causes one or more statements to execute only when a Boolean expression is
true.
In Python we use the if statement to write a single alternative decision structure. Here is the general
format of the if statement:
If the condition is true, we follow one path, which leads to an action being performed. If the condition is
false, we follow another path, which skips the action.

if condition:
statement
statement
etc.
When the if statement executes, the condition is tested. If the condition is true, the statements that appear
in the block following the if clause are executed. If the condition is false, the statements in the block are
skipped.

Boolean Expressions and Relational Operators:


The if statement tests an expression to determine whether it is true or false. The expressions that are
tested by the if statement are called Boolean expressions, named in honor of the English mathematician George
Boole.
The Boolean expression that is tested by an if statement is formed with a relational operator. A
relational operator determines whether a specific relationship exists between two values.

For example, the greater than operator (>) determines whether one value is greater than another. The equal to
operator (==) determines whether two values are equal. Table 3-1 lists the relational operators that are available
in Python.

The >= and <= Operators


Two of the operators, >= and <=, test for more than one relationship. The >= operator determines whether the
operand on its left is greater than or equal to the operand on its right. The <= operator determines whether the
operand on its left is less than or equal to the operand on its right.
For example, look at the following interactive session:
The != Operator
The != operator is the not-equal-to operator. It determines whether the
operand on its left is not equal to the operand on its right, which is the
opposite of the == operator
The if-else Statement:
An if-else statement will execute one block of statements if its condition is true, or another block if its condition
is false. Here is the general format of the if-else statement:
if condition:
statement
statement
etc.
else:
statement
statement
etc

Comparing Strings:
Python allows you to compare strings. This allows you to create decision structures that test the value of a string.
For example, look at the following code:
name1 = 'Mary'
name2 = 'Mark'
if name1 == name2:
print('The names are the same.')
else:
print('The names are NOT the same.')
The == operator compares name1 and name2 to determine whether they are equal.

The if-elif-else Statement:


Python provides a special version of the decision structure known as the if-elif-else statement, which makes this
type of logic simpler to write. Here is the general format of the if-elif-else statement:
if condition_1:
statement
statement
etc.
elif condition_2:
statement
statement
etc.
else:
statement
statement
etc.
The above example of the if-elif-else statement

Logical Operators:
The logical and operator and the logical or operator allow you to connect multiple Boolean expressions to create
a compound expression. The logical not operator reverses the truth of a Boolean expression.
The and Operator
The and operator takes two Boolean expressions as operands and creates a compound Boolean
expression that is true only when both subexpressions are true.
The following is an example of an if statement that uses the and
operator:

if temperature < 20 and minutes > 12:


print('The temperature is in the danger zone.')

The or Operator
The or operator takes two Boolean expressions as operands
and creates a compound Boolean expression that is true when either
of the subexpressions is true. The following is an example of an if
statement that uses the or operator:
if temperature < 20 or temperature > 100:
print('The temperature is too extreme')

The not Operator


The not operator is a unary operator that takes a Boolean
expression as its operand and reverses its logical value. In other
words, if the expression is true, the not operator returns false, and if
the expression is false, the not operator returns true.
The following is an if statement using the not operator:
if not(temperature > 100):
print('This is below the maximum temperature.')
First, the expression (temperature > 100) is tested and a value
of either

Chapter-4: Repetition Structures


Introduction: a repetition structure causes a statement or set of statements to execute repeatedly.

Condition-Controlled and Count-Controlled Loops: two broad categories of loops: condition-controlled and
Count-controlled. A condition-controlled loop uses a true/false condition to control the number of times that it
repeats. A count-controlled loop repeats a specific number of times.
1.The while Loop: A Condition-Controlled Loop:
The condition is tested, and if it is true, the process repeats. If the condition is false, the program exits the
loop.Here is the general format of the while loop in Python:

while condition:
statement
statement
etc
2.The for Loop: A Count-Controlled Loop:
A count-controlled loop iterates a specific number of times. In Python you use the for statement to write a
count-controlled loop.
In Python, the for statement is designed to work with a sequence of data items. When the statement
executes, it iterates once for each item in the sequence. Here is the general format:

for variable in [value1, value2, etc.]:


statement
statement
etc.

Using the range Function with the for Loop:


Python provides a built-in function named range that simplifies the process of writing a count-controlled for
loop. The range function creates a type of object known as an iterable

Here is an example:
for num in range(1, 5):
print(num)

This code will display the following:


1
2
3
4
The range() function
We can generate a sequence of numbers using range() function. range(10) will generate numbers from 0
to 9 (10 numbers). We can also define the start, stop and step size as range(start,stop,step size). step size
defaults to 1 if not provided.
This function does not store all the values in memory, it would be inefficient. So it remembers the start,
stop, step size and generates the next number on the go. To force this function to output all the items, we can
use the function list().
The Augmented Assignment Operators:
Programs have assignment statements in which the variable that is on the left side of the = operator also
appears on the right side of the = operator.

Here is an example:
x=x+1
On the right side of the assignment operator, 1 is added to x. The result is then assigned to x, replacing the value
that x previously referenced.

Input Validation Loops:


An input validation loop is sometimes called an error trap or an error handler, Input validation is the
process of inspecting data that has been input to a program, to make sure it is valid before it is used in a
computation. Input validation is commonly done with a loop that iterates as long as an input variable references
bad data.
1 # This program displays gross pay.
2 # Get the number of hours worked.
3 hours = int(input('Enter the hours worked this week: '))
4 # Get the hourly pay rate.
5 pay_rate = float(input('Enter the hourly pay rate: '))
6 # Calculate the gross pay.
7 gross_pay = hours * pay_rate
8 # Display the gross pay.
9 print('Gross pay: $', format(gross_pay, ',.2f'))
Program Output (with input shown in bold)
Enter the hours worked this week: 400
Enter the hourly pay rate: 20
The gross pay is $8,000.00

When input is given to a program, it should be inspected before it is processed. If the input is invalid, the
program should discard it and prompt the user to enter the correct data. This process is known as input
validation

Figure 4-7 shows a common technique for validating an item of input. In this technique, the input is
read, and then a loop is executed. If the input data is bad, the loop executes its block of statements. The loop
displays an error message so the user will know that the input was invalid, and then it reads the new input. The
loop repeats as long as the input is bad.

Nested Loops:
A loop that is inside another loop is called a nested loop. A nested loop is a loop that is inside another
loop. A clock is a good example of something that works like a nested loop.
Syntax
for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)
Example:
for x in range(1,5):
for y in range(1,10):
print (x,"*",y,"=",(x*y))
Output :
1*1=1
1*2=2
1*3=3
1*4=4
1*5=5
1*6=6
1*7=7
1*8=8
1 * 9 = 9 so on

Boolean Variables:
A Boolean variable can reference one of two values: True or False. Boolean variables are commonly
used as flags, which indicate whether specific conditions exist.
Python also provides a bool data type. The bool data type allows you to create variables that may
reference one of two possible values: True or False. Here are examples of how we assign values to a Boolean
variable:
Ex:
x=10
Print(x==10)
o/p:
true

Calculating a Running Total


A running total is a sum of numbers that accumulates with each iteration of a loop. The variable used to
keep the running total is called an accumulator.
Programs that calculate the total of a series of numbers typically use two elements:
• A loop that reads each number in the series.
• A variable that accumulates the total of the numbers as they are read.
The variable that is used to accumulate the total of the numbers is called an accumulator

====xxx====
(Choice –Easy notes)
Repetition Structures: (LOOPING STATEMENTS IN PYTHON)
A loop statement allows us to execute a statement or group of statements multiple times. The following
diagram illustrates a loop statement –
Python programming language provides following types of loops to handle looping requirements.

Sr.No. Loop Type & Description

1 while loop:Repeats a statement or group of statements while a given condition is TRUE. It tests the condition
before executing the loop body.
2 for loop:Executes a sequence of statements multiple times and abbreviates the code that manages the loop
variable.

3 nested loops: You can use one or more loop inside any another while, for loop.

1. while loop statement:


A while loop statement in Python programming language repeatedly executes a target statement as long
as a given condition is true.
The syntax of a while loop in Python programming language is −
while expression:
statement(s)

Here, statement(s) may be a single statement or a block of statements. The condition may be any
expression, and true is any non-zero value. The loop iterates while the condition is true. When the condition
becomes false, program control passes to the line immediately following the loop.

In Python, all the statements indented by the same number of character spaces after a programming
construct are considered to be part of a single block of code. Python uses indentation as its method of grouping
statements.

Flow Diagram
Here, key point of the while loop is that the loop might not ever run. When the condition is tested and
the result is false, the loop body will be skipped and the first statement after the while loop will be executed.

Example
count = 0
while (count < 9):
print (“The count is:”, count)
count = count + 1
print "Good bye!"
When the above code is executed, it produces the
following result −

The count is: 0


The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!

The block here, consisting of the print and increment statements, is executed repeatedly until count is no longer
less than 9. With each iteration, the current value of the index count is displayed and then increased by 1.
2. The For loop :
A count-controlled loop iterates a specific number of times. In Python you use the for statement to write a count-
controlled loop.
In Python, the for statement is designed to work with a sequence of data items. When the statement
executes, it iterates once for each item in the sequence. Here is the general format:

for variable in [value1,value2,etc.]: statement

The for statement executes in the following manner: The variable is assigned the first value in the list,
and then the statements that appear in the block are executed. Then, variable is assigned the next value in the
list, and the statements in the block are executed again. This continues until variable has been assigned the last
value in the list.

Using the range Function with the for Loop


The range() generates an iterator to progress integers starting with 0 upto n-1. To obtain a list object of
the sequence, it is typecasted to list(). Now this list can be iterated using the for statement.

Syntax: range([start], stop[, step])


● start: Starting number of the sequence.
● stop: Generate numbers up to, but not including this number.
● step: Difference between each number in the sequence.

Example:
>>> for var in list(range(5)):
print (var)
Output:This will produce the following output.
0
1
2
3
4
Example:
Number of integers (whole numbers) to generate, starting from zero.
Example: range(3) == [0, 1, 2].

Nested Loops:
A loop that is inside another loop is called a nested loop. A nested loop is a loop that is inside another
loop. A clock is a good example of something that works like a nested loop.
Syntax:
for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)

Example:
for x in range(1,5):
for y in range(1,10):
print (x,”*”,y,”=”,(x*y))
Output :
1*1=1
1*2=2
1*3=3
1*4=4
1*5=5
1*6=6
1*7=7
1*8=8
1*9=9
so on
==*****==

You might also like