[英]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 並且在任何地方都找不到答案。
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.