Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

python - I am writing a program for a sample test at hackerRank but my loop is not working or i must say i am receiving only one output

Here is the code

def fizzBuzz(n):
    n = list(range(1,n+1))
    for numbers in n:
        m3 = numbers / 3
        m5 = numbers / 5
        if type(m3) == int and type(m5) == int:
            return "FizzBuzz"
        elif type(m3) == int and type(m5) == float:
            return "Fizz"
        elif type(m3) == float and type(m5) == int:
            return "Buzz"
        else:
            return numbers
challenge = fizzBuzz(5)
print(challenge)

I think the function should iterate over n times but I am getting only one output. Why is it so?

question from:https://stackoverflow.com/questions/65871473/i-am-writing-a-program-for-a-sample-test-at-hackerrank-but-my-loop-is-not-workin

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When you divide any integer number by the '/' operator you always have the type float, even when division is an int. Test for yourself: type(2/2) returns float. To check wheter N can be divided by M, it's usually better to test modulo N%M==0.

You can try this:

def fizz_buzz(n):
    for i in range(1, n + 1):
        if i % 3 == 0 and i % 5 == 0:
            print('FizzBuzz')
        elif i % 3 == 0:
            print('Fizz')
        elif i % 5 == 0:
            print('Buzz')
        else:
            print(i)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...