import sys
def main():
keystr = input("Enter the Key: ")
key = int(keystr)
if (key <=0) or (key>=25):
print("The key is out of range")
sys.exit()
When I want to terminate with input of key (<= 0 or >= 25), there is an error messgae.
The key is out of rangeTraceback (most recent call last):
File "C:/Users/USER/Desktop/caesarRefactored.py", line 38, in <module>
main()
File "C:/Users/USER/Desktop/caesarRefactored.py", line 11, in <module>
sys.exit()
builtins.SystemExit:
How can I fix it?
I'm running this on wing idle, the error shows. If on the terminal, it works just fine.
Related
I am making a coding language with Python. I am working on a module system for custom made modules.
The full code is at https://repl.it/#UCYT5040/koolCode and interp.py but the issue I am having is with this code:
for i in keywords:
keyword = i.lower()
if keyword == "print":
for i1 in quotes:
print(i1)
elif keyword == "add":
for i1 in quotes:
quote = i1.lower()
if quote == "python":
modulesInfo["python"] = {"runLang":"python","runpy":"{quote}"}
modules.append("python")
else:
print("koolCode WARN: custom modules not supported/module not found.")
else:
for i1 in modules:
if modulesInfo[i1]["runLang"] == "python":
try:
eval("f\"" + modulesInfo[i1][keyword] + "\"")
except KeyError:
print(f"koolCode ERROR: Module")
I get this error:
Welcome to koolCode console.
Would you like to open a file? y/n
n
A file will not be opened. Type any commands below.
koolCode>add "python"
['add'] ['python']
koolCode>runpy "help()"
Traceback (most recent call last):
File "main.py", line 8, in <module>
noFile()
File "main.py", line 3, in noFile
runString(input("koolCode>"))
File "/home/runner/koolCode/interp.py", line 46, in runString
eval("f\"" + modulesInfo[i1][keyword] + "\"")
File "<string>", line 1, in <module>
NameError: name 'quote' is not defined
How can I do this?
I'm making a Python program on a MacBook using the curses.textpad module. Here's my complete code:
import curses
from curses.textpad import Textbox, rectangle
def editor(stdscr):
stdscr.addstr(0, 0, "Type something: (hit Ctrl-G to exit)")
editor = curses.newwin(5, 30, 2, 1)
rectangle(stdscr, 1, 0, 1 + 5 + 1, 1 + 30 + 1)
stdscr.refresh()
box = Textbox(editor)
box.edit()
message = box.gather()
print(message)
text = curses.wrapper(editor)
print("Here's what you typed:")
print(text)
It keeps giving me this error whenever I try to run it:
Traceback (most recent call last):
File "/Users/Donoru/Desktop/editor/main.py", line 17, in <module>
text = curses.wrapper(editor)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/curses/__init__.py", line 84, in wrapper
stdscr = initscr()
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/curses/__init__.py", line 29, in initscr
setupterm(term=_os.environ.get("TERM", "unknown"),
_curses.error: setupterm: could not find terminal
How can I fix this?
I am pretty new to Python and I am just doing a bunch of exercises.
This is one of them, a simple DiceRoller.
It works perfectly fine in ATOM, the issue arises when I try to run it in IDLE. I am unable to figure out why the issue happen. Pretty sure this is a noob question.
The code:
import random
dices=[2, 3, 4, 6, 8, 10, 12, 20, 100]
Y= ['yes', 'y']
N= ['no', 'n']
def DiceRoller():
dice_selection=input('Please, choose the dice(d2, d3, etc. - only the number): ')
try:
dice = int(dice_selection)
except ValueError:
print('You have to select a number, try again')
DiceRoller()
if dice not in dices:
print('You have to select a 2, 3, 4, 6, 8, 10, 12, 20, 100 faces dice, try again')
DiceRoller()
number=input('How many dice(s) do you want to roll? ')
try:
numint = int(number)
except ValueError:
print('You have to select a number, try again')
DiceRoller()
ripet=0
while ripet < numint:
ripet += 1
if dice in dices:
result=random.randint(1,dice)
print(result)
else:
Continue()
def Continue():
risposta=input('Do you want to roll again? (Y/N) ')
rispostal= risposta.lower()
if rispostal in Y:
DiceRoller()
elif rispostal in N:
return 'Goodbye'
quit()
else:
print('Please, answer Yes or No')
Continue()
DiceRoller()
Errors whit IDLE after the program ask me if I want to roll again (input y or n):
Traceback (most recent call last):
File "E:\Corso Python\DiceRoller.py", line 44, in <module>
DiceRoller()
File "E:\Corso Python\DiceRoller.py", line 30, in DiceRoller
Continue()
File "E:\Corso Python\DiceRoller.py", line 33, in Continue
risposta=input('Do you want to roll again? (Y/N) ')
File "<string>", line 1, in <module>
NameError: name 'y' is not defined
Errors whit IDLE after the program ask me if I want to roll again (input Y or N):
Traceback (most recent call last):
File "E:\Corso Python\DiceRoller.py", line 44, in <module>
DiceRoller()
File "E:\Corso Python\DiceRoller.py", line 30, in DiceRoller
Continue()
File "E:\Corso Python\DiceRoller.py", line 34, in Continue
rispostal= risposta.lower()
AttributeError: 'list' object has no attribute 'lower'
Thank you for your patience!
That's because in the atom editor, you use python3 and your IDLE uses python2. In Python 2, the function for reading user's input was called raw_input(); it was renamed to input() in Python 3 (section starting with PEP 3111: raw_input() was renamed to input()).
You can either ensure you are using python3 by default or make the code python2-compatible: add a code block
import sys
compatible_input = raw_input if sys.version_info < (3, 0) else input
and replace all usages of ... = input(...) in your code with ... = compatible_input(...).
I have a raspberry pi using a GPS module. To use the module, I am running a code such as this:
##Prints the latitude and longitude every second.
import time
import microstacknode.hardware.gps.l80gps
if __name__ == '__main__':
gps = microstacknode.hardware.gps.l80gps.L80GPS()
while True:
data = gps.get_gpgga()
List = [list(data.values())[x] for x in [7, 9, 12]]
string=str(List)
string = string[1:-1]
text_file = open("/home/pi/fyp/gps.txt","a")
text_file.write(string + "\n")
time.sleep(1)
However, every now and then it gives this error because it cannot find my location:
Traceback (most recent call last):
File "gps.py", line 8, in <module>
data = gps.get_gpgga()
File "/usr/lib/python3/dist-packages/microstacknode/hardware/gps/l80gps.py", line 119, in get_gpgga
pkt = self.get_nmea_pkt('GPGGA')
File "/usr/lib/python3/dist-packages/microstacknode/hardware/gps/l80gps.py", line 293, in get_nmea_pkt
"Timed out before valid '{}'.".format(pattern))
microstacknode.hardware.gps.l80gps.NMEAPacketNotFoundError: Timed out before valid 'GPGGA'.
It's alright to have that error. The trouble I have is that the program stops running if it occurs. Is there a way to catch that error and get the program to loop back and try again even if it encounters this error?
UPDATE
if I try Stefan_Reinhardt's method, I would get the following error instead:
Traceback (most recent call last):
File "gps.py", line 9, in <module>
data = gps.get_gpgga()
File "/usr/lib/python3/dist-packages/microstacknode/hardware/gps/l80gps.py", line 119, in get_gpgga
pkt = self.get_nmea_pkt('GPGGA')
File "/usr/lib/python3/dist-packages/microstacknode/hardware/gps/l80gps.py", line 293, in get_nmea_pkt
"Timed out before valid '{}'.".format(pattern))
microstacknode.hardware.gps.l80gps.NMEAPacketNotFoundError: Timed out before valid 'GPGGA'.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "gps.py", line 10, in <module>
except NMEAPacketNotFoundError:
NameError: name 'NMEAPacketNotFoundError' is not defined
I agree to the answer of Oisin,
but i'd suggest to put the try-except clause only arround the line where it could happen, and pass the rest of the while-loop with a continue statement so it would look like
##Prints the latitude and longitude every second.
import time
import microstacknode.hardware.gps.l80gps
if __name__ == '__main__':
gps = microstacknode.hardware.gps.l80gps.L80GPS()
while True:
try:
data = gps.get_gpgga()
except NMEAPacketNotFoundError:
continue
List = [list(data.values())[x] for x in [7, 9, 12]]
string=str(List)
string = string[1:-1]
text_file = open("/home/pi/fyp/gps.txt","a")
text_file.write(string + "\n")
time.sleep(1)
This should work but it could get stuck in an infinite recursion loop.
##Prints the latitude and longitude every second.
import time
import microstacknode.hardware.gps.l80gps
if __name__ == '__main__':
getPos()
def getPos():
try:
while True:
gps = microstacknode.hardware.gps.l80gps.L80GPS()
data = gps.get_gpgga()
List = [list(data.values())[x] for x in [7, 9, 12]]
string=str(List)
string = string[1:-1]
text_file = open("/home/pi/fyp/gps.txt","a")
text_file.write(string + "\n")
time.sleep(1)
except microstacknode.hardware.gps.l80gps.NMEAPacketNotFoundError:
getPos()
I've tried two different versions of the same function:
def position_of(self, table_name, column_name):
positions = self.heading_positions()
position = positions['{t}.{c}'.format(t=table_name, c=column_name)]
return position
-
def position_of(self, table_name, column_name):
positions = self.heading_positions()
try:
position = positions['{t}.{c}'.format(t=table_name, c=column_name)]
except KeyError:
raise RuntimeError('No heading found for {t}.{c} in import profile "{ip}"'.format(t=table_name, c=column_name, ip=self))
return position
With the first version, I get the following error, which is fine:
Traceback (most recent call last):
File "./import.py", line 15, in <module>
g.process()
File "/home/jason/projects/mcifdjango/mcif/models/generic_import.py", line 39, in process
row.process()
File "/home/jason/projects/mcifdjango/mcif/models/csv_row.py", line 18, in process
self.save()
File "/home/jason/projects/mcifdjango/mcif/models/csv_row.py", line 26, in save
self.output("Phone: " + self.value('customer', 'phone'));
File "/home/jason/projects/mcifdjango/mcif/models/csv_row.py", line 60, in value
print self.generic_import.import_profile.position_of(table_name, column_name)
File "/home/jason/projects/mcifdjango/mcif/models/import_profile.py", line 22, in position_of
position = positions['{t}.{c}'.format(t=table_name, c=column_name)]
KeyError: 'customer.phone'
But the second version - the one that has the more informative error description - fails silently. Why is this?
The second version of position_of works fine for me. I have turned it into a minimal complete program as follows:
class Test(object):
def heading_positions(self):
return {}
def position_of(self, table_name, column_name):
positions = self.heading_positions()
try:
position = positions['{t}.{c}'.format(t=table_name, c=column_name)]
except KeyError:
raise RuntimeError('No heading found for {t}.{c} in import profile "{ip}"'.format(t=table_name, c=column_name, ip=self))
return position
a = Test()
a.position_of('customer', 'phone')
When I run this (using Python 2.6.6 on MacOS X) I get the following error message as expected:
Traceback (most recent call last):
File "./a.py", line 17, in <module>
a.position_of('customer', 'phone')
File "./a.py", line 13, in position_of
raise RuntimeError('No heading found for {t}.{c} in import profile "{ip}"'.format(t=table_name, c=column_name, ip=self))
RuntimeError: No heading found for customer.phone in import profile "<__main__.Test object at 0x100426ad0>"
This shows that catching the KeyError and turning it into a RuntimeError works fine. Does this example work for you? As Sven already writes, a possible explanation would be if you catch RuntimeError but not KeyError somewhere in the call chain.