In: Computer Science
PYTHON PROGRAM
QUESTION 1
Briefly describe how a while loop works
QUESTION 2
Compare and contrast a while statement and an if statement ?
QUESTION 3
What is a loop body?
QUESTION 4
What is the value of variable num after the following code segment?
num = 10;
while num > 0:
num = num -1;
QUESTION 5
What is the value of variable num after the following code segment is executed?
var num = 1
while num >10:
num = num -1
QUESTION 6
Why the loop does not terminate?
n = 10
answer = 1
while n > 0:
answer = answer + n
n = n + 1
print(answer)
QUESTION 7
Convert the following for loop to a while loop.
total = 0
for i in range(10):
total = total + i
print(total)
QUESTION 8
Write a while loop to display from 0 to 100, step up 5 each time.
0, 5, 10, 15, 20, ... , 100
Q1-
A while loop works as follows
there is a precondition which is checked before entering the loop,
if that is true, then the while loop body is executed, then counter
is increased for the variable the while loop is working, then again
the precondition is checked and loop exits when the condition gets
failed.
Q2- While statement is a loop which executed the body of while loop till the expression is true, whereas an if statement checks if an expression is true or false, and if it is true then it runs the code inside if block, and it is executed only once unlike while statement.
Q3-
A loop body is a group of statements which are executed on repeat
basis until the loop condition gets false.
Q4-
value of num after the code is executed is 0 because at the start
we have num=10 and then it enters while loop which decrements num
by 1 in every iteration untill num>0 so when num becomes 0 it
exits the loop so at the end of program num=0
Q5-value of num after code segment is executed is 1 as while condition is never true so while loop never executes.
Q6- Loop never terminates because the condition is n>0 which is always true because inside loop we are incrementing n by 1 in every iteration and at the start of loop n=10 so it will always be >0 which is why loop never terminates.
Q7-
for loop to while loop
total=0
i=0
while(i<10):
total=total+i
print total
Q8-
i=0
while(i<=100):
print i
i=i+5
this will print from 0 to 100 incrementing by 5 everytime.
if you like the answer please provide a thumbs up.