10
\$\begingroup\$

I'm new to Python and coded this spin-the-wheel game where the user can bet on each spin of the wheel and either double their money, 1.5x their money, lose their money or keep it.

It all seems to be working fine (I think), but I was wondering if there were any improvements to the structure and efficiency of my code I could make. Or a new feature I could add.

#Spin the wheel game
bet = 0
print("=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=")
print("         Welcome to spin the wheel")
print("                  With bets")
print("=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=")
print("There is 5 options on the wheel:")
print("Green doubles your money")
print("Blue loses your money")
print("Yellow 1.5x your money")
print("Red returns your money")
print("Orange loses your money")
ballance = 0
money = False
while money == False:
    deposit = input("Please deposit money to play: £")
    if deposit.isdigit():
        deposit = int(deposit)
        if deposit > 0:
            print("Thank you your balance is currently: £",ballance+deposit)
            money = True
            ballance = deposit + ballance
        else:
            print("Please deposit at least £1.")
    else:
        print("Please enter a numerical amount.")
play = True
while play == True:
    money = False
    while money == False:
        bet = input("Please enter how much you'd like to bet on this spin: £")
        if bet.isdigit():
            bet = int(bet)
            if bet <= ballance:
                print("Thank you, you have just bet: £",bet)
                ballance = ballance - bet
                money = True
            else:
                print("Please bet an amount that is no larger than your balance of: £",ballance)
        else:
            print("Please enter a numerical amount or a an amount above 0.")
    colour = "green"
    import random
    spin = random.randint(1,5)
    if spin == 1:
        outcome = bet*2
    elif spin == 2:
        outcome = bet - bet
        colour = "Blue"
    elif spin == 3:
        outcome = bet*1.5
        colour = "Yellow"
    elif spin == 4:
        outcome = bet
        colour = "Red"
    else:
        outcome = bet - bet
        colour = "Orange"
    start = input("Hit enter to spin the wheel")
    while start != "":
        quit()
    print("It landed on:",colour)
    if outcome == 0:
        print("That means you lost your bet of £",bet)
    if outcome == bet:
        print("You got your money back.")
    if outcome > bet:
        print("You made: £",outcome - bet,"So got £",outcome,"back.")
    print("Your balance is now: £",ballance+outcome)
    ballance = ballance+outcome
    again = input("Would you like to play another round? ").lower()
    if again in ["yes","y"]:
        if ballance >= 1:
            play = True
        else:
            money = False
            while money == False:
                deposit = input("You have run out of money. Please deposit more money to keep playing. £")
                if deposit.isdigit():
                    deposit = int(deposit)
                    if deposit > 0:
                        print("Thank you your balance is currently: £",ballance+deposit)
                        ballance = deposit + ballance     
                        money = True
                    else:
                        print("Please deposit at least £1.")
                else:
                    print("Please enter a numerical amount.")
    else:
        play = False
        print("Thank you for playing")
        print("Your final balance was: £", ballance)
        if ballance > 0:
            withdraw = input("Would you like to withdraw your money? ").lower()
            if withdraw in ["yes","y","please"]:
                print("We have deposited your balance of £",ballance,"into your bank account.")
                ballance = ballance - ballance
                print("Your balance is now: £",ballance)
            else:
                print("That's ok, we will keep your money for next time you play.")
\$\endgroup\$

3 Answers 3

10
\$\begingroup\$

I think the biggest improvement that you can make is to use functions instead of putting all functionality in one big block of code. The main advantage of functions is that it will be easier to understand and maintain the code, and another advantage is that you can avoid global variables, which are generally considered bad practice.

Another improvement is to avoid the use of "flags" (i.e. variables such as money and play in your code) for program control. Besides that the names are not really descriptive, most programming languages have easier constructs to achieve the same. For example break or return. You will see that this makes your code shorter and simpler.

Other remarks:

  • Place imports at the top of your file.
  • In Python, it is more common to write while x: than while x == True:.
  • Instead of balance = balance - balance you could write balance = 0.
  • quit() is intended to be used in the interpreter and should not be used in scripts. They can cause problems in the future. Use sys.exit() instead.
  • Using pylint and/or an IDE will help you quickly identify potential coding issues and get free tips on improving your code.
  • Following the style guide PEP 8 will help you improve your code and make it more recognizable for others around the world.

I partly implemented above tips in the following code. It is not completely rewritten, but I think it demonstrates the above points.

# Spin the wheel game

import random
import sys


def print_intro_text():
    print('=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=')
    print('         Welcome to spin the wheel')
    print('                  With bets')
    print('=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=')
    print('There is 5 options on the wheel:')
    print('Green doubles your money')
    print('Blue loses your money')
    print('Yellow 1.5x your money')
    print('Red returns your money')
    print('Orange loses your money')


def get_deposit(old_balance=0):
    while True:
        deposit = input('Please deposit money to play: £')
        if deposit.isdigit():
            deposit = int(deposit)
            if deposit > 0:
                new_balance = old_balance + deposit
                print('Thank you your balance is currently: £', new_balance)
                return new_balance
            print('Please deposit at least £1.')
        else:
            print('Please enter a numerical amount.')


def get_bet(balance):
    while True:
        bet = input('Please enter how much you\'d like to bet on this spin: £')
        if bet.isdigit():
            bet = int(bet)
            if bet <= balance:
                print('Thank you, you have just bet: £', bet)
                return bet
            print('Please bet an amount that is no larger than your balance of: £', balance)
        else:
            print('Please enter a numerical amount or a an amount above 0.')


def play(balance):
    while True:
        bet = get_bet(balance)
        balance -= bet

        # The rest of this code is left as an exercise to improve / refactor.

        colour = 'green'
        spin = random.randint(1, 5)
        if spin == 1:
            outcome = bet * 2
        elif spin == 2:
            outcome = bet - bet
            colour = 'Blue'
        elif spin == 3:
            outcome = bet * 1.5
            colour = 'Yellow'
        elif spin == 4:
            outcome = bet
            colour = 'Red'
        else:
            outcome = bet - bet  # FIXME
            colour = 'Orange'
        start = input('Hit enter to spin the wheel')
        while start != '':
            sys.exit()
        print('It landed on:', colour)
        if outcome == 0:
            print('That means you lost your bet of £', bet)
        if outcome == bet:
            print('You got your money back.')
        if outcome > bet:
            print('You made: £', outcome - bet, 'So got £', outcome, 'back.')
        print('Your balance is now: £', balance + outcome)
        balance = balance+outcome
        again = input('Would you like to play another round? ').lower()
        if again in ['yes', 'y']:
            if balance < 1:
                money = False
                while not money:
                    deposit = input('You have run out of money. Please deposit more money to keep playing. £')
                    if deposit.isdigit():
                        deposit = int(deposit)
                        if deposit > 0:
                            print('Thank you your balance is currently: £', balance + deposit)
                            balance = deposit + balance
                            money = True
                        else:
                            print('Please deposit at least £1.')
                    else:
                        print('Please enter a numerical amount.')
        else:
            print('Thank you for playing')
            print('Your final balance was: £', balance)
            if balance > 0:
                withdraw = input('Would you like to withdraw your money? ').lower()
                if withdraw in ['yes', 'y', 'please']:
                    print('We have deposited your balance of £', balance, 'into your bank account.')
                    balance = balance - balance
                    print('Your balance is now: £', balance)
                else:
                    print('That\'s ok, we will keep your money for next time you play.')
            break


def main():
    print_intro_text()
    balance = get_deposit()
    play(balance)


if __name__ == '__main__':
    main()
\$\endgroup\$
7
\$\begingroup\$

Use while True instead of while flag:

An idiomatic and simpler way to loop until condition is changed, is using:

while true:
    # code
    if some_condition:
        break

Instead of maintaining a flag variable and looping until it changes.

Using dicts to select predetermined options

When you want a different outcome according to a value (in other languages usually called case), if/elif structure can become ugly and hard to maintain. In its place, it is common in Python to use a dict to choose the outcome. For example, for your colour/outcome logic we can reduce the code to two lines. First of all the spin is not really necessary - it is just used to choose a color. So instead we can assign to each color its functionality and choose that:

colours = {"green": bet*2, "blue": 0, "yellow": bet*1.5, "red": bet, "orange": 0}
colour, outcome = random.choice(list(colours.items()))

Pack repeating code to functions

The loop for taking new deposit from the user is repeating two times with very slight differences. In that case it is possible to put the code in a function and re-use it. The bet loop is a bit different so for now it is better to keep it separate.

Input handling

The way you did the input handling is fine and covers all cases I think, but according to this SO post we can improve it (IMO) a little bit to be:

while True:
    try:
        deposit = int(input("Please deposit money to play: £"))
    except ValueError:
        print("Please enter a numerical amount.")
        continue

    if deposit > 0:
        balance += deposit
        print("Thank you your balance is currently: £", balance)
        return balance
    else:
        print("Please deposit at least £1.")

Imports at the top

It is usually common to have all imports (in this case just random) at the top of the file and not scattered around.

Small PEP-8 corrections

PEP-8 is the styling guide for Python so a few corrections were in place regarding spaces and such.

Some other minor corrections

There were a few small things that looked weird (like bet - bet), or simple improvements to make (like x += y instead of x = x + y).

Full code:

# Spin the wheel game
import random

print("=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=")
print("         Welcome to spin the wheel")
print("                  With bets")
print("=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=|=")
print("There is 5 options on the wheel:")
print("Green doubles your money")
print("Blue loses your money")
print("Yellow 1.5x your money")
print("Red returns your money")
print("Orange loses your money")

def get_new_balance(balance, message):
    while True:
        try:
            deposit = int(input(message))
        except ValueError:
            print("Please enter a numerical amount.")
            continue

        if deposit > 0:
            balance += deposit
            print("Thank you your balance is currently: £", balance)
            return balance
        else:
            print("Please deposit at least £1.")

balance = get_new_balance(0, "Please deposit money to play: £")

while True:
    while True:
        try:
            bet = int(input("Please enter how much you'd like to bet on this spin: £"))
        except ValueError:
            print("Please enter a numerical amount.")
            continue

        if bet > balance:
            print("Please bet an amount that is no larger than your balance of: £", balance)
        else:
            print("Thank you, you have just bet: £", bet)
            balance -= bet
            break

    colours = {"green": bet*2, "blue": 0, "yellow": bet*1.5, "red": bet, "orange": 0}
    colour, outcome = random.choice(list(colours.items()))

    start = input("Hit enter to spin the wheel")
    print("It landed on:", colour)
    if outcome == 0:
        print("That means you lost your bet of £", bet)
    if outcome == bet:
        print("You got your money back.")
    if outcome > bet:
        print("You made: £", outcome - bet, "So got £", outcome, "back.")

    balance += outcome
    print("Your balance is now: £", balance)

    again = input("Would you like to play another round? ").lower()
    if again in ("yes", "y"):
        if balance < 1:
            balance = get_new_balance(balance, "You have run out of money. Please deposit more money to keep playing. £")

    else:
        print("Thank you for playing")
        print("Your final balance was: £", balance)
        if balance > 0:
            withdraw = input("Would you like to withdraw your money? ").lower()
            if withdraw in ("yes", "y", "please"):
                print("We have deposited your balance of £", balance, "into your bank account.")
                balance = 0
                print("Your balance is now: £", balance)
            else:
                print("That's ok, we will keep your money for next time you play.")
        break
\$\endgroup\$
3
\$\begingroup\$

The two existing answers are quite good, but I picked up on one detail that they did not address.

print() and string formatting

I notice that a lot of your print statements leave odd spaces in the output. I am not sure if this was your intent.

For example, the code

print("Thank you your balance is currently: £", balance)

produces outputs like:

Thank you your balance is currently: £ 300

This would look more natural if there was no space between the pound sign and the number. The solution is to build a single nice-looking string and then print it, instead of printing a list of different values.

There are a few different ways to build a nicely-formatted string in Python, but I would use f-strings. Put an f at the start of the string, and then put your variables inside the string, wrapped in curly brackets/braces.

print(f"Thank you. Your balance is currently £{balance}.")

Thank you. Your balance is currently £300.

You can do other interesting things with f-strings (like printing numbers to a certain number of decimal places, or padding values with spaces so they print in neat columns), but I won't get into that here.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.