簡體   English   中英

試圖創建一個隨機字母循環,但 python 錯誤

[英]Trying to create a loop of random letters, but python errors

    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

如果我在 function 之外聲明 url,我會得到另一個錯誤。 如果我嘗試 str(url) 我會得到另一個錯誤。 該腳本的基本思想是能夠在提示后輸入一個值,然后將代碼運行該次數,並返回一個最終字符串。 我希望這是有道理的。 我只是在學習 Python 並且在任何地方都找不到答案。

當你得到一個input時,它會作為一個字符串返回。 Python 文檔

如果存在提示參數,則將其寫入標准 output 而不帶尾隨換行符。 function 然后從輸入中讀取一行,將其轉換為字符串(去除尾隨換行符),然后返回。

使用int() function 將length_of_url轉換為 integer,然后運行 function:

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

length_of_url作為字符串輸入,但從未轉換為 int。 您應該將其轉換為 int:

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

如果我正確理解了您想要的內容,則您不需要所有代碼。 您所要做的就是以下代碼:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM