I’m having this error:
File "zzz.py", line 70
else:
^
SyntaxError: invalid syntax
The line which causes the problem is marked with a comment in the code:
def FileParse(self, table_file):
vars={}
tf = open(table_file, 'r')
for line in tf:
if line.startswith("#") or line.strip() == "": pass
elif line.startswith("n_states:"):
self.n_states = str(line[9:].strip())
elif line.startswith("neighborhood:"):
self.neighborhood = str(line[13:].strip())
elif line.startswith("symmetries:"):
self.symmetries = str(line[11:].strip())
elif line.startswith("var "):
line = line[4:]
ent = line.replace('=',' ').\
replace('{',' ').\
replace(',',' ').\
replace(':',' ').\
replace('}',' ').\
replace('\n','').split()
vars[ent[0]] = []
for e in ent[1:]:
if e in vars: vars[ent[0]] += vars[e]
else:
vars[ent[0].append(int(e))]
else:
rule = line.strip().split(",")
for k in vars.keys():
if k in rule:
for i in vars[k]:
change = rule.replace(k, i)
change = [int(x) for x in change]
w.rules.append(Rule(change[:5],change[5])
else: # line which causes the problem
rule = [int(x) for x in rule]
w.rules.append(Rule(rule[:5],rule[5]))
tf.close()
self.parse_status "OK"
return w.rules
w.rules
is variable which is assigned to «World» class.
To be honest I have no idea why I get this. Before everything was fine and now that error shows up after adding some extra instructions in other indented blocks.
Any ideas?
Пролистайте в самый низ. Простите, что так много кода, я просто не понимаю где ошибка? Возле проблемного else я написал «Тут ошибка»
# -*- coding: utf-8 -*-
from playsound import playsound
import pyowm
import os
import pyttsx3
import subprocess
import time
import datetime
import random
import webbrowser
import speech_recognition as sr
from datetime import date
speak_engine = pyttsx3.init()
def speak(what):
print(what)
speak_engine.say( what )
speak_engine.runAndWait()
speak_engine.stop()
now = datetime.datetime.now()
file = open('names.txt', 'r')
string = file.read()
file.close()
file2 = open('password.txt', 'r')
string2 = file2.read()
file2.close()
if float(now.hour) > 16:
speak("Добрый вечер, " + str(string))
else:
speak("Добрый день, создатель" + (string))
speak("Говорите")
puti = {"командная строка": "C:/Users/Andrew/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/System Tools/Командная строка.lnk",
"иллюстратор": "D:/adobe Illustrator/Adobe Illustrator 2020/Support Files/Contents/Windows/Illustrator.exe",
"firefox": "C:/Program Files/Mozilla Firefox/firefox.exe",
"калькулятор": "C:/Windows/System32/calc.exe",
"total commander": "C:/Program Files (x86)/Total Commander/Totalcmd.exe",
"блокнот": "C:/Windows/System32/notepad.exe",
"редактор кода": "D:/Sublime Text 3/sublime_text.exe",
}
razgovori = {"хорошо": "Ага", "как тебя зовут": "Меня зовут Алиас", "как дела": "Нормально, я бы сказал даже хорошо", "привет": "Привет", "спасибо": "Пожалуйста", "смешно": "Согласен", "сколько тебе лет": "Дерево не тонет, рукописи не горят, технологии не стареют.", "у тебя есть девушка": "У меня запутаные отношения с командной строкой. Иногда, она не может найти мою директорию.", "у тебя есть жена": "У меня запутаные отношения с командной строкой. Иногда, она не может найти мою директорию.", "где ты живёшь": "Диск C, папка Users, папка Desktop, папка Andrew, папка Python, файл test.py. Приходите, может чайку попьем", "что ты думаешь о windows": "Типичная недо система. Мне больше нравится Linux", "ты знаешь что ты не можешь жить в линуксе": "Да, я это знаю... И меня очень растраивает этот факт : ("}
mat = {"ты тупой": "Вовсе нет, просто, незабывайте что я программа", "ты глупый": "Вовсе нет, просто, незабывайте что я программа", "я не хочу тебя слышать": "Простите меня, если вы больше не хотите разговаривать - скажите отключись"}
all_names_variants = ["измени моё имя", "поменяй моё имя", "измени имя", "поменяй имя"]
weather = ["погода", "какая погода", "покажи погоду", "тепмература", "какая температура", "покажи температуру"]
place = ["где я", "где я нахожусь", "покажи где я", "моё место местоположение", "покажи моё место местоположение", "покажи где я нахожусь"]
what_day = ["дата", "скажи дату", "скажи текущую дату", "какое число", "скажи число", "скажи текущее число"]
what_time = ["время", "час", "скажи время", "скажи час", "который час", "сколько времени"]
marsh = ["проложи маршрут", "сделай маршрут", "маршрут", "покажи маршрут"]
all_open_variants = ["открой", "запусти"]
music = ["включи музыку", "воспроизведи музыку", "запусти музыку"]
def shto():
try:
a = sr.Recognizer()
with sr.Microphone(device_index=1) as source:
audio = a.listen(source)
query = a.recognize_google(audio, language="ru-RU")
print(query.lower())
if query.lower() == "поменяй пароль":
file2 = open('password.txt', 'r')
string2 = file2.read()
file2.close()
if string2 == "tutnetparrrrrrola":
speak("У вас не установлен пароль")
speak("Установите пароль")
password()
if query.lower() in weather:
#city = input("Какой город? ")
speak("В каком городе вы хотите узнать погоду? ")
a = sr.Recognizer()
with sr.Microphone(device_index=1) as source:
audio = a.listen(source)
city = a.recognize_google(audio, language="ru-RU")
owm = pyowm.OWM('f5cb5ced678daf785ff5c62c5cba912c', language = "RU")
observation = owm.weather_at_place(city)
w = observation.get_weather()
temperature = w.get_temperature('celsius')['temp']
m = w.get_detailed_status()
speak("В городе " + city + " сейчас температура: " + str(temperature) + " по Цельсию")
speak("Также в указанном городе " + m)
shto()
if query.lower() in music:
print("Введите путь к музыке(например: C:/User/Andrew...) после чего ")
chooice_music = input("Введите путь к музыке(например: C:/User/Andrew...) после чего нажмите Ctrl + c ")
playsound(chooice_music)
shto()
if query.lower() in place:
webbrowser.open_new_tab("https://www.google.com/search?client=firefox-b-d&q=" + "моё местоположение")
shto()
if query.lower() in what_day:
today = date.today()
speak("Текущая дата: ")
print(today)
shto()
if query.lower() in all_names_variants:
input_new_name = input("Введите новое имя: ")
handle = open("names.txt", "w")
handle.write(input_new_name)
handle.close()
speak("Имя изменено")
shto()
if query.lower() in puti:
subprocess.call(puti[query.lower()])
speak("Запустил")
shto()
if query.lower() in razgovori:
speak(razgovori[query.lower()])
shto()
if query.lower() in mat:
speak(mat[query.lower()])
shto()
if query.lower() == "выключи компьютер":
speak("Выключаю...")
os.system("shutdown /p")
if query.lower() == "перезагрузи компьютер":
speak("Перезагружаю...")
os.system("shutdown /r")
if query.lower() in what_time:
speak("Сейчас " + str(now.hour) + ":" + str(now.minute))
shto()
if query.lower() == "выключись":
speak("Хорошо, отключаюсь, всего доброго!")
if query.lower() == "отключись":
speak("Хорошо, отключаюсь, всего доброго!")
if query.lower() == "пошути":
c = random.randint(1, 4)
if c == 1:
speak("Семья бомжей, часто сорилась, из-за какойто мелочи.")
shto()
if c == 2:
speak("-Милый ты любишь меня?")
speak("-Конечно!")
speak("-А умрешь за меня?")
speak("-Здрасте! А любить тебя кто будет?!")
shto()
if c == 3:
speak("Мои друзья — полицейские служили в милиции, потом в полиции, теперь их переводят в национальную гвардию... Чувствую, на пенсию они уйдут МУШКЕТЕРАМИ.")
shto()
if c == 4:
speak("Если в школах есть уроки труда, то должны быть и уроки отдыха.")
shto()
if query.lower() == "расскажи три закона робототехники":
speak("1. Робот не может причинить вред человеку или своим бездействием допустить, чтобы человеку был причинён вред.")
speak("2. Робот должен повиноваться всем приказам, которые даёт человек, кроме тех случаев, когда эти приказы противоречат Первому Закону.")
speak("3. Робот должен заботиться о своей безопасности в той мере, в которой это не противоречит Первому или Второму Законам.")
shto()
if query.lower() == "поиск":
print("Введите поисковой запрос: ")
a = sr.Recognizer()
with sr.Microphone(device_index=1) as source:
audio = a.listen(source)
search_google = a.recognize_google(audio, language="ru-RU")
print(search_google.lower())
webbrowser.open_new_tab("https://www.google.com/search?client=firefox-b-d&q=" + search_google)
shto()
if search_google == "отмена":
shto()
if query.lower() == "как меня зовут":
file = open('names.txt', 'r')
string = file.read()
file.close()
if string == "none":
new_name = input("Введите имя: ")
new_new_name = ("Вас зовут " + str(new_name))
speak(new_new_name)
handle = open("names.txt", "w")
handle.write(new_name)
handle.close()
shto()
else:
file = open('names.txt', 'r')
string = file.read()
file.close()
speak("Вас зовут " + string)
shto()
if query.lower() in marsh:
speak("Введите начальную точку: ")
aa = sr.Recognizer()
with sr.Microphone(device_index=1) as source:
audio = aa.listen(source)
point_a = aa.recognize_google(audio, language="ru-RU")
print(point_a.lower())
speak("Введите конечную точку: ")
aaa = sr.Recognizer()
with sr.Microphone(device_index=1) as source:
audio = aaa.listen(source)
point_b = aaa.recognize_google(audio, language="ru-RU")
print(point_b.lower())
webbrowser.open_new_tab('https://www.google.com.ua/maps/dir/' + point_a + '/' + point_b)
shto()
def password():
first_password = input("Введите пароль: ")
second_password = input("Повторите пароль: ")
if first_password == second_password:
speak("Пароль установлен")
file = open('password.txt', 'w')
string = file.write(second_password)
file.close()
shto()
else:
speak("Пароли несовпадают!")
password()
else: Тут ошибка
speak("Команда не распознана!")
shto()
except:
shto()
if string2 == "tutnetparrrrrrola":
shto()
else:
input("Введите пароль: ")
shto()

You can combine the else
statement with the elif
and if
statements in Python. But when running if...elif...else
statements in your code, you might get an error named SyntaxError: invalid syntax
in Python.
It mainly occurs when there is a wrong indentation in the code. This tutorial will teach you to fix SyntaxError: invalid syntax
in Python.
Fix the else
& elif
Statements SyntaxError
in Python
Indentation is the leading whitespace (spaces and tabs) in a code line in Python. Unlike other programming languages, indentation is very important in Python.
Python uses indentation to represent a block of code. When the indentation is not done properly, it will give you an error.
Let us see an example of else
and elif
statements.
Code Example:
num=25
guess=int(input("Guess the number:"))
if guess == num:
print("correct")
elif guess < num:
print("The number is greater.")
else:
print("The number is smaller.")
Error Output:
File "c:\Users\rhntm\myscript.py", line 5
elif guess < num:
^^^^
SyntaxError: invalid syntax
The above example raises an exception, SyntaxError
, because the indentation is not followed correctly in line 5. You must use the else
code block after the if
code block.
The elif
statement needs to be in line with the if
statement, as shown below.
Code Example:
num=25
guess=int(input("Guess the number:"))
if guess == num:
print("correct")
elif guess < num:
print("The number is greater.")
else:
print("The number is smaller.")
Output:
Guess the number:20
The number is greater.
Now, the code runs successfully.
The indentation is essential in Python for structuring the code block of a statement. The number of spaces in a group of statements must be equal to indicate a block of code.
The default indentation is 4 spaces in Python. It is up to you, but at least one space has to be used.
If there is a wrong indentation in the code, you will get an IndentationError
in Python. You can fix it by correcting the indent in your code.
Can someone explain why I am getting an invalid syntax error from Python’s interpreter while formulating this simple if/else
statement? I don’t add any tabs myself I simply type the text then press enter after typing. When I type an enter after «else:» I get the error. else
is highlighted by the interpreter. What’s wrong?
>>> if 3 > 0:
print("3 greater than 0")
else:
SyntaxError: invalid syntax
Tomerikoo
18.4k16 gold badges47 silver badges61 bronze badges
asked Jan 14, 2013 at 21:38
4
Python does not allow empty blocks, unlike many other languages (since it doesn’t use braces to indicate a block). The pass
keyword must be used any time you want to have an empty block (including in if/else statements and methods).
For example,
if 3 > 0:
print('3 greater then 0')
else:
pass
Or an empty method:
def doNothing():
pass
monsur
45.7k16 gold badges101 silver badges95 bronze badges
answered Jan 14, 2013 at 21:47
1
That’s because your else
part is empty and also not properly indented with the if
.
if 3 > 0:
print "voila"
else:
pass
In python pass
is equivalent to {}
used in other languages like C.
answered Jan 14, 2013 at 21:40
Ashwini ChaudharyAshwini Chaudhary
245k58 gold badges464 silver badges505 bronze badges
The else
block needs to be at the same indent level as the if
:
if 3 > 0:
print('3 greater then 0')
else:
print('3 less than or equal to 0')
answered Jan 14, 2013 at 21:41
VolatilityVolatility
31.3k10 gold badges80 silver badges89 bronze badges
0
The keyword else
has to be indented with respect to the if
statement respectively
e.g.
a = 2
if a == 2:
print "a=%d", % a
else:
print "mismatched"
icedwater
4,7013 gold badges35 silver badges50 bronze badges
answered Jul 22, 2013 at 5:59
0
The problem is indent only.
You are using IDLE. When you press enter after first print statement indent of else is same as print by default, which is not OK. You need to go to start of else sentence and press back once. Check in attached image what I mean.
Mogsdad
44.8k21 gold badges153 silver badges275 bronze badges
answered Apr 18, 2016 at 18:22
it is a obvious mistake we do, when we press enter after the if statement it will come into that intendation,try by keeping the else statement as straight with the if statement.it is a common typographical error
answered Jan 25, 2017 at 15:40
2
Else needs to be vertically aligned. Identation is playing a key role in Python. I was getting the same syntax error while using else. Make sure you indent your code properly
answered Mar 3, 2019 at 5:19
JasonJason
1031 silver badge11 bronze badges
1
In Python ” else SyntaxError: expected ‘:’ ” error occurs when we miss a colon (:) at the end else statement. In Python, after the if-else statement end line code, we need to add a colon, colons are used to indicate the start of a new block of code, such as the body of a for loop or an if and else statement. In our code, we need to just add a colon (:) after else and then run the code again, for more clarification please see the below example.
Table of Contents
Wrong Code
print("Welcome to the Amol Blog payground hall")
height = int(input("What is your height in cm:"))
if height >120:
print("You can come the cinema hall")
else
print("Sorry, you have to grow taller befor you play")
Error Massage
File "/home/kali/python/webproject/error/main.py", line 6
else
^
SyntaxError: expected ':'
Wrong code line
else
Correct code line
else:
- Wrong action: no colon (else).
- Correct action: add a colon (else:).
Entire Correct Code line
print("Welcome to the Amol Blog payground hall")
height = int(input("What is your height in cm:"))
if height >120:
print("You can come the cinema hall")
else:
print("Sorry, you have to grow taller befor you play")
What is else SyntaxError: expected ‘:’?
In python, we face this error because of forgetting to include a colon (:) at the end of the else statement line then we are facing this error. In Python, colons are used to indicate the start of a new block of code, such as the body of a for loop or an if else statement.
How to fix else SyntaxError: expected ‘:’?
In python, if we want to fix this error, we need to make sure that you add a colon(:) at the end of every else statement line. for more clarification please see the below example.
For more information Visit Amol Blog Code YouTube Channel.