Invalid Syntax error?

Question:

I’m new at Python and tried writing a basic script.
I’m trying to print out all the letters of the alphabet, and I keep getting Invalid Syntax.

letter = ord('a')
while letter != ord('z')
    print(chr(letter))
    letter = letter + 1

Here’s the first error log:

while letter != ord('z')
                       ^
SyntaxError: invalid syntax

It seemed that Python doesn’t like closing parentheses, so when I removed it, it gave me this:

print(chr(letter))
    ^
SyntaxError: invalid syntax

I couldn’t do anything to fix this one, so I tried removing the line entirely. It then gave me this:

letter = letter + 1
     ^
SyntaxError: invalid syntax

I have no idea what I’m doing at this point, and only after deleting the entire script altogether was Python finally happy.
How do I fix the script so it doesn’t get any more Invalid Syntaxes?

Asked By: WaterTipper

||

Answers:

Missing the colon in end while loop.

 letter = ord('a')
 while letter != ord('z'):
       print(chr(letter)) 
       letter += 1
Answered By: stderr

You want a colon at the end of your while loop, to let Python know it’s a block.

while letter != ord('z'):
    <rest of your code here>

Also, right now you seem to have the start of the while loop indented and none of the rest, when you want the opposite: all the code to be run in the while loop should be indented, but the header shouldn’t be.

As a side note, your ord and chr strategy is totally valid but probably more complicated than necessary. In Python, a for loop can iterate through a string as well as a range of numbers. So you can say

for character in "abcdefghijklmnopqrstuvwxyz":
    print(character)

A shorter way to get that alphabet string is

import string
string.lowercase
Answered By: Eli Rose

I’m new at Python and tried writing a basic script.

x = input("ecrit ton premier nomber :")
z = input("ecrit ton Processus :")
y = input("ecrit ton deuxieme nombre :")
if z == + :
    print(x+y)

Here’s the error log:
if z == + :
^
SyntaxError: invalid syntax

Answered By: KIRA
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.