Session Twelve

Download Report

Transcript Session Twelve

Intro to Nested Looping
Intro to Computer Science
CS1510, Section 2
Dr. Sarah Diesburg
Questions
In General?
 PA02 that I just handed back?
 PA03 for next week?

Some Things From PA02

BMI

These were continuous regions.

Set up your code to handle all areas…
Some Things From PA02

BMI

While this is valid mathematically, it is bad form in
programming languages.

And it causes real problems when not set up properly.
Some Things From PA02

BMI

Recognize that these are four related categories. This
makes it much easier to use if/elif/else.
Some Things From PA02

BMI

Recognize that these are four related categories. This
makes it much easier to use if/elif/else.
Some Things From PA02

BMI

Recognize that these are four related categories. This
makes it much easier to use if/elif/else.
Some Things From PA02

Triangle

Watch for messages that can only be printed under
certain circumstances


4,3,5 is not in order
“If the triangle is legal it also checks to see if the triangle
is a right triangle.”
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 positive number”)

9
Nested Loops


We can also nest loops
Can be very powerful, but tricky!
10
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??
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
Finding Out if a Number is Prime


Is 41 a prime number?
Is 77 a prime number?
Finding Out if a Number is Prime


Is 413 a prime number?
Is 419 a prime number?
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
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.
So how would we change this…

To print information about all of the numbers
from 2 to 100?

Nested Looping