Incomplete dice game function, dunno why does'nt works...

If you're not using windows, change the dir. "C:/"

def bet(Bet):
    try:
        f = open('C:/money.txt')
        print f
        money = f.readline()
        f.close()
        print ('You have', money, 'Dollars. Wanna play dice(y/n)?')
        v = raw_input()
        if v == 'y':
            # here i'm printing those values because they seem to be bugged when "money = money - Bet", but not in print Bet or print Money
            print money
            print Bet
            money = money - Bet
            dice = random.randrange(1,7)
            if dice == 6:
                money = money + (Bet * 5)
                print '6! Yey! You have', money, 'Dollars'
            else:
                print 'Damm, a', dice, '!', 'Yo have now', money, 'dollars.'
                pass
        else:
            pass
    except IOError:
        money = 1000
        file = open('c:/money.txt', 'w')
        file.write ('1000')
        file.close()
        bet(Bet)

It reports:

>>> bet(10)
<open file 'C:/money.txt', mode 'r' at 0x015A4340>
('You have', '1000', 'Dollars. Wanna play dice(y/n)?')
y
1000
10

Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    bet(10)
  File "C:/Documents and Settings/Terminal/Desktop/dado_english.py", line 13, in bet
    money = money - Bet
TypeError: unsupported operand type(s) for -: 'str' and 'int'
>>>

Dani AI

Generated

Quick diagnosis and context: the TypeError in the original post came from mixing a text value read from disk with integer arithmetic — exactly the mismatch and pointed out, and ' strip hint avoids stray newlines. That fix resolves the immediate crash, but several robustness and portability issues remain (hardcoded path, no validation, no persistence of updated balance, recursion on IOError, Python‑2 vs Python‑3 differences).

A concise checklist of improvements not covered in the thread: keep file handling in a context manager; store the money file in a user directory (avoid C:/); validate and recover from corrupted file contents; enforce that bets are positive integers and do not exceed the balance; persist updates atomically to avoid truncation/corruption; return the new balance from the function (don’t recurse into the same function on error); and prefer integer cents or Decimal for real currency. Also ensure an explicit import of the random module and adapt input/print calls for the active Python version.

Example implementation demonstrating those practices (portable path, validation, atomic write, no recursion):

from pathlib import Path
import random
import tempfile
import os

DEFAULT_BALANCE = 1000
MONEY_FILE = Path.home() / ".dice_money.txt"

def bet(bet_amount, money_file=MONEY_FILE):
    bet_amt = int(bet_amount)
    if bet_amt <= 0:
        raise ValueError("bet must be positive")

    if money_file.exists():
        text = money_file.read_text().strip()
        try:
            balance = int(text)
        except ValueError:
            balance = DEFAULT_BALANCE
    else:
        balance = DEFAULT_BALANCE

    if bet_amt > balance:
        raise ValueError("insufficient funds")

    balance -= bet_amt
    if random.randint(1, 6) == 6:
        balance += bet_amt * 5

    tmp = tempfile.NamedTemporaryFile("w", delete=False, dir=str(money_file.parent))
    try:
        tmp.write(str(balance))
        tmp.close()
        os.replace(tmp.name, str(money_file))
    finally:
        if os.path.exists(tmp.name):
            os.unlink(tmp.name)

    return balance

Notes: adapt raw_input() -> input() and print statements -> print() when moving to Python 3; avoid floats for money unless fractional currency is required (use Decimal). The fixes by and solved the TypeError; the above adds validation, portability, and safe persistence so the game behaves reliably.

Recommended Answers

All 5 Replies

How dos your money.txt look?

Change to this money = int(money) - Bet .

Type check print type(money) . print type(Bet) Your desgin could be better, a long funtion that only ends(no loop)
Try to make a main function that has meny and question then that function call the bet function.
Betting is done and it goes back to main.

Replace line 5 with money = int(f.readline().strip()) .

How dos your money.txt look?

Change to this money = int(money) - Bet .

Type check print type(money) . print type(Bet) Your desgin could be better, a long funtion that only ends(no loop)
Try to make a main function that has meny and question then that function call the bet function.
Betting is done and it goes back to main.

gee thanks, that worked

I'll read about "int"

int is simple function that changes "numeric" strings into integers. There is also double(), str() etc

it's failing because you're trying to subtract an int (Bet) from a string (money). You need to convert the string you read in from the money file into an int. You can use the built-in function int(string) to do that.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.