Search code examples
pythonloopsfile-read

How to read single characters in a file? Python


Problem: I have to create a program, where the user has to guess a digit after another in pi. If he guesses right. It prints correct. If it's wrong incorrect. Also it counts the r/w guesses.

The problem I have, is that my code is not jumping to the next digit to guess. The user is always guessing the same digit.

Setup:

pi = open("pi.txt", "r")
name = input("Enter username: ")
print("Hey", name)
seed = len(name)
pi.seek(seed)
digit = pi.read(1)
#guess = input("enter a single digit guess or 'q' to quit: ")
correct_counter = 0
wrong_counter = 0

Loop:

while True:
    guess = input("enter a single digit guess or 'q' to quit: ")
    if guess.isdigit():
        if digit == ".":
            digit = pi.read(1)
        elif digit == "\n":
            seed += 1
            pi.seek(seed)
        else:
            if guess == digit:
                print("correct")
                correct_counter += 1
            else:
                print("incorrect")
                wrong_counter += 1
    else:
        break

print("correct answers: ", correct_counter)
print("incorrect answers: ", wrong_counter)

pi.close()

Output:

enter a single digit guess or 'q' to quit: 1
correct
enter a single digit guess or 'q' to quit: 1
correct
enter a single digit guess or 'q' to quit: 1
correct
enter a single digit guess or 'q' to quit: 1
correct

I am very new to coding and this is my first question. So please give me feedback to improve.


Solution

  • Looking at your code, there are only two lines with pi.read(1). Once initially (outside the loop) and then in case of ".". However, you need to read a new character each time the user guessed correctly.