***Welcome to ashrafedu.blogspot.com * * * This website is maintained by ASHRAF***

Tuesday, April 27, 2021

Break and continue

Break:



The break statement
terminates the loop containing it and control of the program flows to the
statement immediately after the body of the loop. If break statement is inside
a nested loop, break will terminate the innermost loop.












break
in for loop



for var in sequence:



#
code inside for loop



If
condition:



break
(if break condition satisfies it jumps to outside loop)



#
code inside for loop



# code outside for loop



break
in while loop



while test expression



#
code inside while loop



If
condition:



break
(if break condition satisfies it jumps to outside loop)



#
code inside while loop



# code outside while
loop



Example:



for num in [11, 9, 88,
10, 90, 3, 19]:



print(num)



if(num==88):



print("The number
88 is found")



print("Terminating
the loop")



break



Continue:



The continue statement
is used to skip the rest of the code inside a loop for the current iteration
only. Loop does not terminate but continues on with the next iteration.












continue in for loop:



for var
in sequence:



#
code inside for loop



If
condition:



continue
(if break condition satisfies it jumps to outside loop)



#
code inside for loop



# code outside for loop



continue
in while loop;



while test expression



#
code inside while loop



If
condition:



continue(if
break condition satisfies it jumps to outside loop)



#
code inside while loop



# code outside while
loop



Example:



# program to display
only odd numbers



for num in [20, 11, 9,
66, 4, 89, 44]:



# Skipping the
iteration when number is even



if num%2 == 0:



continue



#
This statement will be skipped for all even numbers



print(num)


Repetition Structures

A repetition structure causes a statement or set of statements to execute
repeatedly.
Repetition structure, which is more commonly known as a loop
is used to repeat a set of statements.



Two broad categories of
loops are: 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.



In Python the while
statement is used to write a condition-controlled loop, and the for statement is
used to write a count-controlled loop.



1. While loop:

  • Loops are either infinite or conditional. Python while loop keeps reiterating a
    block of code defined inside it until the desired condition is met.
  • The while loop contains a boolean expression and the code inside the loop is repeatedly
    executed as long as the boolean expression is true.
  • The statements that are executed inside while can be a single line of code or a
    block of multiple statements.



Syntax:



while(expression):



    Statement(s)












Example:



i=1



while i<=6:



print("TTWRDC")



i=i+1



2. For loop:



Python for loop is
used for repeated execution of a group of statements for the desired number of
times. It iterates over the items of lists, tuples, strings, the dictionaries
and other iterable objects.



Syntax:



for var in sequence:



Statement(s)











Example 1:



numbers = [1, 2, 4, 6,
11, 20]



seq=0



for val in numbers:



seq=val*val



print(seq)



Example 2: Iterating
over a Tuple:



tuple = (2,3,5,7)



print ('These are the
first four prime numbers ')



#Iterating over the tuple



for a in tuple:



print
(a)



Example 3: Iterating
over a dictionary:



#creating a dictionary



college =
{"MPCs":"block1","BZC":"block2","BCom":"block3"}



#Iterating over the
dictionary to print keys



print ('Keys are:')



for keys in college:



print
(keys)



#Iterating over the
dictionary to print values



print ('Values are:')



for blocks in college.values():



print(blocks)



Example 4: Iterating
over a String:



#declare a string to
iterate over



college = 'TTWRDC'



#Iterating over the
string



for name in college:



print
(name)




3. Nested For loop:



When one Loop defined
within another Loop is called Nested Loops.



Syntax:



for val in sequence:



for
val in sequence:



statements



statements



Example:



for i in range(1,6):



for
j in range(0,i):



print(i,
end=" ")


Decision Structures

A control structure is
a logical design that controls the order in which a set of statements execute.



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)



Although the sequence
structure is heavily used in programming, it cannot handle every type of task.



Control structure: one
that can execute a set of statements only under certain circumstances. This can
be accomplished with a decision structure. Decision structures are also
known as selection structures.



In a decision
structure’s simplest form, a specific action is performed only if a certain
condition exists. If the condition does not exist, the action is not performed.



1. If
Statement:



The if statement
contains a logical expression using which data is compared and a decision is
made based on the result of the comparison.



Syntax:



if expression:



statement(s)



If the boolean
expression evaluates to TRUE, then the block of statement(s) inside the if statement
is executed. If boolean expression evaluates to FALSE, then the first set of code
after the end of the if statement(s) is executed.


Example:



a = 3



if a > 2:



print(a,
"is greater")



print("done")




2. Alternative if
(If-Else):



An else statement can
be combined with an if statement. An else statement contains the block of code
(false block) that executes if the conditional expression in the if statement resolves
to 0 or a FALSE value.



The else statement is
an optional statement and there could be at most only one else Statement
following if.



Syntax of if - else :



if test expression:



Body of if 



else:



Body of else 









Example:



a=int(input('enter the
number'))



if a>5:



print("a
is greater")



else:



print("a
is smaller than the input given")



3. Chained Conditional:
(If-elif-else):



The elif statement
allows us to check multiple expressions for TRUE and execute a block of code as
soon as one of the conditions evaluates to TRUE. Similar to the else, the elif
statement is optional. However, unlike else, for which there can be at most one
statement, there can be an arbitrary number of elif statements following an if.



Syntax of if – elif -
else :



If test expression:



Body
of if 



elif test expression:



Body
of elif 



else:



Body
of else












Example:



a=int(input('enter the
number'))



b=int(input('enter the
number'))



c=int(input('enter the
number'))



if a>b:



print("a
is greater")



elif b>c:



print("b
is greater")



else:



print("c
is greater")

Performing Calculations

A programmer’s tools for
performing calculations are
math operators. Python has numerous operators that can be used to perform mathematical calculations.



A math expression performs
a calculation and gives a value. The following is an example of a simple math
expression:



12 + 2



The values on the right
and left of the operator are called operands.


Example:
(simple_math.py)



a=10;



b=20;



c=a+b



print(‘Total is:
“, c)




Floating-Point and
Integer Division



Python has two
different division operators. The / operator performs floating-point division,
and the // operator performs integer division.



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.



Example:



>>> 5 /
2   



2.5



>>> 5
// 2  



2



The // operator works
like this:



• When the result is
positive, it is truncated, which means that its fractional part is thrown
away.



• When the result is
negative, it is rounded away from zero to the nearest integer.



Example:



>>> −5 // 2



−3




Operator Precedence



First, operations that are enclosed in parentheses are performed first.
Then 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.



Example:



outcome = 12.0 + 6.0 /
3.0







There is an exception
to the left-to-right rule. When two ** operators share an operand, the
operators execute right-to-left. For example, the expression 2**3**4 is
evaluated as 2**(3**4).




Mixed-Type Expressions
and Data Type Conversion



When a math operation
is performed 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.)



The first two
situations are straightforward: operations on ints produce ints, and operations
on floats produce floats. The third situation, which involves 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
happens implicitly in above calucation.



For explicit
conversion, use either the int( ) or float( ) functions.


Reading Input from the Keyboard

Python’s built-in input
function is used 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.



General
format:



variable =
input(prompt)



In the general format, prompt
is a string that is displayed on the screen.



Example:



name = input('What is
your name? ')



When the above
statement executes, the following things happen:



• The string 'What is
your name? ' is displayed on the screen.



• The program pauses
and waits for the user to type something on the keyboard and then to press the
Enter key.



• When the Enter key is
pressed, the data that was typed is returned as a string and assigned to the
name variable.



Reading
numeric data using input function



The input function
always returns the user’s input as a string, even if the user enters numeric
data. 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.



Python has built-in
functions that you can use to convert a string to a numeric type.


Example:



string_value =
input('How many hours did you work? ')



hours =
int(string_value)



OR



hours = int(input('How
many hours did you work? '))



The int( ) and float( )
functions work only if the item that is being converted contains a valid
numeric value. If the argument cannot be converted to the specified data type,
an error known as an exception occurs.


Displaying Output with the print Function

The most fundamental
built-in function of Python 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:



>>>
print('Hello world')



Hello world



>>> 



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.



Using
Script:



Program
to display name and address on the computer screen



program name: output.py



print(“Ashraf”)



print(“TTWRDC,Maripeda”)


More
About Data Output

Output can be formatted
in different ways.

1. Suppressing the print
Function’s Ending Newline

The print function
normally displays a line of output.

Example:

print('One')

print('Two')

print('Three')

Each of the statements
shown here displays a string and then prints a newline character.

Output:

One

Two

Three

If the print function
should not start a new line of output when it finishes displaying its output, pass
the special argument end=' ' to the function.

print('One', end=' ')

print('Two', end=' ')

print('Three')

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

To print anything at
the end of its output, not even a space. If that is the case, pass the argument
end='' to the print function, as shown in the following code:

print('One', end='')

print('Two', end='')

print('Three')

This specifies that the
print function should print nothing at the end of its output. Here is the
output of these statements:

OneTwoThree

2. Specifying an Item
Separator

When multiple arguments
are passed to the print function, they are automatically separated by a space
when they are displayed on the screen.

>>>
print('One', 'Two', 'Three')

One Two Three

If space is not to be
printed between the items, pass the argument sep='' to the print function, as
shown here:

>>>
print('One', 'Two', 'Three', sep='')

OneTwoThree

To specify a character
other than the space to separate multiple items in the output use sep=’*’

>>>
print('One', 'Two', 'Three', sep='*')

One*Two*Three

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











































































Some of Python’s
escape characters


Examples:



Ex \n:



print('One\nTwo\nThree')



When this statement
executes, it displays



One



Two



Three



Ex \t:



print('Mon\tTues\tWed')



print('Thur\tFri\tSat')



The output is



Mon     Tues     Wed



Thur     Fri        Sat




Ex \' and \":

The \' and \"
escape characters can be used to display quotation marks.



print("Your
assignment is to read \"Hamlet\" by tomorrow.")



print('I\'m ready to
begin.')



These statements
display the following:



Your assignment is to
read "Hamlet" by tomorrow.



I'm ready to begin.




Ex \\:

The \\ escape character
is used to display a backslash, as shown in the following:



print('The path is
C:\\temp\\data.')



This statement will
display



The path is
C:\temp\data.




4. Displaying Multiple
Items with the + Operator



When the + operator is used
with two strings, it performs string concatenation.



print('This is ' + 'one
string.')



This statement will
print



This is one string.



5. Formatting Numbers



When a floating-point
number is displayed by the print function, it can appear with up to 12
significant digits.



Python provides the
built-in format function, which can be used to round the decimal places. The format
specifier
is a string that contains special characters specifying how the
numeric value should be formatted.



format function has two
arguments: a numeric value and a format specifier.



format(12345.6789, '.2f
')



The first argument,
which is the floating-point number 12345.6789, is the number that we want to
format. The second argument, which is the string '.2f', is the format
specifier.



Here is the meaning of
its contents:



• The .2 specifies the
precision. It indicates that we want to round the number to two decimal places.



• The f specifies that
the data type of the number we are formatting is a floating-point number.



output: 12345.68



Formatting in
Scientific Notation



To display
floating-point numbers in scientific notation, use the letter e or the letter E
instead of f.



>>>
print(format(12345.6789, 'e'))



1.234568e+04



>>> print(format(12345.6789,
'.2e'))



1.23e+04



Inserting Comma
Separators



If you want the number
to be formatted with comma separators, you can insert a comma into the format
specifier.



>>>
print(format(12345.6789, ',.2f'))



12,345.68



>>> print(format(123456789.456,
',.2f'))



123,456,789.46



Specifying a Minimum
Field Width



The format specifier
can also include a minimum field width, which is the minimum number of spaces
that should be used to display the value.



>>> print('The
number is', format(12345.6789, '12,.2f'))



The number is 12,345.68



The number 12,345.68
uses only 9 spaces on the screen, but it is displayed in a field that is 12
spaces wide. When this is the case, the number is right justified in the field.
If a value is too large to fit in the specified field width, the field is
automatically enlarged to accommodate it.