#๐ Issue with my main function in my number guessing game
72 messages ยท Page 1 of 1 (latest)
@crimson wagon
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.
where it says that, give it the indent (make space from the left) to where its complaining about.
if you share the code people will easily help
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()
!code format instructions below
#Create a function to GET THE PLAYER NAME
name = input("Enter your name: ")
return name
This probably needs to be in a function
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.
'''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()
'''
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.
backticks are located left of your 1 key and below your ESC key.
It looks like this ๐ `
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()
much better
@crimson wagon this is probably the issue
@crimson wagon traceback messages if you can please
I already pointed out the error
Expected except or finally block after def(main): is the first issue
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
What about that line needs to be fixed?
its not a function
and the except?
It's still right after my main function
If you share the entire traceback we can help you interpret it
You have to add except: and then do something if it hits the exception
like print the error message
I guess you should also answer why is there a try there in the first place?
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)
!e
try:
x = "Bob"
x = x + 1.5
print(x)
except:
print("Invalid value at x")
example of how the try except stuff works
@thick moth :white_check_mark: Your 3.12 eval job has completed with return code 0.
Invalid value at x
Ya I fixed that
What is the value for line?
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
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.
Use a pastebin โ๏ธ
are those in separate lines?
Yes
Where's the ,?
What do you mean?
The code is expecting to split on ,
Did you write this code or did ChatGPT?
gotcha
I don't want to manipulate the file. How would I edit the code to format the current file layout?
Did you write this code?
read_history indicates you are reading from a file with comma separated values
But this function does it in a different format?
#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")
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!
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