Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

f-string not working in Jupyter not working

I can run my code in pythontutor and PyCharm and it works. But, when I try to run my code in Jupyter Notebook for my class, I keep getting a SyntaxError.

I have research the web, and the only thing I could find had to do with a CodeMirror issue. Not sure what that is. What am I doing wrong with the f-string?

def list_o_matic(blank):
    if new_animal == "":     #check to see if nothing was entered if so then pop last animal  in list
        pop = animal.pop()
        msg_pop = f'{pop} popped from list' # popped for list
        return msg_pop

    else:
        if new_animal in animal:     #check to see if already have animal if yes remove animal from list
            remove = animal.remove(new_animal)
            msg_remove =  f'1 instance of {new_animal} removed from list'
            return msg_remove

        else:
            animal.append(new_animal)      #check to see if animal is not in list if so append list to add animal
            msg_append = f'1 instance of {new_animal} appended to list'
            return msg_append

animal = ['cat','goat','cat']

while True:
    if len(animal) == 0:  #check if list is empty
        print("\nGoodbye!")
        break

    else:         # get animal input
        print("look at all the animals ",animal)
        new_animal = input("enter the name of an animal or quit: ").lower()

        if new_animal == "quit":   # quit entered print msg and leave
            print("\nGoodbye!")
            break

        else:
            print(list_o_matic(new_animal),"\n")

File "", line 6 msg_pop = f'{pop} popped from list' # popped for list ^ SyntaxError: invalid syntax

like image 846
Brian Price Avatar asked Oct 30 '25 16:10

Brian Price


2 Answers

Try changing

msg_pop = f{'pop'}

to

msg_pop = f'{pop}'

like image 127
Jack Fleeting Avatar answered Nov 01 '25 14:11

Jack Fleeting


The issue with the f-string is that the brackets must be inside the quotation marks. I.e. instead of f{'pop'} it should look like f'{pop}'.

This is because it evaluates pop inside of the string. But it looks like you got it right for all of the other f-strings so must've just been an oversight. Keep it up!

like image 28
Jonathan Porter Avatar answered Nov 01 '25 12:11

Jonathan Porter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!