1 / 11

Nested Loops

Nested Loops. CS303E: Elements of Computers and Programming. Nested Loops. Nested loops occur when a loop has one or more other loops in its body Outside loop variable is constant while the inside loop executes to completion

tameka
Télécharger la présentation

Nested Loops

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Nested Loops CS303E: Elements of Computers and Programming

  2. Nested Loops • Nested loops occur when a loop has one or more other loops in its body • Outside loop variable is constant while the inside loop executes to completion • The outside loop variable is incremented and inside loop begins again

  3. Example for i in range(5): for j in range(3): print “i=“+str(i)+ ” j=“+str(j) Output: i=0 j=0 i=0 j=1 i=0 j=2 i=1 j=0 i=1 j=1 i=1 j=2 i=2 j=0 i=2 j=1 i=2 j=2 i=3 j=0 i=3 j=1 i=3 j=2 i=4 j=0 i=4 j=1 i=4 j=2

  4. Example • Write a program that reads 10 strings from the user and prints the number of times the letter “a” appears in each string.

  5. Question: What is the value of sum after the following code is evaluated? sum=0 for i in range(3): for j in range(6): sum=sum+1 A. 3 C. 18 B. 9 D. 729

  6. Exercise Write a program that prints the following triangle, in which the first row contains 1 *, row 2 contains 2 *’s, … and row 10 contains 10 *’s * ** *** **** ***** ****** ******* ******** ********* **********

  7. Print: Eliminating Extra Space • print always adds a blank space at the end: • A space after a comma OR • A newline when there is no comma • To avoid this, use sys.stdout.write() • sys indicates the sys library • stdout indicates standard output or where the output usually goes---in this case, the interpreter

  8. sys.stdout.write():Example import sys sys.stdout.write(“hello”) sys.stdout.write(“world”) Output: helloworld

  9. Question for you: What does stdout represent? A. standard error B. standard output C. standard deviation

  10. Exercise Write a program that reads in a string from the user and then: • Capitalizes all the words • Uses a loop to print every other character in the string starting with the first character without spaces between the letters

  11. Reminders • No discussion section meetings this week. • Happy spring break! • Work on project – due the week after spring break.

More Related