ValueError with randint - python

I'm having this really weird error and I have no idea what it is.
This is my code:
def wordChoice():
theme = themechoice
word = theme[randint(0, len(theme) - 1)]
This is the error:
Traceback (most recent call last):
File "C:\Users\Andrei\Documents\USB Backup\Python\Hangman.py", line 31, in wordChoice
word = theme[randint(0, len(theme) - 1)]
File "C:\Users\Andrei\AppData\Local\Programs\Python\Python35-32\lib\random.py", line 218, in randint
return self.randrange(a, b+1)
File "C:\Users\Andrei\AppData\Local\Programs\Python\Python35-32\lib\random.py", line 196, in randrange
raise ValueError("empty range for randrange() (%d,%d, %d)" % (istart, istop, width))
ValueError: empty range for randrange() (0,0, 0)
I've searched everywhere but I can't find anything. I'm also kind of a newb so sorry if it was something obvious.
EDIT:
Before i set theme to this:
def themeChoice():
n = 0
for i in themes:
n += 1
print(str(n) + " - " + i)
themechoice = themesToThemes[themes[int(input("Type the number corresponding to your chosen theme: ")) - 1]]
print (themechoice)

This error will occur when theme is empty.
>>> theme = []
>>> random.randint(0, len(theme)-1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Programming\Python 3.5\lib\random.py", line 218, in randint
return self.randrange(a, b+1)
File "C:\Programming\Python 3.5\lib\random.py", line 196, in randrange
raise ValueError("empty range for randrange() (%d,%d, %d)" % (istart, istop, width))
ValueError: empty range for randrange() (0,0, 0)
Make sure theme actually has elements in it before trying to randomly choose an element from it. Also, consider using random.choice instead of manually generating an index with randint.

Related

ValueError: empty range for randrange() (0, 0, 0)

I try to export random proxy from a webpage with this script:
def randProxy():
url = 'https://free-proxy-list.net/anonymous-proxy.html'
response = requests.get(url)
parser = fromstring(response.text)
proxies = []
for i in parser.xpath('//tbody/tr')[:20]:
if i.xpath('.//td[7][contains(text(),"yes")]'):
proxy = ":".join([i.xpath('.//td[1]/text()')[0], i.xpath('.//td[2]/text()')[0]])
try:
t = requests.get("https://www.google.com/", proxies={"http": proxy, "https": proxy}, timeout=5)
if t.status_code == requests.codes.ok:
proxies.append(proxy)
except:
pass
proxy = proxies[random.randint(0, len(proxies)-1)]
px={"http": proxy, "https": proxy}
randProxy()
but when i try i get this error
Traceback (most recent call last):
File "C:\Users\natan\OneDrive\Dokumen\Private-Folder\Project\WtD\main.py", line 51, in <module>
randProxy()
File "C:\Users\natan\OneDrive\Dokumen\Private-Folder\Project\WtD\main.py", line 33, in randProxy
proxy = proxies[random.randint(0, len(proxies)-1)]
File "C:\Users\natan\AppData\Local\Programs\Python\Python39\lib\random.py", line 339, in randint
return self.randrange(a, b+1)
File "C:\Users\natan\AppData\Local\Programs\Python\Python39\lib\random.py", line 317, in randrange
raise ValueError("empty range for randrange() (%d, %d, %d)" % (istart, istop, width))
ValueError: empty range for randrange() (0, 0, 0)
Are anyone know how to fix this? i only want to get some random proxy
That happens when the second argument is a negative. Look here.
import random
print(random.randint(0,-1))
output
Traceback (most recent call last):
File "<string>", line 2, in <module>
File "/usr/lib/python3.8/random.py", line 248, in randint
return self.randrange(a, b+1)
File "/usr/lib/python3.8/random.py", line 226, in randrange
raise ValueError("empty range for randrange() (%d, %d, %d)" % (istart, istop, width))
ValueError: empty range for randrange() (0, 0, 0)
So maybe find a fix for changing the last parameter to something positive.
I believe it's actually because the first number has to be smaller than the second number. I just ran a program and had the same issue with random.randint(-50, -100) then switched the numbers and it worked

Error when calling a Markov Chain

I'm working on a project that calls a Markov Chain module. I've scraped data and composed a basic text generating file, but keep getting an error that I don't understand. My code looks like:
from markov_python.cc_markov import MarkovChain
mc = MarkovChain()
mc.add_file('C:\EclipseWorkspaces\csse120\markov_chain\src\lyrics.txt')
mc.add_string('shape')
print mc.generate_text(10)
The error I get is:
Traceback (most recent call last):
File "C:\EclipseWorkspaces\csse120\markov_chain\src\run.py", line 14, in <module>
print mc.generate_text(10)
File "C:\EclipseWorkspaces\csse120\markov_chain\src\markov_python\cc_markov.py", line 61, in generate_text
idx = random.randint(0, len(self.lookup_dict)-1)
File "C:\Python27\lib\random.py", line 244, in randint
return self.randrange(a, b+1)
File "C:\Python27\lib\random.py", line 220, in randrange
raise ValueError, "empty range for randrange() (%d,%d, %d)" % (istart, istop, width)
ValueError: empty range for randrange() (0,0, 0)
And here is the code it is calling back to:
def generate_text(self, max_length=20):
context = deque()
output = []
if len(self.lookup_dict) > 0:
self.__seed_me(rand_seed=len(self.lookup_dict))
idx = random.randint(0, len(self.lookup_dict)-1)
chain_head = list(self.lookup_dict.keys()[idx])
context.extend(chain_head)
Not sure what to do. Please advise.

Python Tk IndexError:list index out of range

Ok, I'm using python and tk to write a program. I need it to open a file and read one line, print it, then read the next line and print it. I first use:
self.wordlist = tkFileDialog.askopenfile(mode='rb',title='Select a wordlist')
In another part of the code I have:
num = 1
while True:
line = self.wordlist.readlines()[num].strip()
print line
num = num + 1
When I run this it returns:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1532, in __call__
return self.func(*args)
File "C:\Users\Owner\Desktop\hashgui.py", line 109, in hashcrack_command
line = self.wordlist.readlines()[num].strip()
IndexError: list index out of range
It prints the first line but stops on the second? Why?
The count in Python starts at 0, so it should be num = 0. The first line is at file.readlines()[0].
However, this way looks better:
for line in self.wordlist:
print line

Python - randint() returns empty range, crashing error

I've been able to duplicate this error multiple times in my poker program and tried various unsuccessful solutions. Here's the latest:
Traceback (most recent call last):
File "C:\Users\Pangloss\Desktop\tgchanpoker\poker.py", line 1868, in <module>
if __name__ == '__main__': main()
File "C:\Users\Pangloss\Desktop\tgchanpoker\poker.py", line 1866, in main
mainGame = Game(opponent)
File "C:\Users\Pangloss\Desktop\tgchanpoker\poker.py", line 1443, in __init__
if randint(1,betCheck+(10-handValue[1]))<5 or gameStage == "bettingStay":
File "C:\Python27\lib\random.py", line 241, in randint
return self.randrange(a, b+1)
File "C:\Python27\lib\random.py", line 217, in randrange
raise ValueError, "empty range for randrange() (%d,%d, %d)" % (istart, istop, width)
ValueError: empty range for randrange() (1,-7, -8)
And here's the relevant code:
handValue = checkHand(opponent.cards.cards)
if gameStage == "betting" or gameStage == "final" or gameStage == "finalresponding":
betCheck = 18-handValue[1]-round(betAmount/(setMax/5))+opponent.brashness
elif gameStage == "extendedFinal":
betCheck = 16-handValue[1]-round(betAmount/(setMax/5))+opponent.brashness-(pot/100)
else:
betCheck = 16-handValue[1]-round(betAmount/(setMax/5))+opponent.brashness
foldCheck = 16-handValue[1]-round(betAmount/(setMax/3))+opponent.brashness+(pot/100)
if randint(1,betCheck+(10-handValue[1]))<5 or gameStage == "bettingStay":
this code
randint(1,betCheck+(10-handValue[1]))
is giving you this
randrange(1,-7,-8)
This means that betCheck+(10-handValue[1]) is giving you -8
That range will not give you any number at all, because betCheck+(10-handValue[1])) is a negative number and the range is invalid
You need to examine the code that sets betcheck and handvalue[1] to see why it is so negative
Check your value of betCheck+(10-handValue[1]). From the traceback, it is -8.

Randint error in Python?

I'm writing up the code for the RSA algorithm as a project. With those who are familiar woth this encryption system,the function below calculates the value of phi(n). However when I run this, it comes up this error:
Traceback (most recent call last):
File "C:\Python27\RSA.py", line 127, in <module>
phi_n()
File "C:\Python27\RSA.py", line 30, in phi_n
prime_f = prime_list[random.randint(0,length)]
File "C:\Python27\lib\random.py", line 241, in randint
return self.randrange(a, b+1)
File "C:\Python27\lib\random.py", line 217, in randrange
raise ValueError, "empty range for randrange() (%d,%d, %d)" % (istart, istop, width)
ValueError: empty range for randrange() (0,0, 0)
I don't fully understand why this error is coming up. Here is my code for the phi_n function:
def phi_n():
global prime_list
length = len(prime_list) - 1
prime_f = prime_list[random.randint(0,length)]
prime_s = prime_list[random.randint(0,length)]
global pq
n = prime_f * prime_s
global phi_n
phi_n = (prime_f -1) * (prime_s -1)
return phi_n
Comment will be appreciated.
Thanks
The problem is prime_list is empty and therefore length will equal -1 resulting in the call random.randint(0, -1) which is invalid for obvious reasons.

Categories