WaterTipper
WaterTipper

Reputation: 21

Invalid Syntax error?

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?

Upvotes: 0

Views: 3682

Answers (3)

BenDeagle
BenDeagle

Reputation: 21

There's a syntax error because the + sign is counted as a variable when you leave it by itself. It should be like this

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

x and y are also treated as strings so it won't actually add them together, it'll just put them next to each other. Example: if x is 5 and y is 6, the output will be 56 and not 11. This can be fixed by declaring the input as an integer.

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

Upvotes: -1

Eli Rose
Eli Rose

Reputation: 6998

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

Upvotes: 3

stderr
stderr

Reputation: 387

Missing the colon in end while loop.

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

Upvotes: 2

Related Questions