mardi 5 janvier 2021

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)

And this is the error I receive:

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

If I declare url outside of the function, I get a different error. If I try str(url) I get yet another error. The basic idea of this script is to be able to enter a value after being prompted, and then to run the code over that number of times, and return one final string. I hope this makes sense. I'm just learning Python and can't find the answer anywhere.




Aucun commentaire:

Enregistrer un commentaire