Python Programming

Python Programming

While Lab

1 Purpose

This lab explores the use of while loops.

2 To Be Submitted

Each part requires you to write a separate program. You will not be submitting the complete programs. Instead, you will submit a single answer file that contains the loop code from each section (note that section 3.1 is not submitted). Label each answer with the name of the section; for example 3.2 3.3 etc.

Your solutions should be named with your last name, first initial, -lab5, as in doej-lab5. Your file should be .txt, .doc, or .pdf (not .py, since it isn't a program).

3 Simple Loops

3.1 An initial while loop

Create the following program. This will be referred to as the original program. x = eval(input("Enter an integer between 1 and 10: ")) if (x < 1) or (x > 10):

x=5 i=0 while i < x:

print("*") i=i+1 Run the program a few times. Each time you run the program, use a different value. Make sure you understand what each line of code is doing.

1

3.2 A Simple Modification

Change the print statement so that instead of printing one asterisk per line, it prints each asterisk on the same line. That is, instead of printing * * * * when a 4 is input, the program should display **** Note that the print will only print a single asterisk each time through the loop. Do NOT use the duplication operator! Copy your loop into your answer file.

3.3 Counting Backwards

Change the loop control in the original file (section 3.1) so that instead of counting from zero to x, it counts backwards from x to zero. Copy your loop into your answer file.

3.4 Indenting

Change the original file so that instead of printing one asterisk per line where the asterisks are in a column, it prints each asterisk indented by a number of spaces equal to the row it is in (where the value of i is the number of the row). This means that the first asterisk is not indented; the second has one space in front; the third two spaces in front; etc. Like so: *

* * * ...

To do this, control the number of spaces being printed with variable i in the print statement. Copy your loop into your answer file.

2

4 Nested Loops

4.1 Correcting Poorly Designed Nested Loops

The following code is supposed to print out powers of numbers.

x = eval(input('Enter a number greater than 1: '))

e = eval(input('Enter an exponent greater than 1: '))

i=2

#initialize outer loop

j=1

#initialize inner loop

power = 1

#initialize inner process

while i ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download