179k views
5 votes
Lab Goal : This lab was designed to demonstrate the similarities and differences in a for loop and a while loop.Lab Description : Write a for loop that accomplishes the same goal as a while loop and write a while loop that accomplishes the same goal as a for loop. Finally, write a loop your way: write either a for loop or a while loop that produces the appropriate output.Sample Output :***** While Loop String Cleaner ****I am Sam I am with the letter a removed by a while loop is I m Sm I m***** For Loop String Cleaner ****I am Sam I am with the letter a removed by a for loop is I m Sm I m***** For Loop Common Divisor ****The for loop determined the common divisors of 528 and 60 are12 6 4 3 2***** While Loop Common Divisor ****The while loop determined the common divisors of 528 and 60 are12 6 4 3 2***** My Total Loop My Way ****The total of even numbers from 1 to 1000 using a for loop is 250500The total of even numbers from 1 to 1000 using a while loop is 250500*Only one of the two output statements are required. For extra credit, do both

1 Answer

2 votes

Answer:

See Explanation

Step-by-step explanation:

Required:

Use for and while loop for the same program

(1) String Cleaner

#For Loop

name = "I am Sam"

result = ""

for i in range(0, len(name)):

if name[i]!= 'a':

result = result + name[i]

print(result)

#While Loop

name = "I am Sam"

result = ""

i = 0

while i < len(name):

if name[i]!= 'a':

result = result + name[i]

i+=1

print(result)

(2): Common Divisor

#For Loop

num1 = 528

num2 = 60

div = num2

if num1 > num2:

div = num1

for i in range(2,div):

if num1%i == 0 and num2%i==0:

print(i,end = " ")

print()

#While Loop

num1 = 528

num2 = 60

div = num2

if num1 > num2:

div = num1

i = 2

while i <div:

if num1%i == 0 and num2%i==0:

print(i,end = " ")

i+=1

The iterates statements show the difference in the usage of both loops.

For the for loop, the syntax is:

for [iterating-variable] in range(begin,end-1)

-------

---

--

For the while loop, the syntax is:

while(condition)

-------

---

--

User Youss
by
5.3k points