首页 > 解决方案 > Fizzbuzz Challenge in Twilio quest

问题描述

I recently downloaded Twilio quest and I love it! However, I'm stuck at one of the entry-level Python challenges. It should be fairly easy to solve, but somehow I can not seem to work out the error here. Can anyone look through my code and find the obvious mistake which I clearly cannot?

import sys

inputs = sys.argv
inputs.pop(0)



for i in inputs:
    print(i)
    n = int(i) 
    for x in range(1,n+1):
        if x % 3 == 0 and x % 5 == 0:
            print("fizzbuzz")
        elif x % 3 == 0:
            print("fizz")
        elif x % 5 == 0:
            print("buzz")
        else:
            print(x)

The challenge is to solve the fizzbuzz challenge, with multiple numbers as input. Error yields: "We passed your script a number that was divisible by both 3 and 5, and expected you to print fizzbuzz, but instead you printed -3000.

So the input was -3000, and should pass by my first test, as it is indeed divisible by both 3 and 5. I can not seem to work out why the input -3000 would jump to the "else"-part of my for-loop.

标签: pythonpython-3.xfor-looptwiliofizzbuzz

解决方案


If the input is just a number, there is no need of the for loop. The logic is correct. One fix can be:

import sys

inputs = int(sys.argv[-1])
x=inputs
if x % 3 == 0 and x % 5 == 0:
    print("fizzbuzz")
elif x % 3 == 0:
    print("fizz")
elif x % 5 == 0:
    print("buzz")
else:
    print(x)

for a list of int in input:

import sys

inputs = [int(x) for x in sys.argv[1:]]
for x in inputs:
    if x % 3 == 0 and x % 5 == 0:
        print("fizzbuzz")
    elif x % 3 == 0:
        print("fizz")
    elif x % 5 == 0:
        print("buzz")
    else:
        print(x)

推荐阅读