I'm creating a Fizzbuzz code but there is a problem with the code where the result is like this:
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
Here is my code:
word = [3,5]
ans = ["Fizz","Buzz"]
i = 1
j = 0
result = ""
while i <= 20:
while j <= len(word)-1:
if i % int(word[j]) == 0 : result += ans[j]
if result == "" : result = str(i)
j+=1
print(result)
i+=1
The code check on list of the numbers and output the the result or else it will output the number itself.
Well never mind, turns out i found out the answer myself:
word = [3,5]
ans = ["Fizz","Buzz"]
i = 1
while i <= 100:
result = ""
j = 0
while j < len(word):
if i % int(word[j]) == 0 : result += ans[j]
j+=1
if result == "" : result = str(i)
print(result)
i+=1
There is 3 errors that I've found Turns out that the j variable is counting continuously so and it couldn't reset so all I have to do is place the variable j in the first while loop.
while i <= 100:
j = 0
The second issue is similar to j variable so i've place in the first while loop also:
while i <= 100:
result = ""
j = 0
The third errors is within this code:
if result == "" : result = str(i)
so all i have to do i declare it outside the 2 loop and there we have the result right here:
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
So here is a lesson I've learn which is : variable acts on where you place it.
Happy coding guys and thank you for your wonderful help and ideas.