Reputation:
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.
Upvotes: 0
Views: 127
Reputation: 5
If I understand what you want correctly, you don't need all that code. All you have to do is this code:
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)
Upvotes: 0
Reputation: 6857
length_of_url
is being inputted as a string, but never converted to an int. You should convert it to an int:
length_of_url = int(input("How long would you like the URL? "))
Upvotes: 2
Reputation: 2517
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)
Upvotes: 3