#๐Ÿ”’ Issue with my main function in my number guessing game

72 messages ยท Page 1 of 1 (latest)

limber narwhalBOT
#

@crimson wagon

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.

thick moth
#

where it says that, give it the indent (make space from the left) to where its complaining about.

misty marten
#

if you share the code people will easily help

crimson wagon
#

How do you share the code in the proper format on here again?

#

import random

#Create Global variables

game_history_names = []
game_history_guesses = []

#Create a function to STORE THE NAME AND GUESS IN THE HISTORY.TXT FILE

def store_name(name, guesses):
with open("history.txt", "a") as file:
file.write(f"{name},{guesses}\n")

#Create a function to REPEAT THE GAME

def repeat_game():
choice = input("Do you want to play again? (y/n): ")
return choice.lower() == "y"

#Create a function to GET THE PLAYER NAME

name = input("Enter your name: ")
return name

#Create a function to DISPLAY SCORES

def display_scores():
print("Game History:")
print("Name\t\tGuesses")
for i in range(len(game_history_names)):
print(f"{game_history_names[i]}\t\t{game_history_guesses[i]}")

#Create a function to READ THE HISTORY FROM THE HISTORY.TXT FILE

def read_history():
global game_history_names, game_history_guesses
try:
with open("history.txt", "r") as file:
for line in file:
name, guesses = line.strip().split(',')
game_history_names.append(name)
game_history_guesses.append(int(guesses))

#Create main function to EXECUTE THE PROGRAM

def main():
read_history()
player_name = get_player_name()
play_again = True
while play_again:
number_to_guess = random.randint(1, 100)
guesses = 0
while True:
guess = int(input(f"Guess {guesses + 1}: Enter a number between 1 and 100: "))
guesses += 1
if guess < number_guess:
print("Your guess is too low.")
elif guess > number_guess:
print("Your guess is too high.")
else:
print("Congratulations โ€“ You are Correct!")
store_name(player_name, guesses)
break
play_again = repeat_game()
display_scores()

#Call the main function

if name == "main":
main()

thick moth
limber narwhalBOT
#
Formatting code on Discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

last robin
#
#Create a function to GET THE PLAYER NAME

name = input("Enter your name: ")
return name

This probably needs to be in a function

thick moth
#

@crimson wagon can you also share the traceback messages?

#

!traceback looks like this

limber narwhalBOT
#
Traceback

Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.

A full traceback could look like:

Traceback (most recent call last):
  File "my_file.py", line 5, in <module>
    add_three("6")
  File "my_file.py", line 2, in add_three
    a = num + 3
        ~~~~^~~
TypeError: can only concatenate str (not "int") to str

If the traceback is long, use our pastebin.

crimson wagon
#

'''py
import random

#Create Global variables

game_history_names = []
game_history_guesses = []

#Create a function to STORE THE NAME AND GUESS IN THE HISTORY.TXT FILE

def store_name(name, guesses):
with open("history.txt", "a") as file:
file.write(f"{name},{guesses}\n")

#Create a function to REPEAT THE GAME

def repeat_game():
choice = input("Do you want to play again? (y/n): ")
return choice.lower() == "y"

#Create a function to GET THE PLAYER NAME

name = input("Enter your name: ")
return name

#Create a function to DISPLAY SCORES

def display_scores():
print("Game History:")
print("Name\t\tGuesses")
for i in range(len(game_history_names)):
print(f"{game_history_names[i]}\t\t{game_history_guesses[i]}")

#Create a function to READ THE HISTORY FROM THE HISTORY.TXT FILE

def read_history():
global game_history_names, game_history_guesses
try:
with open("history.txt", "r") as file:
for line in file:
name, guesses = line.strip().split(',')
game_history_names.append(name)
game_history_guesses.append(int(guesses))

#Create main function to EXECUTE THE PROGRAM

def main():
read_history()
player_name = get_player_name()
play_again = True
while play_again:
number_to_guess = random.randint(1, 100)
guesses = 0
while True:
guess = int(input(f"Guess {guesses + 1}: Enter a number between 1 and 100: "))
guesses += 1
if guess < number_guess:
print("Your guess is too low.")
elif guess > number_guess:
print("Your guess is too high.")
else:
print("Congratulations โ€“ You are Correct!")
store_name(player_name, guesses)
break
play_again = repeat_game()
display_scores()

#Call the main function

if name == "main":
main()
'''

limber narwhalBOT
#

Hey @crimson wagon!

It looks like you are trying to paste code into this channel.

You seem to be using the wrong symbols to indicate where the code block should start. The correct symbols would be ```, not '''.

Here is an example of how it should look:
```py
print('Hello, world!')
```

This will result in the following:

print('Hello, world!')```
You can **edit your original message** to correct your code block.
thick moth
#

It looks like this ๐Ÿ‘‰ `

crimson wagon
#

oh backsticks! right!

#
import random

#Create Global variables

game_history_names = []
game_history_guesses = []

#Create a function to STORE THE NAME AND GUESS IN THE HISTORY.TXT FILE

def store_name(name, guesses):
    with open("history.txt", "a") as file:
        file.write(f"{name},{guesses}\n")

#Create a function to REPEAT THE GAME

def repeat_game():
    choice = input("Do you want to play again? (y/n): ")
    return choice.lower() == "y"

#Create a function to GET THE PLAYER NAME

name = input("Enter your name: ")
return name
   
#Create a function to DISPLAY SCORES

def display_scores():
    print("Game History:")
    print("Name\t\tGuesses")
    for i in range(len(game_history_names)):
        print(f"{game_history_names[i]}\t\t{game_history_guesses[i]}")

#Create a function to READ THE HISTORY FROM THE HISTORY.TXT FILE

def read_history():
    global game_history_names, game_history_guesses
    try:
        with open("history.txt", "r") as file:
            for line in file:
                name, guesses = line.strip().split(',')
                game_history_names.append(name)
                game_history_guesses.append(int(guesses))

#Create main function to EXECUTE THE PROGRAM

def main():
    read_history()  
    player_name = get_player_name()  
    play_again = True
    while play_again:
        number_to_guess = random.randint(1, 100)
        guesses = 0
        while True:
            guess = int(input(f"Guess {guesses + 1}: Enter a number between 1 and 100: "))
            guesses += 1
            if guess < number_guess:
                print("Your guess is too low.")
            elif guess > number_guess:
                print("Your guess is too high.")
            else:
                print("Congratulations โ€“ You are Correct!")
                store_name(player_name, guesses)
                break
        play_again = repeat_game()
        display_scores()

#Call the main function

if __name__ == "__main__":
    main()
thick moth
#

much better

last robin
thick moth
last robin
#

I already pointed out the error

crimson wagon
#

Expected except or finally block after def(main): is the first issue

last robin
#

yeah there's that too

#

you have a try in def read_history but no except or finally

#

you need to fix this though

#Create a function to GET THE PLAYER NAME

name = input("Enter your name: ")
return name
crimson wagon
#

What about that line needs to be fixed?

thick moth
last robin
#

You can't have a return that's not in a function

#

what's it returning to?

crimson wagon
#

oh duh lol just fixed that

#

Thanks for that

thick moth
#

and the except?

crimson wagon
#

It's still right after my main function

thick moth
#

no

#

its in your read_history function

last robin
#

If you share the entire traceback we can help you interpret it

thick moth
#

You have to add except: and then do something if it hits the exception

crimson wagon
#

It won't even let me run it

#

Oh got you one second

thick moth
#

like print the error message

last robin
#

I guess you should also answer why is there a try there in the first place?

crimson wagon
#

Alright. Here is the traceback now

#

Traceback (most recent call last):
File "C:/Users/ZARD/Desktop/GuessGame.py", line 81, in <module>
main()
File "C:/Users/ZARD/Desktop/GuessGame.py", line 58, in main
read_history()
File "C:/Users/ZARD/Desktop/GuessGame.py", line 49, in read_history
name, guesses = line.strip().split(',')
ValueError: not enough values to unpack (expected 2, got 1)

thick moth
#

!e

try:
    x = "Bob"
    x = x + 1.5
    print(x)
except:
    print("Invalid value at x")

example of how the try except stuff works

limber narwhalBOT
#

@thick moth :white_check_mark: Your 3.12 eval job has completed with return code 0.

Invalid value at x
crimson wagon
#

Ya I fixed that

thick moth
#

In your history.txt file, it grabbed the line out of it but it didn't have enough values to split on , to assign to name and guesses

#

What happens if history.txt is empty?

#

!paste if the file is too long

limber narwhalBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

thick moth
#

Use a pastebin โ˜๏ธ

crimson wagon
#

Ken
4
Paul
7

#

This is all that's in the history.txt file currently

thick moth
#

are those in separate lines?

crimson wagon
#

Yes

thick moth
#

Where's the ,?

crimson wagon
#

What do you mean?

thick moth
#

The code is expecting to split on ,

last robin
thick moth
#

Like Ken,4

#

Then it would split that as name for Ken and guesses for 4

crimson wagon
#

gotcha

#

I don't want to manipulate the file. How would I edit the code to format the current file layout?

vapid garden
#

Did you write this code?

#

read_history indicates you are reading from a file with comma separated values

thick moth
crimson wagon
#

It's crazy because I have a whole pdf showing how it should look in that line and it matches almost perfectly

#

I'm going to go back in and compare real quick. Thanks for the quick help!

limber narwhalBOT
#
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.

#

๐Ÿ”’ Issue with my main function in my number guessing game