【问题标题】:I get an error saying string return ' ' but I have a 0 there. Is it not going through the string?我收到一个错误,说 string return ' ' 但我有一个 0 那里。它不是通过字符串吗?
【发布时间】:2021-01-07 03:12:37
【问题描述】:

这是我的代码:

    import turtle
    def first_index(s):
      for i in range(len(s)):
        if not (s[i].isdigit()):
          return i 
       return None
    
    def go_to(s):
      if s[0] == 'G':
        comma_ind = first_index(s)
        first_arg = int(s[1:comma_ind])
        second_arg = int(s[comma_ind + 1:comma_ind + first_index(s[comma_ind + 1:])])
        turtle.goto(first_arg, second_arg)
    
    go_to('G10,10')
  

有谁知道为什么会出现这个错误?非常感谢您的帮助,谢谢!

【问题讨论】:

  • 看起来您的 return None 没有缩进到正确的深度。
  • 另外,如果你没有从函数返回任何东西,默认情况下它会返回 None。所以你可以删除return None 行。

标签: python string indexing numbers python-turtle


【解决方案1】:

两期:

  • 如果未找到非数字字符,first_index 应返回最后一个索引
  • 获取第二个参数时,您将部分字符串发送到索引函数,因此您需要添加您传递的字符串的起始索引

试试这个代码:

import turtle
#This gets the 
def first_index(s): 
    for i in range(1,len(s)): 
       if not (s[i].isdigit()): 
          return i 
    return len(s)-1  # reached end of string

def go_to(s):
  if s[0] == 'G':
    comma_ind = first_index(s)
    first_arg = int(s[1:comma_ind])
    second_arg = int(s[comma_ind + 1:comma_ind + first_index(s[comma_ind + 1:])+comma_ind])  # add comma index to returned index
    turtle.goto(first_arg, second_arg)

go_to('G99,99')

input()

输出

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-16
    • 1970-01-01
    • 2015-12-17
    相关资源
    最近更新 更多