Opening files in pygame error - python

I just can't figure out the problem. So i'm making a game and im using money to buy things in the game and this doesn't seem to be working. I try to write the new spent money in the .txt file and i just get an error.
with open("money.txt", "r") as rm:
game_money = rm.read()
with open("money.txt", "w") as fm:
fm.write(str(game_money))
def Function():
............
slowdown_price = 20
elif action == "buy_slowdown":
if game_money >= 20:
time.sleep(0.5)
game_money -= slowdown_price
slowdown_powerup += 1
with open("money.txt", "w") as wm:
wm.write(str(game_money))
I get the following error:
TypeError: unsupported operand type(s) for -=: 'str' and 'int'

You are using Python 2, which will happily compare integers with strings, so if game_money >= 20: works fine. However, you can't subtract an integer from a string, so game_money -= slowdown_price fails. Convert that value to an integer (or float) after you read it in:
game_money = int(rm.read())
or
game_money = float(rm.read())
If you use floating-point numbers, keep in mind that they aren't exact, so exact comparisons with == and != aren't reliable.

Reading from a file results in a string. That means that game_money is a string that contains the characters of a number, e.g "30".
You should cast the string to an integer:
game_money = int(rm.read())
Do take note that this could fail if the file does not contain just a number, but other non-numerals.

It seams that you try to substract number slowdown_price from text game_money. You have to convert game_money to number first. ie.
game_money = int(game_money)

Related

Python String Comparison Error: invalid literal for int() with base 10:

I'm new to python so go easy on me here...
In this instance formattedRank = 'N.A.'
if(int(formattedReview) <= 50 and (formattedRank == "N.A.") and (formattedReview == "N.A.")):
print("hi")
rank = int(formattedRank)
review = int(formattedReview)
totalRank += rank
totalReviews += rank
count += 1
Error:
ValueError: invalid literal for int() with base 10: 'N.A.'
Why might this error be happening I come from a mostly C#, Javascript background so I'm sure a lack of knowledge here is hurting me
Easy enough to narrow this down to a minimal example:
formattedRank = 'N.A'
int(formattedRank)
The int function simply does not accept the string 'N.A'. It doesn't know how to interpret it as an integer, and why should it? It doesn't correspond to any integer.
Wait a minute ... this isn't possible to pass:
if(int(formattedReview) <= 50 and
(formattedRank == "N.A.") and
(formattedReview == "N.A.")):
If formattedReview is the string "N.A.", then it cannot convert to an integer, let alone one that is <= 50. Your logic is faulty ... and I expect that your problematic value of formattedReview has non-digits in the string, which will easily cause the error.

Python: Trying to convert string to int, get error to int invalid literal for int() with base 10: ''

I am new to Python, so I apologize if this is a simple fix. I have been stuck on a Codeval problem (Happy Numbers) for quite some time and I am not sure what is going wrong.
Problem Description:
Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1, or it loops endlessly in a cycle which does not include 1.Those numbers for which this process ends in 1 are happy, while those that do not end in 1 are unhappy.
For example:
7 is a happy number (7->49->97->130->10->1)
22 is not a happy number (22->8->64->52->29->85->89->145->42->20->4->16->37->58->89 ...)
My test input and expected outcome:
1 --> 1
7 --> 1
22 --> 0
If the number is a happy number, print out 1. If not, print out 0.
Here is the full Traceback:
Traceback (most recent call last):
File "/happy_number.py", line 58, in <module>
happy_number_check("happy_numbers.txt")
File "/happy_number.py", line 55, in happy_number_check
happy_or_not(line)
File "/happy_number.py", line 33, in happy_or_not
i = int(i)
ValueError: invalid literal for int() with base 10: ''
Here is my code:
# test = 7
def happy_or_not(number):
number = str(number)
if number == 1:
print 1
else:
new_num = 0
for i in number:
i = int(i)
if i == " ":
continue
else:
new_num += i**2
if new_num == 10 or new_num == 10:
print 1
else:
try:
happy_or_not(new_num)
except RuntimeError:
print 0
# happy_or_not(test)
def happy_number_check(file):
f = open(file, 'r+')
for line in f:
if line == "":
continue
else:
happy_or_not(line)
happy_number_check("happy_numbers.txt")
What I have already tried:
Based on what I gathered from other similar questions, the issue may be that I am not able to convert a str into an int when I hit the line i = int(i). It is my understanding that I have to convert the str type into an int type before doing any math on it, yet it looks like that is where it is failing.
I tested the happy_or_not function by itself, and it does print out the value that I expect it to. It seems like to me that the issue comes when I try and call that happy_or_not function inside of the happy_number_check function, which is reading my txt file (containing a list of numbers to test). I must not be grasping a larger principle here, so any explanations would be helpful.
This is also my first real attempt at a recursive function and there probably is a better way to structure this, so any suggestions on how to change things up to be more effective is most welcome.
Thank you in advance!
Try changing happy_number_check like this (validate each line is an integer):
def happy_number_check(file):
with open(file, 'r+') as f: # Safer way to open a file. Will automatically close for you even if something goes wrong
for line in f:
if line.strip().isdigit():
happy_or_not(line.strip())
The strip() will also make it so that you can remove this code:
if i == " ":
continue
else:
By the way, you also have a bug in your logic. You are relying on a RuntimeError - a Stack Overflow interestingly enough :-) - to terminate a test. You should really keep track of what numbers have been tried, and if you try the same number again, return 0.
Don't click this link if you don't want a straight up solution to the problem, but if you do, here is an iterative solution: http://rosettacode.org/wiki/Happy_numbers#Python

How to let python use negative numbers

I've been making a linear equation calculator and I'm wondering how to let python use negative numbers. Like int(), float() etc...
here is my code.
import time
print("Hello and welcome to the linear equation calculator.")
time.sleep(2)
print("Enter the first co-ordinate like this - (xx, yy): ")
coordnte1 = input()
print("Now enter the second co-ordinate like this, with the brackets, - (xx,yy): ")
coordnte2 = input()
print("Now the y-intercept: ")
yintrcpt = input()
ydif = coordnte2[1] - coordnte1[1]
xdif = coordnte2[0] - coodrnte1[0]
g = ydif / xdif
print("y = " + g + "x + " + yintrcpt)
And the problem:
Traceback (most recent call last):
File "C:/Users/Dale/Documents/GitHub/new_python_rpi_experiments/linear.py", line 17, in <module>
ydif = coordnte2[1] - coordnte1[1]
TypeError: unsupported operand type(s) for -: 'str' and 'str'
I'm very new to Python, so any help would be appreciated.
What your are reading from the input is a string, you need to extract the coordinates and convert them to float, for example:
print("Enter the first co-ordinate like this - (xx, yy): ")
s = input()
Now s = "(34, 23)" is a string and you need to process it (eliminate parens, comma, etc...):
coords = [float(coord) for coord in s.strip('()').split(',')]
Now coords is a list(array) of floats and you can do coords[0]- coords[1] and so on.
The problem has nothing to do with negative numbers. It's that input() gives you a text string. Python doesn't know how to subtract or do math with text strings, even if they happen to contain numeric characters.
You will need to write a function to convert a string of the form (10,3) to two numbers. I'll let you explore how to do that, but the strip and split methods of the string object may be useful to you, and you can use int() or float() on a string that contains only a numeric value to convert it to an integer or floating-point numeric variable. For example: int('123') gives you the number 123.
Try int:
ydif = int(coordnte2[1]) - int(coordnte1[1])
xdif = int(coordnte2[0]) - int(coodrnte1[0])
ydif = float(coordnte2[1]) - float(coordnte1[1])
I think is your problem ...
Try using eval to convert the string to type, e.g.
coordnte1 = eval(coordnte1)
coordnte2 = eval(coordnte2)
You might want to put that in a try statement, because it will fail if the user inputs a string that can't be evaluated.

Python 'int' object is not subscriptable

Im trying to read a file and make sure that each value is in order. I dont think im converting the string into the integer correctly. Here is some of my code. I am also trying to use flags.
fileName = input("What file name? ")
infile = open(fileName,'r')
correct_order_flag = False
i = 0
line = infile.readline()
while line !="":
for xStr in line.split(" "):
if eval(xStr) [i] < i:
correct_order_flag = True
else:
correct_order_flag = False
i = i+1
if correct_order_flag:
print("Yes, the numbers were in order")
else:
print("No, the numbers were not in order")
count = i - 1
print("There were", count, "numbers.")
You are correct - you are indicating with eval(xStr)[i] that eval(xStr) is an array, and thus can be subscripted. What it looks like you may want (since you say you want to convert the string to an int) is just int(xStr), to make that whole line:
if int(xStr) < i:
For starters, you don't read the whole file at all. Try this:
with open(fileName) as f:
for line in f:
# here goes your code
Not sure though, what do you mean by "each value is in order", but using eval() is a VERY bad idea for any purpose.
I would like to add that because you are comparing xstr[i] to i that unless your first number is less than zero the flag will change, meaning that the sequence 1 2 3 4 5 would print out saying "NO, the numbers were not in order"
As Chris indicated, int(s) is the preferred way to convert a string to an integer. eval(s) is too broad and can be a security risk when evaluating data from an untrusted source.
In addition, there is another error in the script. The *correct_order_flag* is being set on every iteration, so one entry with incorrect order can be masked by a subsequent entry in the correct order. Accordingly, you should break out of the loop when incorrect ordering is found.

simple python program help!

This program is supposed to calculate the number of degrees below 60 on a given day then create a running sum of degrees. count equals the sum of degrees below 60. However, when I run it I get this error:
cool = 60 - temp
TypeError: unsupported operand type(s) for -: 'int' and 'str'
Any ideas on why it's doing this? Thanks!
def cold_days():
temp = eval(input("What is the temperature? "))
count = 0
if temp < 60:
while temp !="quit":
temp = eval(input("What is the temperature? "))
cool = 60 - temp
count = count + heat
print(count)
else:
print("you have no cold days")
You need to turn temp into an int:
...
try:
temp = int(temp)
except TypeError:
# Handle invalid integer
print("%s is not a valid integer." % temp)
sys.exit(1)
...
In Python 3, the input() function always returns a string (this is different from Python 2, and could be the source of the confusion since the Python tutorial you're using might be unaware of Python 3). Since Python is strongly (but dynamically) typed, you can't perform arithmetic calculations using a string and an integer, as your error message shows. You must first convert the temp string into an integer using int():
temp = int(temp)
If temp does not contain something that can be converted to an integer, you will get a ValueError exception. By default, an exception will terminate your program with an informative error message. To handle the exception and take alternative action, your Python tutorial should have a whole chapter on that.
You can just drop the 'eval' since input does return the correct type. Or typecast the temp to int:
temp = int(temp)
I think you need to rethink how you are reading in data. input() returns eval() of whatever text the user types in, so I would expect an error when the user types "quit".
Instead, I suggest using raw_input() which returns text. Then check if it is equal to "quit" before converting to an int.

Categories

Resources