Python 3.8: strange behavior of try code block inside while loop - while-loop

I have the following Python function:
def bet():
my_bet = -1
while my_bet < 0 or my_bet > 49:
print("before input")
my_bet = input("Enter a bet: ")
print("after input")
try:
my_bet = int(my_bet)
if my_bet < 0 or my_bet > 49:
print("Bet must be between 0 and 49")
except:
print("Need a number between 0 and 49")
continue
return my_bet
When I run this under Windows 10, I am seeing the following behavior:
>>> bet()
before input
enter a bet: ddd
after input
need a number between 0 and 49
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in bet
TypeError: '<' not supported between instances of 'str' and 'int'
I have also tried moving the if statement after the conversion to int into the else clause of the try statement, with the exact same result. It looks like the conversion is run, raises the exception, then the except block is run, but instead of continuing the loop, it executes the rest of the 'try' code block. According to the Python description, I would not expect the rest of the try block after the exception is raised. What am I doing wrong?

Thanks Vorspring durch Technik for pointing out what should have been obvious: after the continue, what is executed is the test of the while loop which is the same as that of the if statement.

Related

using pandas.read_csv, how can one process all errors, receive all non-error data?

Data which, for me, generates an exception instead of invoking the 'on_bad_lines' handler is at:
https://opencalaccess.org/misc/NAMES_CD.TSV
I have this:
bad_lines = list()
def bad_line_finder(x):
bad_lines.append(str(x))
return None
for file in os.listdir(dir):
bad_lines = list()
try:
for df in pd.read_csv(f"{dir}/{file}",
sep='\t',
on_bad_lines=bad_line_finder,
engine='python',
chunksize=1000):
print(f"\n{target}")
df.info()
print(f"Bad Lines: {bad_lines}")
bad_lines = list()
except:
print("EXCEPTION:")
traceback.print_exc()
and this works great. There are errors in the files and the method handles them so that I can keep track of them. Except, why do i still see this:
EXCEPTION:
Traceback (most recent call last):
File "/home/ray/Projects/opencalaccess-data/import.py", line 41, in <module>
for df in pd.read_csv(f"{dir}/{file}",
File "/home/ray/Projects/opencalaccess-data/.venv/lib/python3.10/site-packages/pandas/io/parsers/readers.py", line 1698, in __next__
return self.get_chunk()
File "/home/ray/Projects/opencalaccess-data/.venv/lib/python3.10/site-packages/pandas/io/parsers/readers.py", line 1810, in get_chunk
return self.read(nrows=size)
File "/home/ray/Projects/opencalaccess-data/.venv/lib/python3.10/site-packages/pandas/io/parsers/readers.py", line 1778, in read
) = self._engine.read( # type: ignore[attr-defined]
File "/home/ray/Projects/opencalaccess-data/.venv/lib/python3.10/site-packages/pandas/io/parsers/python_parser.py", line 250, in read
content = self._get_lines(rows)
File "/home/ray/Projects/opencalaccess-data/.venv/lib/python3.10/site-packages/pandas/io/parsers/python_parser.py", line 1114, in _get_lines
new_rows.append(next(self.data))
_csv.Error: ' ' expected after '"'
What is the "on_bad_lines" option doing if it does not handle all of the bad lines? Which of them will it handle and which will it not?
This is a government data source. There are format errors in the data that cannot be corrected by the agency, because they constitute the 0fficial record. So, I must fix them myself. But which of them throw exceptions and which do not?

I get this error when i try to use Wolfram Alpha in VS code python ValueError: dictionary update sequence element #0 has length 1; 2 is required

This is my code
import wolframalpha
app_id = '876P8Q-R2PY95YEXY'
client = wolframalpha.Client(app_id)
res = client.query(input('Question: '))
print(next(res.results).text)
the question I tried was 1 + 1
and i run it and then i get this error
Traceback (most recent call last):
File "c:/Users/akshi/Desktop/Xander/Untitled.py", line 9, in <module>
print(next(res.results).text)
File "C:\Users\akshi\AppData\Local\Programs\Python\Python38\lib\site-packages\wolframalpha\__init__.py", line 166, in text
return next(iter(self.subpod)).plaintext
ValueError: dictionary update sequence element #0 has length 1; 2 is required
Please help me
I was getting the same error when I tried to run the same code.
You can refer to "Implementing Wolfram Alpha Search" section of this website for better understanding of how the result was extracted from the dictionary returned.
https://medium.com/#salisuwy/build-an-ai-assistant-with-wolfram-alpha-and-wikipedia-in-python-d9bc8ac838fe
Also, I tried the following code by referring to the above website....hope it might help you :)
import wolframalpha
client = wolframalpha.Client('<your app_id>')
query = str(input('Question: '))
res = client.query(query)
if res['#success']=='true':
pod0=res['pod'][0]['subpod']['plaintext']
print(pod0)
pod1=res['pod'][1]
if (('definition' in pod1['#title'].lower()) or ('result' in pod1['#title'].lower()) or (pod1.get('#primary','false') == 'true')):
result = pod1['subpod']['plaintext']
print(result)
else:
print("No answer returned")

ValueError: invalid literal for int() with base 10: 'O'

I am relatively new to python, and as such I don't always understand why I get errors. I keep getting this error:
Traceback (most recent call last):
File "python", line 43, in <module>
ValueError: invalid literal for int() with base 10: 'O'
This is the line it's referring to:
np.insert(arr, [i,num], "O")
I'm trying to change a value in a numpy array.
Some code around this line for context:
hOne = [one,two,three]
hTwo = [four,five,six]
hThree = [seven, eight, nine]
arr = np.array([hOne, hTwo, hThree])
test = "O"
while a != Answer :
Answer = input("Please Enter Ready to Start")
if a == Answer:
while win == 0:
for lists in arr:
print(lists)
place = int(input("Choose a number(Use arabic numerals 1,5 etc.)"))
for i in range(0,len(arr)):
for num in range(0, len(arr[i])):
print(arr[i,num], "test")
print(arr)
if place == arr[i,num]:
if arr[i,num]:
np.delete(arr, [i,num])
np.insert(arr, [i,num], "O")
aiTurn = 1
else:
print(space_taken)
The number variables in the lists just hold the int version of themselves, so one = 1, two = 2 three = 3, etc
I've also tried holding "O" as a variable and changing it that way as well.
Can anyone tell me why I'm getting this error?

Tensorflow Object Detection, error while generating tfrecord [TypeError: None has type NoneType, but expected one of: int, long]

When checking across different solutions available on the net, most people (including datitran) pointed out that it might be a missing class or a misspell of a class in the train csv file. Am not able to figure that out since the labelling is done using labelImg, it saves these classes as xml, the xml_to_csv.py converts this to a csv. Am not sure under what circumstance I could have had the opportunity to miss out or misspel any class incorrectly.
Here's the error am dealing with:
(OT)
nisxxxxx#xxxxxxxx:~/Desktop/OD/models/research/object_detection$
python generate_tfrecord.py --csv_input=data/train_labels.csv --
output_path=data/train.record
Traceback (most recent call last):
File "generate_tfrecord.py", line 192, in <module>
tf.app.run()
File "/home/nisxxxxx/Desktop/test_OD/OT/lib/python2.7/site-
packages/tensorflow/python/platform/app.py", line 48, in run
_sys.exit(main(_sys.argv[:1] + flags_passthrough))
File "generate_tfrecord.py", line 184, in main
tf_example = create_tf_example(group, path)
File "generate_tfrecord.py", line 173, in create_tf_example
'image/object/class/label':
dataset_util.int64_list_feature(classes),
File"/home/nishanth/Desktop/test_OD/models/research/object_detection/utils/dat
aset_util.py", line 26, in int64_list_feature
return
tf.train.Feature(int64_list=tf.train.Int64List(value=value))
TypeError: None has type NoneType, but expected one of: int, long
Has anyone been able to solve this problem?
I am not sure how many classes you have used... after the final else try with "return 0 instead of none"... example
if row_label == 'red':
return 1
elif row_label == 'orange':
return 2
elif row_label == 'blue':
return 3
else:
return 0
Just change the label name whatever you labeling them during crop the image by labelImg tool.
def class_text_to_int(row_label):
if row_label == 'raccon':
return 1
else:
None
Instead of 'raccon' put label name for ex:- 'car'.

Python 3 with the range function

I can type in the following code in the terminal, and it works:
for i in range(5):
print(i)
And it will print:
0
1
2
3
4
as expected. However, I tried to write a script that does a similar thing:
print(current_chunk.data)
read_chunk(file, current_chunk)
numVerts, numFaces, numEdges = current_chunk.data
print(current_chunk.data)
print(numVerts)
for vertex in range(numVerts):
print("Hello World")
current_chunk.data is gained from the following method:
def read_chunk(file, chunk):
line = file.readline()
while line.startswith('#'):
line = file.readline()
chunk.data = line.split()
The output for this is:
['OFF']
['490', '518', '0']
490
Traceback (most recent call last):
File "/home/leif/src/install/linux2/.blender/scripts/io/import_scene_off.py", line 88, in execute
load_off(self.properties.path, context)
File "/home/leif/src/install/linux2/.blender/scripts/io/import_scene_off.py", line 68, in load_off
for vertex in range(numVerts):
TypeError: 'str' object cannot be interpreted as an integer
So, why isn't it spitting out Hello World 490 times? Or is the 490 being thought of as a string?
I opened the file like this:
def load_off(filename, context):
file = open(filename, 'r')
'490' is a string. Try int('490').
Sigh, never mind, it did turn out to by evaluated as a string. Changing the for loop to
for vertex in range(int(numVerts)):
print("Hello World")
fixed the problem.