#πŸ”’ Hi, I'm looking for ways to improve this code.

94 messages Β· Page 1 of 1 (latest)

strange agate
#

Hello, i made this code today in my computer science lesson. I feel like I made too much use of if statements and I am not sure if there were any other things I couldve done to make it work. Any advice is appreciated πŸ™‚

import random
Credit = 100
Answer = input('Would you like to play the game? (y/n):')

while Credit > 0 and Answer == 'yes':
print(Credit)
Answer = input('Would you like to play the game? (y/n):')
if Answer != 'yes':
print('Okay, you are leaving with ', Credit , ' credits.')
break
Credit -= 20
Value1 = random.randint(1,4)
Value2 = random.randint(1, 4)
Value3 = random.randint(1, 4)

if Value1 == Value2 == Value3:
    if Value1 == 1:
        print('You got three lemons! +100 credit!')
        Credit += 100

    if Value1 == 2:
        print('You got three cherries! +100 credit!')
        Credit += 100

    if Value1 == 3:
        print('You got three Bells! +500 credit!')
        Credit += 500

    if Value1 == 4:
        print('Unlucky! The game is over!')
        Credit == 0





elif Value1 == Value2 or Value3 == Value2 or Value3 == Value1:
    if Value1 == Value2 or Value1 == Value3:
        if Value1 == 1:
            print('You got two lemons! +50 credit!')
            Credit += 50
        if Value1 == 2:
            print('You got two cherries! +50 credit!')
            Credit += 50
        if Value1 == 3:
            print('You got two bells! +100 credit!')
            Credit += 100
        if Value1 == 4:
            print('You got two skulls! Unlucky, -100 credit!')
            Credit -= 100
    if Value2 == Value3:
        if Value2 == 1:
            print('You got two lemons! +50 credit!')
            Credit += 50
        if Value2 == 2:
            print('You got two cherries! +50 credit!')
            Credit += 50
        if Value2 == 3:
            print('You got two bells! +100 credit!')
            Credit += 100
        if Value2 == 4:
            print('You got two skulls! Unlucky, -100 credit!')
            Credit -= 100

else:
    print('You didn't win anything'.)
pale shaleBOT
#

@strange agate

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

hollow frigate
#

I guess the first thing to change is print('You didn't win anything'.), you need to use different " and ' if you're mixing them in a string

elder nest
#
if Value1 == 4:
    print('Unlucky! The game is over!')
    Credit == 0
#

You're also using == here to try and set credits to 0, but it should be Credit = 0

#

it seems to be some sort of slot machine game though

hollow frigate
#

using the answer y doesn't actually start the game since you're checking for the answer 'yes' not 'y'

unkempt heath
#

a style thing, but in python variables are usually in snake_case

hollow frigate
#

I got up to 280 credits and then lost it all, 10/10 mimics reality well

strange agate
strange agate
elder nest
#

instead of Value1 do value_1

hollow frigate
#

it means if you want to name something, you do credit instead of Credit and value_1 instead of Value1

strange agate
#

My tutor usually has me use CamelCase

elder nest
#

camelCase has no place in python

strange agate
#

Why's that?

elder nest
#

because that's the styling that the python community has agreed upon

strange agate
#

Im only doing it at GCSE level for now

elder nest
#

better to break bad habits now though

strange agate
hollow frigate
#

camelCase is used in other languages, probably those your teacher is familiar with

strange agate
#

Yeah I guess.

#

Took me a whole hour to write this so you can probably guess how rubish I am lol

#

Well like 45 minutes but still

strange agate
hollow frigate
#

everyone starts from the same place and takes ages

hollow frigate
strange agate
#

Ohhh I see

hollow frigate
#

!e

print('You didn't win anything'.)
pale shaleBOT
#

@hollow frigate :x: Your 3.12 eval job has completed with return code 1.

001 |   File "/home/main.py", line 1
002 |     print('You didn't win anything'.)
003 |                                   ^
004 | SyntaxError: unterminated string literal (detected at line 1)
hollow frigate
#

!e

print('You didn't win anything.')
pale shaleBOT
#

@hollow frigate :x: Your 3.12 eval job has completed with return code 1.

001 |   File "/home/main.py", line 1
002 |     print('You didn't win anything.')
003 |                                    ^
004 | SyntaxError: unterminated string literal (detected at line 1)
strange agate
#

Thanks, I didn't notice that it was outside the area

hollow frigate
#

!e

print("You didn't win anything".)
pale shaleBOT
#

@hollow frigate :x: Your 3.12 eval job has completed with return code 1.

001 |   File "/home/main.py", line 1
002 |     print("You didn't win anything".)
003 |                                     ^
004 | SyntaxError: invalid syntax
hollow frigate
#

!e

print("You didn't win anything.")
pale shaleBOT
#

@hollow frigate :white_check_mark: Your 3.12 eval job has completed with return code 0.

You didn't win anything.
strange agate
#

from the looks of it when I did it in pycharm and pasted it over I mustve accidentaly put a fullstop

#

Because the original pycharm bit doesnt have it

#

Tyvm for all the help btw

#

Write a program to simulate a Fruit Machine that displays three symbols at random from Cherry, Bell, Lemon, Orange, Star, Skull.
The player starts with Β£1 credit, with each go costing 20p. If the Fruit Machine β€œrolls” two of the same symbol, the user wins 50p. The player wins Β£1 for three of the same
and Β£5 for 3 Bells. The player loses Β£1 if two skulls are rolled and all of his/her money if three skulls are rolled. The player can choose to quit with the winnings after each
roll or keep playing until there is no money left.

#

This was the prompt for it ^

hollow frigate
#

also what is the point of doing

    elif Value1 == Value2 or Value3 == Value2 or Value3 == Value1:
        if Value1 == Value2 or Value1 == Value3:
...
        if Value2 == Value3:
``` ? you've already checked that one of those is true but then outcome of any 2 numbers being equal is always the same, so I don't see why that bit of code is repeated
#

your machine doesn't contain oranges and stars

strange agate
#

Uh I had to narrow it down so I could do Value1 and stuff

strange agate
#

It was just a little bit of practice and we said we only needed the 4 for now

hollow frigate
#

ah I see

strange agate
#

Im not really sure how to explain what I mean lol

#

Because we need to know if it's value1 that is the same as 1 or value2 or value3 basically

hollow frigate
#

I understand, but there are better ways of doing that

strange agate
#

Yeah that's what I was here to ask

#

I dont know other ways of doing it

hollow frigate
#

let me try and write something up

strange agate
strange agate
hollow frigate
#

I've been waiting for 2 hours for a script to finish running so I can do other work, I can spend a bit of time on this πŸ˜„

strange agate
#

2 hours? I didnt even know code could take that long to run lol.

hollow frigate
#

well I'm processing 24GB of data that then goes through a bunch of steps so it takes a while

#

running it on my laptop...

strange agate
#

Jesus what do you need that much data for lol

hollow frigate
#

medical research

#

3D images are big

strange agate
#

Damn, the amount of interesting stuff ive seen in this server in the half an hr ive been here is crazy.

elder nest
hollow frigate
#

true, still working on the game

hollow frigate
# strange agate I dont know other ways of doing it

without spending too much time optimising and perfecting it, this is more or less how I would do it

import random
from collections import Counter

emoji_dict = {
    'lemon': '\U0001F34B',
    'cherry': '\U0001F352',
    'bell': '\U0001F514',
    'orange': '\U0001F34A',
    'star': '\U00002B50',
    'skull': '\U0001F480'
}

symbols = ['lemon', 'cherry', 'bell', 'orange', 'star', 'skull']
SYMBOLS = [emoji_dict[fruit] for fruit in symbols]

def main():
    credit = 100
    credit = fruit_game(credit)
    print(f'You are leaving with {credit} credits.')

def fruit_game(credit: int) -> int:
    #This function plays the fruit game
    while True:
        print(f'You have {credit} credits.')
        user_input = input('Would you like to play the game? (y/n): ')
        if user_input != 'y':
            return credit
        if credit < 20:
            print('You do not have enough credits to play the game.')
            return credit
        credit = play_round(credit)
#
def play_round(credit: int) -> int:
    #This function plays one round of the fruit game
    credit -= 20
    values = [random.choice(SYMBOLS) for _ in range(3)]
    print(' '.join(values))
    duplicates = get_duplicates(values)
    print(duplicates)
    #3 of the same value
    if len(duplicates) == 3:
        if duplicates[0] == emoji_dict['skull']:
            print(f'Unlucky! The game is over!')
            return 0
        #Get 500 if the three values are bells otherwise 100
        winnings = 500 if duplicates[0] == emoji_dict['bell'] else 100
        credit += winnings
        print(f'You got {get_fruit(duplicates[0])}! +{winnings} credits!')
    #2 of the same value
    elif len(duplicates) == 2:
        if duplicates[0] == emoji_dict['skull']:
            print(f'You got two skulls! Unlucky, -100 credit!')
            credit -= 100
        else:
            winnings = 100 if duplicates[0] == emoji_dict['bell'] else 50
            credit += winnings
            print(f'You got two {get_fruit(duplicates[0])}! +{winnings} credits!')
    else:
        print(f'No matches! Try again!')
    return credit

def get_duplicates(lst: list) -> list:
    #This function returns a list of duplicates in the given list
    counter = Counter(lst)
    duplicates = [item for item in lst if counter[item] > 1]
    return duplicates

def get_fruit(emoji: str) -> str:
    #This function returns the fruit name based on the emoji
    for fruit, emoji_value in emoji_dict.items():
        if emoji_value == emoji:
            return fruit

if __name__ == '__main__':
    main()
elder nest
#

This is likely introducing a lot of new things they aren't familiar with though

hollow frigate
#

I can always answer questions about individual bits

elder nest
#

I think it's some nice code, but it's a lot to throw at someone. functions, typehinting, dicts, list comp, lists

hollow frigate
#

I'll do a smaller change

strange agate
#

Uh it's really cool for sure but honestly I've got no clue what half of it means, I still havent gotten functions down yet.

hollow frigate
#
import random
from collections import Counter

credit = 100
answer = input('Would you like to play the game? (y/n):')

def get_duplicates(lst: list) -> list:
    #This function returns a list of duplicates in the given list
    counter = Counter(lst)
    duplicates = [item for item in lst if counter[item] > 1]
    return duplicates

while credit > 0 and answer == 'yes':
    print(credit)
    answer = input('Would you like to play the game? (y/n):')
    if answer != 'yes':
        print('Okay, you are leaving with ', credit , ' credits.')
        break
    credit -= 20
    values = [random.randint(1,4) for _ in range(3)]
    duplicates = get_duplicates(values)

    if len(duplicates) == 3:
        if duplicates[0] == 4:
            print('Unlucky! The game is over!')
            credit = 0
        elif duplicates[0] == 3:
            print('You got three Bells! +500 credit!')
            credit += 500
        else:
            print('You got three of the same value! +100 credit!')
            credit += 100
    elif len(duplicates) == 2:
        if duplicates[0] == 4:
            print('You got two skulls! Unlucky, -100 credit!')
            credit -= 100
        elif duplicates[0] == 3:
            print('You got two bells! +100 credit!')
            credit += 100
        else:
            print('You got two of the same value! +50 credit!')
            credit += 50
    else:
        print("You didn't win anything.")
strange agate
#

Thank you very much for the advice and ill make sure to message my tutor to ask if we can go thru it together πŸ™‚

strange agate
hollow frigate
#

this would be the smaller change, just instead of checking for individual values, you can grab everything that is the same in your list of numbers and give points based on that

strange agate
#

You're clearly amazing at this lol, how long have you been practicing?

strange agate
hollow frigate
#

everything I used here I knew after about a year of doing nothing but coding (covid times)

elder nest
#

most of programming is "work smarter not harder"

#

finding ways to not repeat yourself and to write code that can accommodate any data size instead of just a specific one

#

if your game had 5 rows instead of 3, you'd have to rewrite almost your entire code

#

and it would start to get exponentially longer

#

instead, you need to find a way to write code that can score "any" row size

#

A common saying is that there's only 3 numbers in programming

#

Zero
One
Many

strange agate
#

Sorry if I'm not responding, I am reading the messages and I appreciate all the advice im just a bit busy right now πŸ™‚

pale shaleBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.