mimimi SNIPE
mimimi SNIPE

Reputation: 23

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.

Upvotes: 0

Views: 100

Answers (2)

Prune
Prune

Reputation: 77837

You start by reading location 1, which is the decimal point. Your program advances to the next digit, 1. You never change digit after that. pi.seek() does not change digit; you have to read the character there and assign the value again.

Upvotes: 1

finefoot
finefoot

Reputation: 11234

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.

Upvotes: 0

Related Questions