【问题标题】:Trying to create a loop of random letters, but python errors试图创建一个随机字母循环,但 python 错误
【发布时间】:2021-04-11 12:25:04
【问题描述】:
    import random

def number_to_letter():
    n = random.randint(1, 26)
    if n == 1:
        n = "A"
        return n
    elif n == 2:
        n = "B"
        return n
    elif n == 3:
        n = "C"
        return n
    else:
        n = "Out of Range."
        return n

def items_in_url(loops):
    url = ""
    i = loops
    while i <= loops:
        url += number_to_letter()
        i += 1
    return url

length_of_url = input("How long would you like the URL? ")
items_in_url(length_of_url)

这是我收到的错误:

How long would you like the URL? 3
Traceback (most recent call last):
  File "C:/Users/cmich/PycharmProjects/pythonProject/RandomNumber.py", line 28, in <module>
    items_in_url(length_of_url)
  File "C:/Users/cmich/PycharmProjects/pythonProject/RandomNumber.py", line 24, in items_in_url
    i += 1
TypeError: can only concatenate str (not "int") to str

Process finished with exit code 1

如果我在函数之外声明 url,我会得到一个不同的错误。如果我尝试 str(url) 我会得到另一个错误。该脚本的基本思想是能够在提示后输入一个值,然后将代码运行该次数,并返回一个最终字符串。我希望这是有道理的。我只是在学习Python,在任何地方都找不到答案。

【问题讨论】:

    标签: python string loops variables random


    【解决方案1】:

    如果我正确理解您想要的内容,您就不需要所有这些代码。你所要做的就是这段代码:

    import random
    while True:
      LETTERS = ("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z")
      g = random.choice(LETTERS)
      print(g)
    

    【讨论】:

      【解决方案2】:

      length_of_url 作为字符串输入,但从未转换为 int。您应该将其转换为 int:

      length_of_url = int(input("How long would you like the URL? "))
      

      【讨论】:

        【解决方案3】:

        当您获得input 时,它会以字符串形式返回。 Python docs:

        如果提示参数存在,则将其写入标准输出,不带尾随换行符。然后该函数从输入中读取一行,将其转换为字符串(去除尾随的换行符),然后返回。

        使用int()函数将length_of_url转换成整数,然后运行函数:

        ...
        length_of_url = int(input("How long would you like the URL? "))
        items_in_url(length_of_url)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-09-21
          • 2017-03-18
          • 2018-08-11
          • 1970-01-01
          • 2021-09-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多