python - 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.
解决方案
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)
推荐阅读
- git - 如何防止源树中没有提交消息?
- ios - AppStore 图标变为全黑
- mongodb - MongoDB更新:-更新嵌套在数组中的多个对象(在多个文档中)
- database - 在数据库中查找所有用户定义的公共同义词
- java - 如何在使用 XSL-FO 生成另一个 PDF 文件时合并一个 PDF 文件?
- git - 在私有存储库中添加公共 github 存储库作为子模块将使子模块存储库成为私有
- javascript - “const”如何影响变量的类型?
- jquery - HTML 设计 - 用 div 替换表格
- django - 如何在 APIView 中设置密码 - Django
- python - 如何在文件路径中使用变量