Syntax error in print

Asked

Viewed 108 times

-3

code:

# -*- coding: utf-8 -*-
import MySQLdb

db = MySQLdb.connect(host="xxx.xxx.x.xx", user="xxxxx", passwd="xxxxxxxx", db="xxxxxxx")


cursor = db.cursor()

cursor.execute("SELECT Dias, HoraConsulta, HoraSaida, nome, Consulta, centrodb.LocalConsulta.Descricao, Contato FROM centrodb.RegistoConsultas LEFT OUTER JOIN centrodb.LocalConsulta ON centrodb.LocalConsulta.Id = centrodb.RegistoConsultas.`Local` LEFT OUTER JOIN centrodb.utentes ON centrodb.utentes.codigoutente = centrodb.RegistoConsultas.Utente LEFT OUTER JOIN centrodb.DiasSemana ON centrodb.DiasSemana.Id = centrodb.RegistoConsultas.DiaSemana")

myresult = cursor.fetchall()

for linha in myresult:
                dia = linha['Dias']
                hora = linha['HoraConsulta']
                saida = linha['HoraSaida']
                utente = linha['nome']
                consulta = linha['Consulta']
                local = linha['Descricao']
                contato =linha['Contato']

print​(​"Dia:", dia)
print​(​"Hora Consulta:", hora)
print​(​"Hora Saída:", saida)
print​(​"Utente:", utente)
print​(​"Consulta:", consulta)
print​(​"Local:", local)
print​(​"Contato:", contato)

The syntax error is in the first line of the print. In the terminal the error is:

Syntaxerror: invalid syntax

what will be shown in the prints:

  • Day: Wednesday
  • time: 11:00:00
  • Exit: 10:15:00
  • user: xxxxxxxxxx
  • consultation: Dentist
  • Location: Hospital São João
  • contact: xxxxxxx

Let me just show you why it’s not a query problem:

# -*- coding: utf-8 -*-
    import MySQLdb

db = MySQLdb.connect(host="xxx.xxx.x.xx", user="xxxxx", passwd="xxxxxxxx", db="xxxxxxx")


cursor = db.cursor()

cursor.execute("SELECT Dias, HoraConsulta, HoraSaida, nome, Consulta, centrodb.LocalConsulta.Descricao, Contato FROM centrodb.RegistoConsultas LEFT OUTER JOIN centrodb.LocalConsulta ON centrodb.LocalConsulta.Id = centrodb.RegistoConsultas.`Local` LEFT OUTER JOIN centrodb.utentes ON centrodb.utentes.codigoutente = centrodb.RegistoConsultas.Utente LEFT OUTER JOIN centrodb.DiasSemana ON centrodb.DiasSemana.Id = centrodb.RegistoConsultas.DiaSemana")

myresult = cursor.fetchall()

print(myresult)

Thus prints the existing result in the table

  • Shouldn’t these prints be inside the loop? And the indentation remains strange.

  • @Anderson Carlos Woss, isn’t this loop what I do before the print? Is the indentation you refer to in the print? I’m starting in python, but it’s hard to ask for help because they keep putting negative votes on questions. I think there is no common sense. The question is not explicit?

  • It’s not. Usually in Python you only use 4 recoil spaces, you used 16 inside the loop, being an indication that this could be wrong in your code. Amen that indentation is essential in Python. Currently the prints are out of the loop, so this would be iterating over the results, set variables and doing nothing with them, which makes no sense. You need to ensure that the code in the question is exactly like the original and preferably make a [mcve].

  • For example, you cite that the error is on line 22, but your code only has 16 lines. We have no way of knowing where you found the error. Post the full code in the question, along with the full error message.

  • @Anderson Carlos Woss already put all the code, and the error information in the terminal is just that.

  • Wouldn’t that be the part? " centrodb.LocalConsulta.Id = centrodb.Registoqueries.Local"

  • @Victor Laio no, that part of the code is correct

  • So are you sure he was able to successfully connect in the BD? If you change the query to a simple select * from it will run?

  • If you do not find records in the database you will not enter the loop and do not define the variables. In this case, what should be shown in the prints?

  • If you take it all down, go all the way and put print(myresult) it prints the only row that exists in the database table, but if you do the for, define variables and then do print each of the variables, in the first line of the print of the first variable gives syntax error, which says invalid syntax

  • @Anderson Carlos Woss edited the question with what should be shown in the prints

  • 1

    (personal ,when so please direct AP to copy and paste the complete error message. It would bring the error row and column in that case)

Show 7 more comments

1 answer

2


Use a text editor suitable for programming

When copying your code and editing it to the example below, I discovered that there are invisible, non-printable characters between the ( and the ") Checking here, I saw that it’s the caracer \u200b with the name "ZERO WIDTH SPACE". That is, your text editor has put a crazy unprintable and invisible character in random positions in your code.

I was finishing my initial answer - and I give tips about the editor. But I thought you had used the "Notepad" which is already pretty bad - word processors, like Word, Openoffice, Wordpad, are most likely what you used out there -these tools are utterly inappropriate to edit code. There are hundreds of programming editors, dozens of very good quality and free, including one that comes installed with Python itself.

original response

Apart from what was said in the comments - the syntax of this script seems to be correct, and it would work in both Python 2 and Python 3

BUT - if you are saving the file with the default Windows encoding - which is Latin-1 (also known as cp-1252), because of the first line of the file: # -*- coding: utf-8 -*- which makes Python read the file as utf-8, it will give syntax error on the line print​(​"Hora Saída:", saida) - due to the accentuated character.

The actual encoding of the file is done by the editor that you use to edit the program. It should have the option to select the encoding. Without it, the accentuated character í will be written to your file . py as a byte which is invalid in utf-8.

It would help if you paste the entire error instead of just the first word of the error message. (if so, it will say that it is a "Unicode Decode error")

You don’t mention the Python version - I hope it’s Python 3- it doesn’t make sense to work with Python 2 today on new projects. You can simply remove the first line with the encoding indication - but look for saving your file as utf-8 the same way. Tip: the "Notepad" that comes with Windows is not a tool in which it is possible to write Python code - besides the coding problem, it does not have the automatic identation feature.

Along with the installation of Python in Windows is installed the idle - is an interactive and simple IDE environment, however quite complete, which will work well for this.

In addition to the question of encoding and using Python 3: recoding for indentation in Python is 4 spaces - the syntax of the language leaves free how much You use identation, provided that in each block it is maintained - so there is no error with its identation of more than 10 spaces - but this type of identment does not have any advantage neither theoretical nor practical, either to write, to read, or to maintain the code. (but it’s a clue that you must have used a text editor with no automatic indentation - since they use 4, at most 8, spaces by default, and had to be placing spaces manually on each line)

And finally, when you pass the syntax error, you’ll probably want to put the "print" all inside the loop for to print all records and not just the last.

In fact, there is no need to make that block of assigning variables - the values are as usable directly from within the dictionary, as from "own" variables for each - in this case, you are only typing more.

What’s more, the strisn in Python has a method format to which you can pass a direct dictionary - this makes it possible for you to write your formatting directly in a single print - and pass the data at once. You can use strigns delimietation with three quotes """ to have more than one line inside the string to be printed. (note that the .format is string, not print)

from textwrap import dedent

for linha in myresult:
    print​(dedent("""​
    Dia: {Dias}
    Hora Consulta: {HoraConsulta}
    Hora Saída: {HoraSaida}
    ....
    """.format(**linha)

How to check your crazy Python characters:

Python itself can be used to find invisible and control characters like the one in the above code. (It will depend on the capabilities of copying and pasting these characters on your system and your terminal - Windows is not the best tool). But if in addition to seeing the codes you want to see the Unicode name of the characters you can do so - the text with the line I want to analyze I copied and pasted directly from your code above:

In [100]: for char in """print("Dia:", dia)""": 
     ...:     print(char, hex(ord(char)), unicodedata.name(char)) 
     ...:                                                                                                
p 0x70 LATIN SMALL LETTER P
r 0x72 LATIN SMALL LETTER R
i 0x69 LATIN SMALL LETTER I
n 0x6e LATIN SMALL LETTER N
t 0x74 LATIN SMALL LETTER T
 0x200b ZERO WIDTH SPACE
( 0x28 LEFT PARENTHESIS
 0x200b ZERO WIDTH SPACE
" 0x22 QUOTATION MARK
D 0x44 LATIN CAPITAL LETTER D
i 0x69 LATIN SMALL LETTER I
a 0x61 LATIN SMALL LETTER A
: 0x3a COLON
" 0x22 QUOTATION MARK
, 0x2c COMMA
  0x20 SPACE
d 0x64 LATIN SMALL LETTER D
i 0x69 LATIN SMALL LETTER I
a 0x61 LATIN SMALL LETTER A
) 0x29 RIGHT PARENTHESIS

Browser other questions tagged

You are not signed in. Login or sign up in order to post.