if expression:
statement(s)
a = 3 if a > 2: print(a, "is greater") print("done") a = -1 if a < 0: print(a, "a is smaller") print("Finish")
if test expression: Body of if stmts else: Body of else stmts
bp=int(input("Enter basic pay: ")); if bp >= 15000: np=bp+bp*.85; print("Net Pay= ",np); else: np=bp+bp*.5; print("Net Pay= ",np);
If test expression: Body of if stmts elif test expression: Body of elif stmts else: Body of else stmts
n=int(input(“Enter any number:”)) if n<10: print(n,” is single digited”) elif n>9 and n<100: print(n,” is double digited”) elif n>99 and n<1000: print(n,” is triple digited”) else: print(n,” is multiple digited”)
a = float (input("Enter First Value: ")) b = float (input("Enter Second Value: ")) operator = input ("Enter Operator: ") if operator == '+': print ("Result= ", a+b) elif operator == '-': print ("Result= ", a-b) elif operator == '*': print ("Result= ", a*b) elif operator == '/': print ("Result= ", a/b) else: print ("Operator Doesn't Macth the Criteria ")
while(expression):
Statement(s)
n = 50 while(n >=2 ): print(n) n =n-2
n=int(input("Enter a number")); c=0; while(n!=0): n=int(n/10); c=c+1; print("No. of Digits=",c);
n=int(input("Enter decimal number")); p=int(0); r=int(0); x=n; while n!=0: b=int(n/2); d=n-b*2; r=r+d*pow(10,p); p=p+1; n=b; print("Binary of",x," is ",r);
Step-by-Step Explanation of above code:
Step
1: n = int(input("Enter decimal
number"))
input("Enter decimal number")
: This statement asking the user to enter a decimal number. Theinput()
function waits for the user to enter a value.int()
: Converts the input (which is a string) into an integer. So, whatever decimal number the user enters is converted into an integer and assigned to the variablen
.
Step
2: p = int(0)
p
is initialized to 0. It will be used as a position counter (starting from the rightmost bit) while constructing the binary number.
Step
3: r = int(0)
r
is initialized to 0. This variable will hold the binary result. Initially, it is set to zero.
Step
4: x = n
x
is a copy ofn
, used to preserve the original decimal number. This will be used in the final print statement to show the original input.
Step
5: while n != 0:
- This
starts a
while
loop that runs as long asn
is not equal to 0. - The
idea is to repeatedly divide the decimal number
n
by 2 to get the binary digits.
Step
6: b = int(n / 2)
b = int(n / 2)
: This line dividesn
by 2 (using integer division). It computes the quotient of the division, which represents the remaining number to process in the next iteration. This quotient is stored inb
.
Step
7: d = n - b * 2
d = n - b * 2
: This line calculates the remainder of the division, which is either 0 or 1. It's essentially the least significant bit (rightmost bit) of the binary number.- If
n
is even,d
will be 0 (becausen
divided by 2 leaves no remainder). - If
n
is odd,d
will be 1 (becausen
divided by 2 leaves a remainder of 1).
Step
8: r = r + d * pow(10, p)
pow(10, p)
: This line raises 10 to the power ofp
. It is used here to place the bitd
in the correct position in the binary number. For example, ifp = 0
, it addsd * 1
tor
; ifp = 1
, it addsd * 10
(moving the bit one place to the left), and so on.r = r + d * pow(10, p)
: This adds the bitd
to the current value ofr
, shifting it appropriately by using powers of 10.
Step
9: p = p + 1
- This
line increments
p
by 1, so the next bit will be placed in the next higher position in the binary number (next left bit).
Step
10: n = b
n = b
: This line setsn
to the quotientb
from the division. The next iteration will now work with the smaller valueb
, repeating the process untiln
becomes 0.
Step
11: print("Binary
of", x, "is", r)
- After
the
while
loop finishes (i.e., whenn
becomes 0), the program prints the binary equivalent of the decimal numberx
. The variabler
contains the binary representation, and it's printed out as the result.
Example Walkthrough:
Let's say the user inputs n
= 10
(decimal number).
1.
First Iteration
(n = 10
):
b = int(10 / 2) = 5
(quotient)d = 10 - 5 * 2 = 0
(remainder)r = 0 + 0 * pow(10, 0) = 0
p = 1
(incremented)n = 5
(updated to quotient)
2.
Second Iteration
(n = 5
):
b = int(5 / 2) = 2
(quotient)d = 5 - 2 * 2 = 1
(remainder)r = 0 + 1 * pow(10, 1) = 10
p = 2
(incremented)n = 2
(updated to quotient)
3.
Third Iteration
(n = 2
):
b = int(2 / 2) = 1
(quotient)d = 2 - 1 * 2 = 0
(remainder)r = 10 + 0 * pow(10, 2) = 10
p = 3
(incremented)n = 1
(updated to quotient)
4.
Fourth Iteration
(n = 1
):
b = int(1 / 2) = 0
(quotient)d = 1 - 0 * 2 = 1
(remainder)r = 10 + 1 * pow(10, 3) = 1010
p = 4
(incremented)n = 0
(updated to quotient, loop ends)
After the loop, the program prints:
Binary
of
10
is
1010
Conclusion:
This program converts a decimal number to binary by repeatedly dividing the
number by 2, storing the remainders (binary digits), and building the result.for value in sequence: {loop body}
n = 4 for i in range(0, n): print(i)
For i in range(10,0,-1): Print(i)
For i in range(20,1,-2): Print(i)
Step-by-Step Explanation:
Step
1: for i in range(20, 1, -2):
for i in ...
: This line begins afor
loop, which will iterate over a sequence of values. The variablei
will take on the value of each item in the sequence, one by one, for each iteration.range(20, 1, -2)
: This line generates a sequence of numbers using therange()
function. It takes three arguments:- The
first argument (20) is the
starting value of the sequence. The loop will start with this value.
- The
second argument (1) is the
stopping condition. The loop will stop when the value reaches 1 (but it
will not include 1).
- The
third argument (-2) is the
step value, which indicates how much to decrease the value after each
iteration. In this case,
-2
means that the value will decrease by 2 in each iteration (i.e., count backward by 2).
So,
range(20, 1, -2)
generates the sequence:
20, 18, 16, 14, 12, 10, 8, 6, 4, 2
. The loop will run for
each value in this sequence.
Step
2: print(i)
- This
line is the body of the
for
loop. For each value ofi
, it prints the value ofi
to the screen. - For
example, in the first iteration,
i
will be 20, soprint(i)
will display20
. In the next iteration,i
will be 18, and so on.
Summary:
- The
loop starts at 20 and counts down by 2 (i.e., 20, 18, 16, ...), stopping
just before it reaches 1.
- The
print(i)
statement prints each value as the loop runs through the sequence generated byrange(20, 1, -2)
.
for outer_variable in range(start, stop): # Outer loop body for inner_variable in range(start, stop): # Inner loop body
· The outer
loop runs first and controls how many times the inner loop will execute.
· The inner
loop will execute completely for every iteration of the outer loop.
Summary:
- A nested loop is when you have one loop
inside another loop.
- The inner loop runs completely for every single
iteration of the outer loop.
- They are useful for iterating over
multi-dimensional data or performing tasks that require multiple
iterations.
for
loopfor i in range(0, 6): for j in range(0, i+1): print("*", end=" ") print()
Step-by-Step Explanation:
Step 1: for
i in range(0, 6):
range(0, 6)
: Therange()
function generates a sequence of numbers from 0 to 5 (inclusive of 0, exclusive of 6). This means the outer loop (i
) will iterate 6 times, withi
taking the values 0, 1, 2, 3, 4, and 5 in each iteration.- Outer loop: The variable
i
will represent the current row number in the pattern.
Step 2: for
j in range(0, i+1):
- Inner loop: For each iteration of the outer loop, we have an inner loop.
range(0, i+1)
: This creates a sequence of numbers from 0 toi
, inclusive. Thei+1
ensures that the inner loop runs for exactlyi + 1
iterations. This means the number of stars printed in each row depends on the value ofi
.- When
i = 0
, the inner loop will run0 + 1 = 1
time. - When
i = 1
, the inner loop will run1 + 1 = 2
times, and so on.
Step 3: print("*",
end=" ")
print("*", end=" ")
: This prints a star (*
) followed by a space.end=" "
: By default, theprint()
function ends with a newline (\n
). Here,end=" "
changes the behavior, so it adds a space (" "
) after each star instead of moving to the next line. This ensures that the stars in each row are printed on the same line, separated by a space.
Step 4: print()
print()
: After the inner loop finishes running, thisprint()
function is called without any arguments. This prints a newline character (\n
), causing the next set of stars to appear on a new line. This happens after the stars for each row are printed.
Summary:
- The outer loop (for i in range(0, 6)) controls how many rows of
stars will be printed.
- The inner loop (for j in range(0, i+1)) controls how many stars will
be printed in each row.
- The print("*", end=" ") statement prints a star
followed by a space, keeping the stars on the same line.
- After each row is printed, the print() statement adds a new line to
separate the rows.
This code will print a right-angled triangle pattern of stars, where the number of stars increases by 1 with each row.
Nested while
loop
Preview:
i = 1 while i <= 6: # Outer while loop j = 1 while j <= i: # Inner while loop print("*",end = " ") j += 1 print() i += 1
# Example 1 of Nested For Loops (Pattern Programs)
for i in range(1,6): for j in range(0,i): print(i, end=" ") print('')
Output:
2 2
Break and continue:
Break:
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
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
Output:
11
The following shows the working of break statement in for and while loop:
while test expression # code inside while loop If condition: continue (if continue condition satisfies it jumps to outside loop) # code inside while loop # code outside while loop
0 Comments