python - 尝试打印从 0 到 x 的范围,用单词替换偶数位,最后一位数字为 None

标签 python python-3.x

我是编程新手,正在学习 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/

相关文章:

python - 关于 Python fnmatch 模块的疑问?

python - 使用 py2 解释器时 PyCharm py3 语法问题

从列表创建独立列表的 Pythonic 方法?

python - 在 Python 中对整个应用程序进行回归测试

python - 为 Apache airflow 配置日志记录保留策略

python - Scikit - 如何定义绘制 roc 曲线的阈值

javascript - python对象和json对象有什么区别?

python - OpenCV 轮廓 - 需要超过 2 个值才能解包

python - TypeError : Can't instantiate abstract class <. ..> 使用抽象方法

python - 为什么将此函数应用于未作为参数调用的变量?