我是编程新手,正在学习 Python 在线学校类(class),作业是从 0 数到数字 (x),但跳过 0,数字之间没有空格或换行,但也将偶数替换为“番茄”这个词。
寻找类似于以下内容的答案:01tomato3tomato5tomato7tomato9tomato
指令说不要在函数体内使用 print 语句。不是打印,而是构建字符串然后返回它。我不知道没有他们如何做到这一点。
作业规定不要使用“高级”编码,而只使用我们学到的基础知识,我正在尝试使用此代码,但我不断收到最后一个数字的“无”一词,而不是数字或单词没有飞机。
代码:
def soup(x):
for i in range(x):
if i>0 and i%2==0:
print ('tomato',end='')
else:
print (i,end='')
我搜索了过去几个小时,似乎找不到基本的解决方案或好的答案。感谢您的帮助。
最佳答案
def foo(n):
# we are going build string instead of printing
# start with 0 as it will be our base case.
s = '0'
# loop to n
for i in range(n):
# skip 0
if i > 0:
# if even, add to s, tomato
if i % 2 == 0:
s += 'tomato'
else:
# else, add i, but cast it to string
s += str(i)
return s
print(foo(10))
def foo_cleanup(n):
# we are going build string instead of printing
# start with 0 as it will be our base case.
s = '0'
# loop to n, skipping 0 all together
# might look like a small clean up, but consider n > 1 billion
# that is 1 billion redundant checks
for i in range(1,n):
# if even, add to s, tomato
if i % 2 == 0:
s += 'tomato'
else:
# else, add i, but cast it to string
s += str(i)
return s
# list comprehension, not always best, but useful
def foo_advanced(n):
s = '0'+''.join(['tomato' if i % 2 ==0 else str(i) for i in range(1,n)])
return s
print(foo_advanced(10))
关于python - 尝试打印从 0 到 x 的范围,用单词替换偶数位,最后一位数字为 None,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41949741/