Python - formatting problem with print()-function - Why does formatting (autopep8) pushes my print statement after `print(` to the next line?

56 views Asked by At

I noticed that parts of my last print()-function statement got pushed down when I formatted it with autopep8 in VSC and I don't understand why. This only occurs, if I have the temp foor loop variable {guesses_Taken} inside the String.

if guess == secret_number:
    print(
        f'Good job, {name}! You guessed my number in {guesses_taken} guesses taken')

Without the variable, it's formatting like usual:

print(f'Good job, {name}! You guessed my number in  guesses taken')

I tried to print a temp. for loop variable in another file to reproduce the problem, but here it's working properly.

numbers = 23
for i in range(3):
    x = i
if x == 2:
    print(f'Number {i} and Number {numbers}')

Original Code with formatting problem in last line

for guesses_taken in range(1, 7):
    print('Take a guess.')
    guess = int(input())
    if guess < secret_number:
        print('Your guess is too low.')
    elif guess > secret_number:
        print('Your guess is too high')
    else:
        break  # This condition is for the correct guess
if guess == secret_number:
    print(
        f'Good job, {name}! You guessed my number in {guesses_taken} guesses taken')

Is it a bug or can I improve something? The program itself is working properly.

Thank you in advance!

Full source code line #21: https://pastebin.com/D66mDm5K VSC Version: 1.72.1

2

There are 2 answers

0
DeepSpace On BEST ANSWER

The addition to the string pushes the length of the line above PEP8's suggested 80 characters:

print(len("print(f'Good job, {name}! You guessed my number in  guesses taken')"))
print(len("print(f'Good job, {name}! You guessed my number in {guesses_taken} guesses taken')"))

outputs

67
82

autopep8's solution is to break the line after print(.

You can use the --max-line-length [length] CLI argument to configure a different value.

0
Florent Monin On

PEP8 specificies the line length has to be maximum 79, so the editor is refactoring your code to try to respect that rule.

One way to make your code look cleaner here, would be:

if guess == secret_number:
    print(
        f"Good job, {name}! You guessed my number in " 
        f"{guesses_taken} guesses taken"
    )

for instance