V
V
Vadimganin2022-04-05 12:56:42
Python
Vadimganin, 2022-04-05 12:56:42

Why are math operations not working properly in SQLite3?

I made a casino with a database and when I play it, the program counts the coins incorrectly. Why?

The code:

import sqlite3
import hashlib
from random import randint

def md5sum(value):
  return hashlib.md5(value.encode()).hexdigest()

with sqlite3.connect('database.db') as db:
  cursor = db.cursor()

  tables = """
  CREATE TABLE IF NOT EXISTS users(
      id INTEGER PRIMARY KEY,
      name VARCHAR(30),
      age INTEGER(3),
      balance INTEGER NOT NULL DEFAULT 2000,
      login VARCHAR(15),
      password VARCHAR(20)
  );
  CREATE TABLE IF NOT EXISTS casino(
      name VARCHAR(50),
      description TEXT(300),
      balance BIGINT NOT NULL DEFAULT 20000
  )
  """

  cursor.executescript(tables)

def registration():
  print('РЕГИСТРАЦИЯ\n')

  name = input('Имя: ')
  age = input('Возраст: ')
  login = input('Придумайте логин: ')
  password = input('Придумайте пароль: ')

  try:
    db = sqlite3.connect('database.db')
    cursor = db.cursor()
    db.create_function('md5', 1, md5sum)

    cursor.execute("SELECT login FROM users WHERE login = ?", [login])
    if cursor.fetchone() is None:
      values = [name, age, login, password]

      cursor.execute("INSERT INTO users(name, age, login, password) VALUES(?, ?, ?, md5(?))", values)
      db.commit()

      print('Вы успешно зарегистрированы! Теперь войдите в систему.')
      log_in()
    else:
      print('Пользователь с таким логином уже существует!')
      registration()

  except sqlite3.Error as e:
    print('Ошибка!', e)
  finally:
    cursor.close()
    db.close()

def log_in():
  print('ВХОД В СИСТЕМУ\n')

  login = input('Введите логин: ')
  password = input('Введите пароль: ')

  try:
    db = sqlite3.connect('database.db')
    cursor = db.cursor()
    db.create_function('md5', 1, md5sum)

    cursor.execute("SELECT login FROM users WHERE login = ?", [login])
    if cursor.fetchone() is None:
      print('Такого пользователя не существует! Зарегистрируйтесь')
      registration()
    elif cursor.execute("SELECT password FROM users WHERE login = ? AND password = md5(?)", [login, password]).fetchone() is None:
      print('Неверный пароль!')
      log_in()
    else:
      print('Вы успешно вошли в систему!')
      play_casino(login)

  except sqlite3.Error as e:
    print('Ошибка!', e)
  finally:
    cursor.close()
    db.close()

def play_casino(login):
  print('КАЗИНО\n')

  try:
    db = sqlite3.connect("database.db")
    cursor = db.cursor()

    cursor.execute("SELECT age FROM users WHERE login = ? AND age >= ?", [login, 18])
    if cursor.fetchone() is None:
      print("Вам недостаточно лет!")
    else:
      bet = int(input("Ставка: "))
      number = randint(1, 100)

      balance = cursor.execute("SELECT balance FROM users WHERE login = ?", [login]).fetchone()[0]
      if balance < bet:
        print("Недостаточно коинов")
      elif balance <= 0:
        print("Недостаточно коинов")
      else:
        if number < 50:
          cursor.execute("UPDATE users SET balance = balance - ? WHERE login = ?", [bet, login])
          cursor.execute("UPDATE casino SET balance = balance + ?", [bet])

          print("Ты проиграл. Твой баланс - " + str(balance) + " коинов")
        else:
          cursor.execute("UPDATE users SET balance = balance + ? WHERE login = ?", [bet, login])
          cursor.execute("UPDATE casino SET balance = balance - ?", [bet])

          print("Ты выйграл! Твой баланс - " + str(balance) + " коинов")

        db.commit()
        play_casino(login)


  except sqlite3.Error as e:
    print('Ошибка!', e)
  finally:
    cursor.close()
    db.close()
  

def main():
  log_in()

if __name__ == '__main__':
  main()


Conclusion:
ВХОД В СИСТЕМУ

Введите логин: g
Введите пароль: ok
Вы успешно вошли в систему!
КАЗИНО

Ставка: 46
Ты проиграл. Твой баланс - 1777 коинов
КАЗИНО

Ставка: 32
Ты проиграл. Твой баланс - 1731 коинов
КАЗИНО

Ставка: 324
Ты проиграл. Твой баланс - 1699 коинов

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mikhail Krostelev, 2022-04-05
@Vadimganin

Your program works exactly as you wrote))
did not notice the pattern?
Bet 46. 1777-46=1731
Bet 32. 1731-32=1699.
Before withdrawing the balance, subtract the bet from it. And so you display the previous balance.
And in general, hiding logic and calculations in SQL queries is such an idea. pull all calculations out of queries. Record only the result.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question