Home > database >  Python syntax error when using strings in variables
Python syntax error when using strings in variables

Time:10-16

Code

import random
    
print("Witaj w grze papier, kamień i nożyczki")
    
player_1 = input("Wpisz nazwę gracza nr 1: ")
player_2 = input("Wpisz nazwę gracza nr 2: ")
choice_1 = (input("Wpisz wybór %s:",% (player_1)))

Problem

This code seems to be causing a syntax error and i dont know why

choice_1 = (input("Wpisz wybór %s:",% (player_1)))
                                            ^
SyntaxError: invalid syntax```

CodePudding user response:

Solution

Remove the comma after the string choice_1 = (input("Wpisz wybór %s:" % (player_1)))

Other cleaner way (imo)

I would recommend you format the string differently, using the format() function.

choice_1 = input("Wpisz wybór {}:".format(player_1))

CodePudding user response:

remove the comma from line 13

choice_1 = (input("Wpisz wybór %s:" % (player_1)))

CodePudding user response:

If you are using Python 3.6 or a later version, I'd recommend using f-string (PEP 498 – Literal String Interpolation). It would be easy to concatenate strings in Python.

choice_1 = (input(f"Wpisz wybór {player_1}:"))

Here are a few alternatives ways that would do the same,

# Concatenating With the   Operator
choice_1 = (input("Wpisz wybór"   player_1   ":"))

# String Formatting with the % Operator
choice_1 = (input("Wpisz wybór %s:" % (player_1)))

# String Formatting with the { } Operators with str.format()
choice_1 = (input("Wpisz wybór {}:".format(player_1)))
choice_1 = (input("Wpisz wybór {0}:".format(player_1)))
choice_1 = (input("Wpisz wybór {some_name}:".format(some_name=player_1)))

You can find this answer to learn more ways to concatenate strings in Python.

  • Related