Sarvesh EB
Sarvesh EB

Reputation: 103

This simple piece of code gives an error when it gets looped for the second time

import random
import string



for x in range(0,15):
    print "something"
    string= str(random.choice(string.letters)+str(random.randint(100,10000))+random.choice(string.letters)+str(random.randint(0,100)))
    print  string

Why does this code throw an error when it runs for the second time inside the for loop? I have no idea how it works perfectly for the first time and throws this error:

something J6554r15 something

Traceback (most recent call last): File "C:\Users\test\Desktop\soooo.py", line 8, in string= str(random.choice(string.letters)+str(random.randint(100,10000))+ran dom.choice(string.letters)+str(random.randint(0,100))) AttributeError: 'str' object has no attribute 'letters'

What am I missing here?

Upvotes: 0

Views: 63

Answers (1)

nuric
nuric

Reputation: 11225

You are setting the variable string inside the loop which overwrites the import string library. Hence, on the second round you no longer have the string library to use string.letters but an actual string. Try using a different variable name.

Upvotes: 2

Related Questions