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()
name=input ("please enter your name") .upper()
names=["MARTIN","JAMES","LOUIS","BABYSHARK"]
if name==list:names
print ("You are allowed to play my game")
else
prin ("ACCES DENIED!"))
asked Sep 12, 2018 at 19:23
6
Your solution might be this one:
names=["MARTIN","JAMES","LOUIS","BABYSHARK"]
name = input('Enter your name:').upper()
if name in names:
print('You can play my game')
else:
print('Access Denied')
answered Sep 12, 2018 at 19:39
GhanteyGhantey
6262 gold badges11 silver badges24 bronze badges
1
You need to add colons after your if and else statements. Also you need to indent the code in the if segment.
answered Sep 12, 2018 at 19:41
mindfoldedmindfolded
2161 silver badge8 bronze badges
3
Welcome to Stack Overflow. I suggest you read the python documentation about if statements. This clearly defines the syntax. The most common thing to miss is a colon after the condition of your if
and after else
.
answered Sep 12, 2018 at 19:44
Code-ApprenticeCode-Apprentice
81.2k22 gold badges142 silver badges265 bronze badges
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:Usersrhntmmyscript.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.
The if
Statement and Conditionals
if
in Python means: only run the rest of this code once, if the condition evaluates to True
. Don’t run the rest of the code at all if it’s not.
Anatomy of an if
statement: Start with the if
keyword, followed by a boolean value, an expression that evaluates to True
, or a value with “Truthiness”. Add a colon :
, a new line, and write the code that will run if the statement is True
under a level of indentation.
Remember, just like with functions, we know that code is associated with an if
statement by it’s level of indentation. All the lines indented under the if
statement will run if it evaluates to True
.
>>> if 3 < 5:
... print("Hello, World!")
...
Hello, World!
Remember, your if
statements only run if the expression in them evaluates to True
and just like with functions, you’ll need to enter an extra space in the REPL to run it.
Using not
With if
Statements
If you only want your code to run if the expression is False
, use the not
keyword.
>>> b = False
>>> if not b:
... print("Negation in action!")
...
Negation in action!
if
Statements and Truthiness
if
statements also work with items that have a “truthiness” to them.
For example:
- The number 0 is False-y, any other number (including negatives) is Truth-y
- An empty
list
,set
,tuple
ordict
is False-y - Any of those structures with items in it is Truth-y
>>> message = "Hi there."
>>> a = 0
>>> if a: # 0 is False-y
... print(message)
...
>>> b = -1
>>> if b: # -1 is Truth-y
... print(message)
...
Hi there.
>>> c = []
>>> if c: # Empty list is False-y
... print(message)
...
>>> d = [1, 2, 3]
>>> if d: # List with items is Truth-y
... print(message)
...
Hi there.
if
Statements and Functions
You can easily declare if
statements in your functions, you just need to mindful of the level of indentation. Notice how the code belonging to the if
statement is indented at two levels.
>>> def modify_name(name):
... if len(name) < 5:
... return name.upper()
... else:
... return name.lower()
...
>>> name = "Nina"
>>> modify_name(name)
'NINA'
Nested if
Statements
Using the same technique, you can also nest your if
statements.
>>> def num_info(num):
... if num > 0:
... print("Greater than zero")
... if num > 10:
... print("Also greater than 10.")
...
>>> num_info(1)
Greater than zero
>>> num_info(15)
Greater than zero
Also greater than 10.
How Not To Use if
Statements
Remember, comparisons in Python evaluate to True
or False
. With conditional statements, we check for that value implicitly. In Python, we do not want to compare to True
or False
with ==
.
Warning — pay attention, because the code below shows what you shouldn’t do.
# Warning: Don't do this!
>>> if (3 < 5) == True: # Warning: Don't do this!
... print("Hello")
...
Hello
# Warning: Don't do this!
>>> if (3 < 5) is True: # Warning: Don't do this!
... print("Hello")
...
Hello
Do this instead:
>>> if 3 < 5:
... print("Hello")
...
Hello
If we want to explicitly check if the value is explicitly set to True
or False
, we can use the is
keyword.
>>> a = True # a is set to True
>>> b = [1, 2, 3] # b is a list with items, is "truthy"
>>>
>>> if a and b: # this is True, a is True, b is "truthy"
... print("Hello")
...
Hello
>>> if a is True: # we can explicitly check if a is True
... print("Hello")
...
Hello
>>> if b is True: # b does not contain the actual value of True.
... print("Hello")
...
>>>
else
The else
statement is what you want to run if and only if your if
statement wasn’t triggered.
An else
statement is part of an if
statement. If your if
statement ran, your else
statement will never run.
>>> a = True
>>> if a:
... print("Hello")
... else:
... print("Goodbye")
...
Hello
And vice-versa.
>>> a = False
>>> if a:
... print("Hello")
... else:
... print("Goodbye")
...
Goodbye
In the REPL it must be written on the line after your last line of indented code. In Python code in a file, there can’t be any other code between the if
and the else
.
You’ll see SyntaxError: invalid syntax
if you try to write an else
statement on its own, or put extra code between the if
and the else
in a Python file.
>>> if a:
... print("Hello")
...
Hello
>>> else:
File "<stdin>", line 1
else:
^
SyntaxError: invalid syntax
elif
Means Else, If.
elif
means else if. It means, if this if
statement isn’t considered True
, try this instead.
You can have as many elif
statements in your code as you want. They get evaluated in the order that they’re declared until Python finds one that’s True
. That runs the code defined in that elif
, and skips the rest.
>>> a = 5
>>> if a > 10:
... print("Greater than 10")
... elif a < 10:
... print("Less than 10")
... elif a < 20:
... print("Less than 20")
... else:
... print("Dunno")
...
Less than 10