Skip to content
Advertisement

Strange bugs in Python program: `str() cannot be interpreted as integer

I’m converting many of my R programs to Python (a language I don’t use on a day-to-day basis).

Here my program, which simulates a simple card game:

JavaScript

Appearently the bug is in the fill_envelopes line.

Here’s the error returned by the interpreter:

JavaScript

It seems that the interpreter is trying to treat a string object as an integer. This was found while also encountering a TypeError.

Debugging using print statements line-by-line reveals things are working as expected. Thus, i’m a bit lost as to what’s going on here.

Advertisement

Answer

Two quick things: You might have just copy/pasted wrong, but you have a break outside of a loop. If you want that if/else to be in the loop, make sure it is indented correctly. The other thing, which is your actual problem: you are reusing a variable you want to remain static.

Running your code the first time works just fine, but second time breaks. Why? It has to do with this line cards = cards[not cards in pick_envelope]. Here, you replace the cards list with a single card, and then never re-make it into the original list of all 52 cards. I suspect this is actually a typo and you meant for that variable to be the singular card. If this is NOT a typo, you need to re-define the cards list to be the list of 52 cards at the start of the loop. Otherwise, the second time around the loop will have cards = 'someString', and you will get the ValueError.

EDIT: For further clarification – you are getting this error on the second go around the while loop, because you change your cards list to a string that has only one card, which happens to be the card that was ‘chosen’ in the previous iteration. You need to either make sure you don’t change the original cards list, or re-define it at the start of the loop.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement