Hi People,
I’m having a little trouble figuring out a way to convert this while-loop to a function.
I know how to create functions, but not as far as converting a while-loop to one.
Here’s what I did:
def while_loop():
i = 0
numbers = []
while i < 6:
print(f"at the 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)
while_loop()
The easiest way to fix this is take out the “f” it is invalid syntax. The way you are using f doesn’t assign anything to it. so you initialise say f = 0 but it will just keep print ‘0’ because there is no information going into the variable to be printed. This is essential the best you can do with what I can see.
def while_loop():
i = 0
numbers = []
while i < 6:
print ("at the top i is {%d}") % i
numbers.append(i)
i = i + 1
print("Numbers now: ", numbers)
print ("At the bottom i is {%d}") %i
print("The numbers: ")
for num in numbers:
print(num)
while_loop()
That’s pretty close, but here’s a couple other ideas:
Take the body of the while-loop and put that in a function, then just call it from the while loop with everything it needs.
Change your while_loop() function to accept a value for 6 you have there, and then return numbers. That way you can make it do as many numbers as you want.
Okay, after a few weeks of playing around with this, I believe I finally found what I wanted to achieve. I was tempted to search more on-line for the answers, but everyone’s comments here encouraged me to try other things. Although, I don’t believe I’ve tried the return method yet, I’m very happy to have made it this far. This morning I was about to give-up and start fresh on the next lesson, but an epiphany just shot into my head.
First: I converted the while-loop to a function:
def guitar(i, a, b, numbers):
while i < a:
print(f"Top number: {i}.")
numbers.append(i)
i += b
print("Numbers: ", numbers)
print(f"Bottom number: {i}.")
print("Numbers in List:")
for num in numbers:
print(num)
guitar(0, 10, 2, [])
Second: After converting to a while loop, I found right away that the ex33.py study drills became crystal clear to me
def guitar2(i, a, b, numbers):
for i in range(i, a):
print(f"Top number: {i}.")
numbers.append(i)
print("Numbers: ", numbers)
print(f"Bottom number: {i}.")
print("Numbers in List:")
for num in numbers:
print(num)
guitar2(0, 10, 2, [])
It’s an f-string, which is the way I tell people they should be formatting their strings, not with .format(). I only teach .format() because people will run into it, and there’s one situation where you need it.
Sorry to dredge up something so old, but I am stuck on this one. I like your conversion of the while loop and I follow it until the last line. in guitar or guitar2 what does the 3rd number do? I have changed it to different values with no change in results. guitar2(0, 10, 2, [])