Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
348 views
in Technique[技术] by (71.8m points)

string - 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When you get an input, it is returned as a string. Python docs:

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.

Use the int() function to convert length_of_url into an integer, and then run the function:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...