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.
No comments:
Post a Comment