elif a=="no": ^ SyntaxError: invalid syntax - python

this is the error i get for my code I cant seem to find out how to fix it
File "C:\Users\mayar\Desktop\final edge project\execute_html.py", line 19
elif a=="no":
^
SyntaxError: invalid syntax
Code -
import codecs
import subprocess
import os
while (True):
corona = input("Do you want to know more about Coronavirus-COVID-19? answer in yes/no format \n")
if corona== "yes":
url = "CORONAVIRUS.htm"
#Python executes code following the try statement as a “normal” part of the program
try:
os.startfile(url)
#The code that follows the except statement is the program’s response to any exceptions in the preceding try clause.
except AttributeError:
try:
subprocess.call(['open', url])
except:
print('Could not open URL')
break
elif a=="no":
print("Have a nice day!")
else:
print("Enter either yes/no")

You need to have elif directly after if. You can't have any other lines of codes between an if and the following elifs. You are probably messing up with the indentations in your code. You can edit your code to have try except to be included inside the first if statement and then it will work.
Correct code -
import codecs
import subprocess
import os
while (True):
corona = input("Do you want to know more about Coronavirus-COVID-19? answer in yes/no format \n")
if corona== "yes":
url = "CORONAVIRUS.htm"
try:
os.startfile(url)
#The code that follows the except statement is the program’s response to any exceptions in the preceding try clause.
except AttributeError:
try:
subprocess.call(['open', url])
except:
print('Could not open URL')
break
elif corona=="no":
print("Have a nice day!")
else:
print("Enter either yes/no")

Use this code:
import codecs
import subprocess
import os
while (True):
corona = input("Do you want to know more about Coronavirus-COVID-19? answer in yes/no format \n")
if corona== "yes":
url = "CORONAVIRUS.htm"
#Python executes code following the try statement as a “normal” part of the program
try:
os.startfile(url)
except AttributeError:
try:
subprocess.call(['open', URL])
except:
print('Could not open URL')
break
elif corona=="no":
print("Have a nice day!")
else:
print("Enter either yes/no")

Right code:
import codecs
import subprocess
import os
url = "CORONAVIRUS.htm"
while True:
corona = input("Do you want to know more about Coronavirus-COVID-19? answer in yes/no format \n")
if corona== "yes":
#Python executes code following the try statement as a “normal” part of the program
try:
os.startfile(url)
#The code that follows the except statement is the program’s response to any exceptions in the preceding try clause.
except AttributeError:
try:
subprocess.call(['open', url])
except:
print('Could not open URL')
break
elif corona=="no":
print("Have a nice day!")
else:
print("Enter either yes/no")

Related

Git Commit-Msg in Python. Getting an EOF Error

I am creating a commit-msg for .git/hooks/commit-msg and I am getting an EOF Error when asking user for input() on this line
response = input("Are you sure you want to commit? [y/N]: ")
if anyone could help me figure out what is wrong!
Output log
#!/usr/bin/python
import sys
import re
def main():
# open file to read every lines
with open(sys.argv[1], "r") as fp:
lines = fp.readlines()
for idx, line in enumerate(lines):
if line.strip() == "# ------------------------ >8 ------------------------":
break
if line[0] == "#":
continue
# warning message
if (re.search('#[0-9]+$', line) is None):
print("Warning: add issue number related to this commit.")
# ask user to confirm until valid response
try:
while True:
response = input("Are you sure you want to commit? [y/N]: ")
if (response == 'y'):
sys.exit(0)
elif (response == 'N'):
sys.exit(1)
except EOFError as e:
print(e)
# successful commit
print("Success: Perfect commit!")
sys.exit(0)
if __name__ == "__main__":
main()
The commit-msg hook is run with no standard input (more specifically, standard input is redirected from /dev/null), and therefore any attempt to read from standard input will immediately read EOF.
You could try reading from /dev/tty if standard output is a TTY, but be aware that it isn't guaranteed that you'll have one at all. Commits can be run noninteractively without any terminal at all, and the hooks are not designed to be interactive. You'll have to decide what you want to do in that case.

Multiple phrases with SpeechRecognition in python

I have posted the complete code below and I would like to be able to achieve repeated execution of audio = r.listen(source). I have gotten the code to repeat but it returns the same thing everytime. I don't really like giving up and coming here asking for answers (first time posting). What do I have to do to get the code to return new phrase every time It executes the do_again(quit) function. Basically, the program asks to say something and it works fine the first time. When I am prompted to continue or quit and I enter 'c' I want to repeat the whole thing all over. Any help would be greatly appreciated. PS I am new to python and am probably doing this completely wrong. Any tips also will be appreciated!
Here is the code (All criticism is welcome. like: is there a better cleaner way to do this?)
import speech_recognition as sr
import sys
r = sr.Recognizer()
m = sr.Microphone()
with m as source:
print('Speak clearly for better results ...')
audio = r.listen(source)
quit = 'c'
q = quit
def do_again(quit):
quit = input('Press c to continue OR press q to quit: ')
q = quit
if q == 'q':
print('Exiting program')
sys.exit()
elif q == 'c':
print('Running again...')
else:
print('ERROR! Press c to continue OR press q to quit ')
return q
response = {"success": True,
"error": None,
"transcription": None
}
while q == 'c':
try:
# I want this to return new phrase instead of returning the same phrase.
response['transcription'] = r.recognize_sphinx(audio) # I want a new 'response' here
print(f"[SPEECH RECOGNIZED] {response['transcription']}")
except sr.UnknownValueError:
print(f"[FATAL ERROR] Exiting...")
except sr.RequestError as e:
response['success'] = False
response['error'] = 'API Unavailable/unresponsive'
print(f"[FATAL ERROR] {response['error']} {e}")
do_again(quit)
I think I found my answer. I was reading the documentation in the python interpreter with the help(r.Recognizer) feature. I found a listen_in_background method. Will listen_in_background do what I need? I know it's a silly program but I plan to do something practical for myself. If this will work, you guys can close this thread. I feel very dumb haha. I'm gonna try it out and if it works ill post my solution. Thanks again!
[EDIT]
It worked! I defined this function: def callback(r,audio) which is needed for stop_listening = r.listen_in_background(m, callback). I am having a hard time understanding the purpose of this line: stop_listening(wait_for_stop=True). If someone can please explain a bit so I can use it better in the future. Finally i added a 'magic word' to quit the program (just say 'quit' and sys.quit() terminates the program.). Is there a better way to do this?
Here is the new code:
import time
import speech_recognition as sr
import sys
def callback(r, audio):
global done
try:
print(f"[PocketSphinx]: Thinks you said: '{r.recognize_sphinx(audio)}'. Read some more ")
except sr.UnknownValueError:
print(f"[PocketSphinx]: Fatal error! Unknown Value Error! Exiting program.")
except sr.RequestError as ex:
print(f"[PocketSphinx]: Fatal error! Could not process request! {ex}")
if r.recognize_sphinx(audio) == 'quit':
print(f"[PocketSphinx]: You said the magic word: 'quit'... Exiting program.")
done = True
r = sr.Recognizer()
r.energy_threshold = 4000
m = sr.Microphone()
done = False
with m as source:
r.adjust_for_ambient_noise(source)
print(f"[PocketSphinx]: Read to me... Say 'quit' to exit...")
stop_listening = r.listen_in_background(m, callback)
# 5 second delay
for _ in range(50):
time.sleep(0.1)
while not done:
time.sleep(0.1)
if done:
stop_listening(wait_for_stop=True)
sys.exit()

How to point from one module to the next

I'm trying to make a password system for a program. I have the first half working so when I punch in the code it opens my file. After that the program asks for the password again instead of moving on to the next module which is supposed to close the file. Here's what I have
import os
while True:
choice = int(input("Enter Password: "))
if (choice>=1124):
if choice ==1124:
try:
os.startfile('C:\\restriced access')
except Exception as e:
print (str(e))
while True:
choice = int(input("Close? (y/n): "))
if (choice<='y'):
if choice =='y':
os.system('TASKKILL /F /IM C:\\restriced access')
I want it to kind of appear as an "if/then" kinda statement. For example if the password is entered correctly it opens the file `os.startfile('C:\restriced access') then points to the next module to give the option to close.
"While True" just keeps looping infinitely. As soon as you open the file it'll go back to the beginning of that loop and ask for your password again. If you want it to break from that loop if they get the password correct you need to add a "break" after your startfile line. I'm also not sure why you check their password twice. If you want it to exit the loop after attempting to open the file whether it succeeds or not, add a "finally" block after your exception handler.
while True:
choice = int(input("Enter Password: "))
if (choice>=1124):
if choice ==1124:
try:
os.startfile('C:\\restriced access')
break
except Exception as e:
print (str(e))
Your while loop is while True:. This will never exit unless you explicitly exit from it. You want to add a break in it like so:
os.startfile('C:\\restriced access')
break
Great to see you learn python.
The reason is because the while loop doesn't have a break in it.
Then again avoid opening files in a loop.
Also the nested if makes it hard to debug.
Also checkout pep8.
havent made any code changes.
import os
while True:
choice = int(input("Enter Password: "))
if (choice<1124):
continue
if choice ==1124:
try: os.startfile('C:\\restriced access')
break
except Exception as e:
print (str(e))
break
while True:
choice = input("Close? (y/n): ")
if (choice=='y'):
break

python-help learning how to deal with errors using try-except [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 6 years ago.
I am brand new to the site and python. I'm learning how to deal with errors using try-except. I'm asking for inputs to open a file and search for a line. This is the program i have now. It mostly works...
try:
file_str = input("Open what file:")
input_file = open(file_str) # potential user error
find_line_str = input("Which line (integer):")
find_line_int = int(find_line_str) # potential user error
line_count_int = 1
for line_str in input_file:
if line_count_int == find_line_int:
print("Line {} of file {} is {}".format(find_line_int, file_str,line_str))
break
line_count_int += 1
else: # get here if line sought doesn't exist
print("Line {} of file {} not found".format(find_line_int,file_str))
input_file.close()
except IOError:
while True:
file_str = input("That file was not found. Please try again:")
except ValueError:
find_line_str = input("Invalid line value. Please try again:")
print("End of the program")
Originally, if there was an error it would say "invalid entry, end of program" Now I am trying to make the program keep asking for inputs until the user gets it right.
With the while loop I put in my except IOError it just loops forever even if I enter a valid file name. If I just ask for input it ends the program after entry.
How do I get it to go back and run the for loop after it receives a valid input? Ive been trying to figure this out for hours I really appreciate the help.
In a nutshell
while True:
try:
#code
break #success case
except IOError:
#error display
#no break, the loop goes on
Updated version of your own script. Added a while loop. The following script will start again from top in case of ValueError or IOError.
while True:
try:
file_str = input("Open what file:")
input_file = open(file_str) # potential user error
find_line_str = input("Which line (integer):")
find_line_int = int(find_line_str) # potential user error
line_count_int = 1
for line_str in input_file:
if line_count_int == find_line_int:
print("Line {} of file {} is {}".format(find_line_int, file_str,line_str))
break
line_count_int += 1
else: # get here if line sought doesn't exist
print("Line {} of file {} not found".format(find_line_int,file_str))
input_file.close()
break
except IOError:
print "That file was not found. Please try again:"
except ValueError:
print "Invalid line value. Please try again:"
print("End of the program")
With the while loop I put in my except IOError it just loops forever even if I enter a valid file name. If I just ask for input it ends the program after entry.
Of course it would:
except IOError:
while True:
file_str = input("That file was not found. Please try again:")
Once the first IOError is occurred there is no way to break from that while loop.
As a rule of thumb, you should keep the least amount of lines in each try block. This way you will have a finer control over what line raised the exception.
In this case, you should try opening the file in a while loop, breaking if succeeding and keep looping if an exception occurred:
while True:
file_str = input("Open what file:")
try:
input_file = open(file_str) # potential user error
break
except IOError:
print('File not found. Try again')
# rest of code
Your try/except(s) should be put in a while-condition loop.
To exit the loop you can then either:
set a condition flag as True before entering the loop and as False as soon as entry is ok - you'll keep looping on any error
or put a 'break' at the end of a correct entry within a 'while True:' loop
In both case, you should accept also quitting the loop on some request from the user (something as a 'cancel' use-case).

sys.exit in python console

Hi I have troubles using sys.exit in a python console. It works really nice with ipython. My code looks roughly like this:
if name == "lin":
do stuff
elif name == "static":
do other stuff
else:
sys.exit("error in input argument name, Unknown name")
If know the program know jumps in the else loop it breaks down and gives me the error message. If I use IPython everything is nice but if I use a Python console the console freezes and I have to restart it which is kind of inconvenient.
I use Python 2.7 with Spyder on MAC.
Is there a workaround such that I the code works in Python and IPython in the same way? Is this a spyder problem?
Thanks for help
Not sure this is what you should be using sys.exit for. This function basically just throws a special exception (SystemExit) that is not caught by the python REPL. Basically it exits python, and you go back to the terminal shell. ipython's REPL does catch SystemExit. It displays the message and then goes back to the REPL.
Rather than using sys.exit you should do something like:
def do_something(name):
if name == "lin":
print("do stuff")
elif name == "static":
print("do other stuff")
else:
raise ValueError("Unknown name: {}".format(name))
while True:
name = raw_input("enter a name: ")
try:
do_something(name)
except ValueError as e:
print("There was a problem with your input.")
print(e)
else:
print("success")
break # exit loop
You need to import sys. The following works for me:
import sys
name="dave"
if name == "lin":
print "do stuff"
elif name == "static":
print "do other stuff"
else:
sys.exit("error in input argument name, Unknown name")

Categories

Resources