Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

Python Number Hi-Low game.

menator01

Gold Coder
Been a while since posting so, I though I would get a number guessing game started and see if anyone wants to add to it. Change re-arrange or whatever needed.
I've done several just thought I would try and get some kind of community group thing going. Sorry if I've posted this under the wrong topic.

Modules needed is pandas and tabulate. Both can be gotten using pip

Python:
# Do the imports
from pandas import DataFrame as df
from tabulate import tabulate as tb

# Create Player class
class Player:
    '''
        Player class contains a name and scores for win/loose/tie
    '''
    def __init__(self, name='Computer'):
        self.stats = {
            'name': name.title(),
            'wins': 0,
            'losses': 0,
            'ties': 0
        }

# Create winner class
class Winner:
    '''
        Winner class does our comparison to see who wins
    '''
    def __init__(self, number):
        self.number = number

    def __lt__(self, other):
        return self.number < other.number
    
    def __gt__(self, other):
        return self.number > other.number
    
    def __eq__(self, other):
        return self.number == other.number
    

if __name__ == '__main__':

    # Using while loop to get a player name and some error checking
    while True:
        print('Enter player name:')
        name = input('>> ')

        # If statement to make sure only letters are used for name
        # Sets up our player and computer player
        # Else is some basic error checking
        if name.strip().isalpha():
            player = Player(name)
            player2 = Player()
            break
        else:
            print('You must enter a name.\nNames can only contain letters.')
    
    # Start the game loop
    while True:
        # A way to exit the game
        print('Enter \'q\' to quit')
        data = [player.stats, player2.stats]

        # Print out player and computer player data
        print(tb(df(data), tablefmt='grid', headers=[dat.title() for dat in data[0].keys()], showindex=False, numalign='center'))
        
        # Prompt for getting user input
        user_input = input('>> ').lower()

        # q was entered exit the game
        if user_input == 'q':
            print('Goodbye!')
            break

        # Play the game
        else:

            # Try block for checking only whole numbers are entered
            try:
                number = int(user_input)
            except ValueError:
                user_input = 'blank space' if user_input.strip() == '' else user_input
                print(f'{user_input} character is not allowed. Only whole number can be entered.')
 
The final version. Could be made better. some repetitive code needs replaced with functions.

Python:
# Do the imports
from pandas import DataFrame as df
from tabulate import tabulate as tb
from random import randint

import os

def clear():
    os.system('cls' if os.name == 'nt' else 'clear')

def random_number():
    return randint(1, 20)

# Create custom exception for numbers out of range
class InvalidNumber(Exception):
    '''This is an eception for numbers out of range'''
    pass



# Create Player class
class Player:
    '''
        Player class contains a name and scores for win/loose/tie
    '''
    def __init__(self, name):
        self.stats = {
            'name': name.title(),
            'wins': 0,
            'losses': 0,
            'ties': 0,
            'round': 0
        }

# Create winner class
class Winner:
    '''
        Winner class does our comparison to see who wins
    '''
    def __init__(self, number):
        self.number = number

    def __lt__(self, other):
        return self.number < other.number
    
    def __gt__(self, other):
        return self.number > other.number
    
    def __eq__(self, other):
        return self.number == other.number
    
if __name__ == '__main__':

    # Using while loop to get a player name and some error checking
    while True:
        clear()
        print('Enter player name:')
        name = input('>> ')

        # If statement to make sure only letters are used for name
        # Sets up our player and computer player
        # Else is some basic error checking
        if name.strip().isalpha():
            player = Player(name)
            player2 = Player('Computer')
            break
        else:
            print('You must enter a name.\nNames can only contain letters.')
    
    # Start the game loop
    clear()
    while True:
        # A way to exit the game
        print('Enter a number from 1 to 20. Enter \'q\' to quit')
        data = [player.stats, player2.stats]

        # Print out player and computer player data
        print(tb(df(data), tablefmt='grid', headers=[dat.title() for dat in data[0].keys()], showindex=False, numalign='center'))
        
        # Prompt for getting user input
        user_input = input('>> ').lower()

        # q was entered exit the game
        if user_input == 'q':
            clear()
            print('Goodbye!')
            break

        # Play the game
        else:
            clear()
            # Try block for checking only whole numbers are entered
            try:
                number = int(user_input)

                # Check if number is out of range. If it is throw exception
                if number < 1 or number > 20:
                    raise InvalidNumber
                
            except ValueError:
                user_input = 'blank space' if user_input.strip() == '' else user_input
                print(f'{user_input} character is not allowed. Only whole number can be entered.')

            except InvalidNumber:
                print('Error! Number out of range.')
                print('Number can only be from 1 - 20')
                input('Press enter to continue')

            # Everything checks, do comparison, add 1 to appropriate field for players
            else:
                # Generate a random number from 1 - 20 for the computer
                randnum = random_number()
                if Winner(int(user_input)) > Winner(randnum):
                    print(f'{player.stats["name"]} wins')
                    player.stats['wins'] += 1
                    player2.stats['losses'] += 1

                if Winner(int(user_input)) < Winner(randnum):
                    print(f'{player2.stats["name"]} wins')
                    player2.stats['wins'] += 1
                    player.stats['losses'] += 1

                if Winner(int(user_input)) == Winner(randnum):
                    print(f'Tie Game! {player.stats["name"]} and {player2.stats["name"]} have the same number')
                    player.stats['ties'] += 1
                    player2.stats['ties'] += 1

                player.stats['round'] += 1
                player2.stats['round'] += 1

                # Final round has been played, display a message and the table, exit game
                if player.stats['round'] == 3:
                    if Winner(player.stats['wins']) > Winner(player2.stats['wins']):
                        final = f"{player.stats['name']} is the grand winner!"
                    elif Winner(player.stats['wins']) < Winner(player2.stats['wins']):
                        final = f"{player2.stats['name']} is the grand winner!"
                    else:
                        final = 'Both players tied!'
                    print(final)
                    print(tb(df(data), tablefmt='grid', headers=[dat.title() for dat in data[0].keys()], showindex=False, numalign='center'))
                    break
 
My original post description has the purpose. Started as a number guessing but changed to a hi low game. Just trying to see if anyone wants to add or improve the game. There is no real purpose.
 
lovely_loveseat_description = "Lovely Loveseat. Tufted polyester blend on wood. 32 inches high x 40 inches wide x 30 inches deep. Red or white."
lovely_loveseat_price = 254.00
stylish_settee_description = "Stylish Settee. Faux leather on birch. 29.50 inches high x 54.75 inches wide x 28 inches deep. Black."
stylish_settee_price = 180.50
luxurious_lamp_description = "Luxurious Lamp. Glass and iron. 36 inches tall. Brown with cream shade."
luxurious_lamp_price = 52.15
sales_tax = .088
customer_one_total = 0
customer_one_itemization = ""
customer_one_total += lovely_loveseat_price
customer_one_itemization += lovely_loveseat_description
customer_one_total += luxurious_lamp_price
customer_one_itemization += luxurious_lamp_description
customer_one_tax = customer_one_total * sales_tax
customer_one_total += customer_one_tax
print("Customer One Items:")
print(customer_one_itemization)
print("Customer One Total:")
print(customer_one_total)
customer_two_total = 0
customer_two_itemization = ""
customer_two_total += stylish_settee_price
customer_two_itemization += stylish_settee_description
customer_two_total += luxurious_lamp_price
customer_two_itemization += luxurious_lamp_description
customer_two_tax = customer_two_total * sales_tax
customer_two_total += customer_two_tax
print("Customer Two Items:")
print(customer_two_itemization)
print("Customer Two Total:")
print(customer_two_total)





can some look at the above coding and tell me where the error is


thanks
 
Please use proper tags when posting. In my opinion you would be better off using classes for your project.
Here is a quick example of one way doing it

Python:
customers = []

class Store:
    sales_tax = 0.088

    def __init__(self):
        self.items = {}

    def add_item(self, item, price):
        self.items[item] = float(price)

    def add_tax(self):
        tax = sum(self.items.values()) * Store.sales_tax
        return round(tax, 2)


    def checkout(self):
        total = round(sum(self.items.values()) + self.add_tax(), 2)
        return total



customer1 = Store()
customer1.add_item('lamp', 19)
customer1.add_item('couch', 128.25)

customers.append(customer1)

customer2 = Store()
customer2.add_item('carpet', 85.00)
customer2.add_item('tv', 899.99)

customers.append(customer2)

for i, customer in enumerate(customers):
    print(f'Customer {i+1}')
    for item, price in customer.items.items():
        print(f'{item}: ${round(price, 2):.2f}')
    print(f'Tax: ${customer.add_tax()}')
    print(f'Total: ${round(customer.checkout(), 2):.2f}')
    print()

Output

Code:
Customer 1
lamp: $19.00 
couch: $128.25
Tax: $12.96   
Total: $160.21

Customer 2   
carpet: $85.00
tv: $899.99   
Tax: $86.68   
Total: $1071.67
 
My advice would be to buy a book. Doesn't have to be an expensive book. Learn all the basic syntax such as print, how to define variables, basic functions.
Once you get a understanding then move on how to create functions, classes, and many other aspects of the language.

There are many online tutorials for learning python. Once you get an understanding try doing projects. Start out small and work your way up. There are many forms to get help from if you get stuck on something.
 
Except for syntax errors, what the error is depends on what you want the program to do. What do you want for your output? If you are getting an error, what is the error message and what line is causing it?
 

New Threads

Latest posts

Buy us a coffee!

Back
Top Bottom