《笨办法学Python3》练习三十三:while循环

练习代码

i = 0
numbers = []

while i < 6:
    print(f"At the top i is {i}")
    numbers.append(i)

    i = i + 1
    print("Numbers now: ", numbers)
    print(f"At the bottom i is {i}")

print("The numbers: ")

for num in numbers:
    print(num)

Study Drills

  1. Convert this while-loop to a function that you can call, and replace 6 in the test (i < 6) with a variable.
i = 0
numbers = []

def loop_func(end, i, numbers):
    while i < end:
        print(f"At the top i is {i}")
        numbers.append(i)

        i += step
        print("Numbers now: ", numbers)
        print(f"At the bottom i is {i}")        

loop_func(6, i, numbers)

print("The numbers: ")

for num in numbers:
    print(num)
  1. Use this function to rewrite the script to try different numbers.

  2. Add another variable to the function arguments that you can pass in that lets you change the + 1 on line 8 so you can change how much it increments by

i = 0
numbers = []

def loop_func(end, step, i, numbers):
    while i < end:
        print(f"At the top i is {i}")
        numbers.append(i)

        i = i + 1
        print("Numbers now: ", numbers)
        print(f"At the bottom i is {i}")        

loop_func(6, 2, i, numbers)

print("The numbers: ")

for num in numbers:
    print(num)
  1. Rewrite the script again to use this function to see what effect that has.

  2. Write it to use for-loops and range. Do you need the incrementor in the middle anymore?
    What happens if you do not get rid of it?

设置一个结束值

i = 0
numbers = []
# 设置一个结束值
end = 6

for i in range(6):
  print(f"At the top i is {i}")
  numbers.append(i)
  print("Numbers now: ", numbers)
  print(f"At the bottom i is {i}")

print("The numbers: ")

for num in numbers:
  print(num)

你可能感兴趣的:(《笨办法学Python3》练习三十三:while循环)