We used lists for our Python class to correspond to Java arrays. Python does have arrays but lists are actually closer to Java arrays. Our examples show both single dimensional and two dimensional arrays and lists. We processed the arrays using for loops to compute sums. Again, note that the Python syntax iterates over a range. Click on the image below to see an expanded image on box.com.
Showing posts with label loops. Show all posts
Showing posts with label loops. Show all posts
Tuesday, April 4, 2017
Sunday, April 2, 2017
Loops in Java and Python
Below are the basic looping statements in Java and Python. Java has three: while, do...while and for, Python has two: while and for. But not do...while, although there are ways to accomplish the same thing. Also Python has an interesting approach to the for statement, sometimes called a for each. It iterates over a sequence selecting each element in turn. In the example below if counter is 15 it will iterate over i from 1 through 15.
for i in range(1,counter+1):
sum = sum + i;
On another note I decided I would I put the code for the Python scripts in a function and then called the function. This is more similar to Java which requires the existence of a class with a main() method. See the example below. It basically checks to see if the script being run is the main program, not an import.
def Loops():
counter = 10
i = 1
while i <= counter:
print("i = {}".format(i))
i = i + 1
if __name__ == "__main__":
Loops()
Click on the image below to see the code for the various loops.
for i in range(1,counter+1):
sum = sum + i;
On another note I decided I would I put the code for the Python scripts in a function and then called the function. This is more similar to Java which requires the existence of a class with a main() method. See the example below. It basically checks to see if the script being run is the main program, not an import.
def Loops():
counter = 10
i = 1
while i <= counter:
print("i = {}".format(i))
i = i + 1
if __name__ == "__main__":
Loops()
Click on the image below to see the code for the various loops.
Subscribe to:
Posts (Atom)

