Loop Mechanisms in Python

메카니즘 설명

x = int(raw_input('Enter an integer: ')) # asks me to enter a value 
                    # for x that I want to find the cube root of
for ans in range(0, abs(x)+1): # tests answers from x = 0 to x ...
                    # Certainly the cube root of x can't be 
                    # greater than x.
    if ans**3 == abs(x): # compares ans**3 with x
        break # if we have the answer, break out of the loop
if ans**3 != abs(x): # if we run past the end of the range, we end
                # up here, so x is not a perfect cube, and we're
                # done.
     print(str(x) + ' is not a perfect cube')
else: # If we don't run out of range, and we have the answer, we
# end up here.
     if x < 0: # If we began with a negative integer, we will have a 
            # negative root. Note that we used abs(x) in the
            # above code to account for this possibility.
         ans = - ans
     print('Cube root of ' + str(x) + ' is ' + str(ans))

심플예제_1

num = 10
while True:
    if num < 7:
        print 'Breaking out of loop'
        break
    print num
    num -= 1
print 'Outside of loop'


Result

10, ,9, 8, 7, "Breaking out of loop", "Outside of loop"


심플예제_2

num = 2
while num < 11:
    print num
    num += 2
print "Goodbye!"
num = 2
while num <= 10:
    print num
    num += 2
print "Goodbye!"
num = 0
while True:
    num += 2
    print num
    if num >= 10:
        print "Goodbye!" 
        break
num = 1
while num <= 10:
    if num % 2 == 0:
        print num
    num += 1
print "Goodbye!"


심플예제_3

print "Hello!"
num = 10
while num > 0:
    print num
    num -= 2
num = 11
print "Hello!"
while num > 1:
    num -= 1
    if num %2 == 0:
        print num


심플예제_4

total = 0

current = 1

while current <= end:

    total += current

    current += 1


print total

Posted by Parametric Culture