1484238788 by Unknown

1484238788 by Unknown

Author:Unknown
Language: eng
Format: epub
Published: 2018-08-14T12:15:28+00:00


Chapter 6 Loops

ONE INFINITE LOOP

Did you know that when apple built its corporate headquarters, it paid homage to software developers? the current headquarters is a series of six buildings. When the buildings were built, an oval road was built to allow cars to navigate around the buildings. the official address of apple is one Infinite Loop Drive in Cupertino, California.

149

Chapter 6 Loops

First Loop in a Real Program

Let’s build a simple program using a loop. The program asks the user for a target number.

The goal of the program is to calculate the sum of the numbers from 1 through the target number. For example, if the user enters 4, then we want to calculate 1 + 2 + 3 + 4, and report the answer of 10:

#Add up numbers from 1 to a target number

target = input('Enter a target number: ')

target = int(target)

total = 0

nextNumberToAddIn = 1

while nextNumberToAddIn <= target:

# add in the next value

total = total + nextNumberToAddIn #add in the next number

print('Added in:', nextNumberToAddIn, 'Total so far is:', total)

nextNumberToAddIn = nextNumberToAddIn + 1

print('The sum of the numbers from 1 to', target, 'is:', total)

Notice the setup before the while loop starts. First, we get the target number from the user and convert it to an integer. We then set total to 0; this variable will eventually hold the total of all the numbers. We also set the nextNumberToAddIn variable to 1. This variable will be used to walk through the numbers from 1 to the target number that the user entered.

Next, we build our while statement. We will keep going through the loop until the nextNumberToAddIn is greater than the target number. When this happens, the value of the Boolean expression in the while statement becomes False and we exit the loop.

Every time through the loop, we add the value of nextNumberToAddIn to total. Then, just to see what’s going on, we add a print statement to print out the number that was just added in, and the total so far.

Finally, we add one to the nextNumberToAddIn to get to the next number. This

is the key to exiting the loop. Remember, we continue in the loop as long as the nextNumberToAddIn is less than or equal to the target number.

150



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.