#π Alternating for loop
22 messages Β· Page 1 of 1 (latest)
@thin laurel
Remember to:
- Ask your Python question, not if you can ask or if there's an expert who can help.
- Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
- Explain what you expect to happen and what actually happens.
:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.
for example i want it to print 2 4 6 8 10
Well the problem above is that i gets reset to the next number in the sequence on each loop iteration. So your +1 happens, your print happens, then the value of i becomes whatever is next from range.
ah, so i need to create a new variable then
Like, overtly:
for j in range(10):
i = j
i += 1
print(i)
You can make the range step by 2 instead of 1 (the default).
You can make the loop body conditional:
if i%2== 0:
print(i)
You can use another variable.
i will try my homework with the additional variable for now maybe it will work
You can do the counting yourself:
i=0
while i < 10:
i += 1
print(i)
i += 1 # this is like the next item from the for-loop
What strategy you usedepends a bit on the larger problem.
i think the best way would be to do the counting myself tbh
i didnt even think of that for some reason
thanks!
Don't forget that range() has an optional third step parameter. But yes, counting yourself gives complete control.
this is the final code, it works now with the manual counting:
def fizz_buzz(n: int) -> str:
"""
Gets `n` int and checks if it is divisble by 3, 5 or both and prints Fizz, Buzz or Fizz Buzz respectively
:param n: Int to be used to generate string
:return: Returns string `Fizz`, `Buzz`, or `Fizz Buzz` and if `n`is not divisible by 3 nor 5, it will output the `n` and a error
"""
if n % 3 == 0 and n % 5 == 0:
return "Fizz Buzz"
elif n % 3 == 0:
return "Fizz"
elif n % 5 == 0:
return "Buzz"
else:
return str(n)
turns = 0
i = 1
while not turns == 101:
print(i, "Comp A")
print("computer says ",fizz_buzz(i))
i += 1
print(i, "P A")
guess = input("Number, Fizz, Buzz or Fizz Buzz?: ")
if guess == fizz_buzz(i):
print("True")
i += 1
pass
else:
print("WRONG")
break
!solved
This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.