Download - Intro to Nested Looping Intro to Computer Science CS1510 Dr. Sarah Diesburg.

Transcript
Page 1: Intro to Nested Looping Intro to Computer Science CS1510 Dr. Sarah Diesburg.

Intro to Nested Looping

Intro to Computer Science

CS1510

Dr. Sarah Diesburg

Page 2: Intro to Nested Looping Intro to Computer Science CS1510 Dr. Sarah Diesburg.

Nesting

Nesting means to place one code structure inside of another

Nested if statements

If (a<1):

if (a==0):

print(“Hey, this is zero”)

else:

print(“This is a negative number”)

2

Page 3: Intro to Nested Looping Intro to Computer Science CS1510 Dr. Sarah Diesburg.

Nested Loops

We can also nest loops Can be very powerful, but tricky!

3

Page 4: Intro to Nested Looping Intro to Computer Science CS1510 Dr. Sarah Diesburg.

The idea of nested looping

for x in range(1,4):

for y in range(1,5):

print (x, '*' , y , '=' , (x*y))

How many times will this print??

Page 5: Intro to Nested Looping Intro to Computer Science CS1510 Dr. Sarah Diesburg.

Finding Out if a Number is Prime An integer, N, is prime if it is not evenly

divisible by any of the numbers from 2 to N-1

Page 6: Intro to Nested Looping Intro to Computer Science CS1510 Dr. Sarah Diesburg.

Finding Out if a Number is Prime Is 41 a prime number? Is 77 a prime number?

Page 7: Intro to Nested Looping Intro to Computer Science CS1510 Dr. Sarah Diesburg.

Finding Out if a Number is Prime Is 413 a prime number? Is 419 a prime number?

Page 8: Intro to Nested Looping Intro to Computer Science CS1510 Dr. Sarah Diesburg.

Let’s Write a Design Paragraph Inputs? Steps to calculate result Outputs?

8

Page 9: Intro to Nested Looping Intro to Computer Science CS1510 Dr. Sarah Diesburg.

Finding Out if a Number is Prime Write a program that:

Asks for an integer greater than 2 Keeps prompting until it gets one Checks the numbers from 2 to N-1 to see if N is

evenly divisible by that number Prints a message either way.

Page 10: Intro to Nested Looping Intro to Computer Science CS1510 Dr. Sarah Diesburg.

So how would we change this… To print information about all of the numbers

from 2 to 100? Nested Looping