Here's my script:
def makeithappen():
word=""
while True:
try:
word=inputText()
except:
print("Something happened inputText")
else:
if len(word)>0:
break
elif word!=str:
break
For some reason however I get an invalid syntax error and I am not sure why.
def makeithappen():
word=""
while True:
try:
word=input() #is this supposed to be input()?
except:
print("Something happened inputText")
else:
if len(word)>0:
break
elif isinstance(word, basestring): #I never got the logic behind it
break
I think this is what you wanted to do. It exits if entered text is valid (length is more than 0) and input type is not of str (which is always false in case of python3).
#!/usr/bin/python
# -*- coding: utf-8 -*-
def makeithappen():
word=""
while True:
try:
word=raw_input("Go:")
except:
print("Something happened inputText")
else:
if len(word)>0:
print("Hello!!")
elif word!=str:
print("Bye!!")
break
makeithappen()
Related
The code works fine except for the exceptions i.e., when I input something like cat/dog or 1/0 or for the case 3/2, instead of re-prompting, the terminal just goes into blank infinite mode that I have to manually stop with cmd+c. Please help identify what I'm doing wrong. Thanks!
def main():
fuel=input("Fuel: ")
c=convert(fuel)
print(f"{convert(fuel)}%")
gauge(c)
def convert(fraction):
while True:
try:
X,Y=fraction.split("/")
x=int(X)
y=int(Y)
f=x/y
z=int((x/y)*100)
if f<=1:
return z
except (ValueError, ZeroDivisionError):
pass
def gauge(percentage):
if percentage<=1:
print("E")
elif percentage>=99:
print("F")
else:
print("Z%")
if __name__ == "__main__":
main()
Well, you never re-ask the question. To solve it, move the input("Fuel: ") call inside the while loop:
def main():
c = convert()
print(f"{c}%")
gauge(c)
def convert():
while True:
fraction = input("Fuel:")
try: # Rest can be the same
The program isn't printing what I want ("too slow") after the except with the KeyboardInterrupt, which should end the program and print the string, instead the program just ends. I tried messing around with it a bit but can't seem to figure it out. What should I do?
import os
import signal
import threading
from random import randint
def timed_input(interval, *args):
t = threading.Timer(interval, os.kill, args=(os.getpid(), signal.SIGINT))
t.start()
try:
return int(input(*args))
except:
pass
finally:
t.cancel()
while True:
want = randint(1,9)
try:
got = timed_input(5, f'type "{want}": ')
except KeyboardInterrupt:
print('too slow')
else:
if got != want:
print('You Lose.')
break
This is because your first function is removing the KeyboardInterrupt thus making the second try block useless.
To fix this add another except block for the first function so it is properly raised:
import os
import signal
import threading
from random import randint
def timed_input(interval, *args):
t = threading.Timer(interval, os.kill, args=(os.getpid(), signal.SIGINT))
t.start()
try:
return int(input(*args))
except KeyboardInterrupt:
raise
except ValueError:
pass
finally:
t.cancel()
while True:
want = randint(1,9)
try:
got = timed_input(5, f'type "{want}": ')
except KeyboardInterrupt:
print('too slow')
else:
if got != want:
print('You Lose.')
break
Hi guys I was working on a shoppinglist-creator code but at the end I faced with a surprise.
My code:
import time
import math
import random
dict_of_lists={}
def addlist():
while True:
try:
listname=str(raw_input("=>Name of the list:\n"))
dict_of_lists[listname]={}
break
except ValueError:
print "=>Please enter a valid name.\n"
print "=>You added a new list named %s.\n" % (listname)
def printlists():
for lists in dict_of_lists:
return "-"+lists
def addproduct():
while True:
try:
reachlistname=input("=>Name of the list you want to add a product,Available lists are these:\n %s \nPlease enter one:\n" % (printlists()))
break
except ValueError:
print "=>Please enter a valid list name.\n"
while True:
try:
productname=raw_input("=>Name of the product:\n")
break
except ValueError:
print "=>Please enter a valid name.\n"
while True:
try:
productprice=input("=>Price of the product:\n")
if isinstance(float(productprice),float):
break
except ValueError:
print "=>Please enter a valid number.\n"
while True:
try:
productcount=input("=>Amount of the product:\n")
if isinstance(int(productcount),int):
break
except ValueError:
print "=>Please enter a valid number.\n"
dict_of_lists[reachlistname][productname]={"price":productprice,"count":productcount}
dict_of_lists[reachlistname]={productname:{"price":productprice,"count":productcount}}
allevents="1-Add a list"+" 2-Add a product to a list"
def eventtochoose():
while True:
try:
event=raw_input("=>What would you like to do? Here are the all things you can do:\n %s\nPlease enter the number before the thing you want to do:" % (allevents))
if not isinstance(int(event),int):
print "\n=>Please enter a number.\n"
else:
if event==1:
addlist()
break
elif event==2:
addproduct()
break
except ValueError:
print "\n=>Please enter a valid input.\n "
while True:
print "%s" % ("\n"*100)
eventtochoose()
So, the problem is (I suggest you run the code) it says "=>What would you like to do? Here are the all things you can do:
1-Add a list 2-Add a product to a list
Please enter the number before the thing you want to do:" and when i put an answer it simply doesn't call the fucntion.
If I put 1 It should have called the fucntion addlist but I think it doesn't. There is nothing to explain I think just look at the code and find the problem if you want to help crocodiles. Thx
When you do int(event), that returns an int if possible, and raises a ValueError if not. So, testing the type of the result doesn't do you any good—if your code gets that far, the type has to be an int.
You already have code to handle the ValueError, so you don't need any other test for the same problem.
Meanwhile, you want to start the number that you got from int(event). That's the thing that can be == 1; the original string '1' will never be == 1.
So:
while True:
try:
event=raw_input("=>What would you like to do? Here are the all things you can do:\n %s\nPlease enter the number before the thing you want to do:" % (allevents))
event = int(event)
if event==1:
addlist()
break
elif event==2:
addproduct()
break
except ValueError:
print "\n=>Please enter a valid input.\n "
You are not converting your input to an integer before comparing, so the comparisons are always false:
'1' == 1 # false
Try:
event = raw_input("=>What would you like to do? Here are the all things you can do:\n %s\nPlease enter the number before the thing you want to do:" % (allevents))
try:
event = int(event)
if event == 1:
addlist()
elif event == 2:
addproduct()
break
except ValueError:
print('Please enter a valid input')
I'm trying to make do with Python's lack of a switch statement and make code more efficient by using a dictionary, but I can't quite get what I'm looking for. Here's a simplified version of the code I'm working with
def zero():
print("Yo")
def one():
print("Hey")
options = {
0: zero,
1: one,
}
while True:
response = int(input("Number: "))
try:
options.get(response)()
except TypeError:
print("Not a valid response")
and what I would like to see is some way to break the loop such as 2: break that exits the loop. Currently I'm using sys.exit(0), but was wondering if it was possible to use the break keyword
You could define a LoopBreak exception, raise that in a two function, and catch it in the loop to break:
class LoopBreak(Exception):
pass
def zero():
print("Yo")
def one():
print("Hey")
def two():
raise LoopBreak
options = {
0: zero,
1: one,
2: two
}
while True:
response = int(input("Number: "))
try:
options.get(response)()
except TypeError:
print("Not a valid response")
except LoopBreak:
break
As a point of interest, this is similar to the pattern used natively by Python to stop generators; they raise a StopIteration exception when they run out of values to yield.
EDIT: As #mfripp correctly notes below, this will mask any TypeErrors that are raised during execution of zero or one. I would change the main loop to this instead (so you don't have to rely on TypeError):
while True:
response = int(input("Number: "))
action = options.get(response)
if action is None:
print("Not a valid response")
continue
try:
action()
except LoopBreak:
break
There are a few ways you could do this.
Here's a more robust version of #BingsF's clever answer (this one won't mask exceptions raised within the selected function):
class LoopBreak(Exception):
pass
def zero():
print("Yo")
def one():
print("Hey")
def two():
raise LoopBreak
options = {
0: zero,
1: one,
2: two
}
while True:
try:
response = int(input("Number: "))
action = options[response]
except (ValueError, KeyError):
print("Not a valid response")
continue
try:
action()
except LoopBreak:
break
Or you could specify a special flag in your dictionary that will force a break:
def zero():
print("Yo")
def one():
print("Hey")
options = {
0: zero,
1: one,
2: False
}
while True:
try:
response = int(input("Number: "))
action = options[response]
except (ValueError, KeyError):
print("Not a valid response")
continue
if action is False:
break
else:
action()
Or use a special return value to force a break:
def zero():
print("Yo")
# returns None by default
def one():
print("Hey")
# returns None by default
def two():
return False
options = {
0: zero,
1: one,
2: two
}
while True:
try:
response = int(input("Number: "))
action = options[response]
except (ValueError, KeyError):
print("Not a valid response")
continue
if action() is False:
break
The following code might be more "Pythonic". It could be infinitesimally slower than the approaches above, because it has to check all the if statements instead of looking up the function in a dictionary via a hash. But it may be easier to read and maintain.
while True:
try:
response = int(input("Number: "))
except ValueError:
response = -1 # error flag
if response == 0:
print("Yo")
elif response == 1:
print("Hey")
elif response == 2:
break
else:
print("Not a valid response")
This is all you need:
while True:
response = int(input("Number: "))
if response not in options:
print("Not a valid response")
else if response == 2:
break
else:
options[response]() # invoke the corresponding function
Incidentally, storing functions in a dictionary and having to invoke them like this isn't exactly Pythonic. It's a lot nicer to simply explicitly enumerate the behaviour you need with successive ifs.
This program checks molecular formulas. I want the program to exit as soon as it detects an error in a formula. For example, the formula "a", is incorrect.
When I run it through my code:
def readletter():
if q.peek() in string.ascii_lowercase:
print(q.peek())
return q.get()
else:
raise Formelfel("Förväntad liten bokstav.")
def readLetter():
if q.peek() in string.ascii_uppercase:
print(q.peek())
return q.get()
else:
raise Formelfel("Förväntad stor bokstav.")
def readAtom():
X = ""
try:
X += readLetter()
except Formelfel:
print("Missing capital letter at end of row "+getRest())
sys.exit()
return
try:
x = readletter()
atom = X+x
except (Formelfel, TypeError):
atom = X
if atom in ATOMER:
return
else:
raise Formelfel("Okänd atom.")
def readGroup():
if q.peek() in string.ascii_uppercase or q.peek() in string.ascii_lowercase:
try:
readAtom()
except:
print("Unknown atom at end of row "+getRest())
sys.exit()
I get this output:
Missing capital letter and end of row a
Unknown atom at end of row
Why is this? I called sys.exit() before print("Unknown atom at end of row "+getRest()) so why does it still execute? I want only the first row of the output to be printed.
sys.exit raises a SystemExit exception. You are catching it with your except clause.
What you should do instead is catch a more specific class of exceptions, which does not include SystemExit.
Catching Exception will work:
def readGroup():
if q.peek() in string.ascii_uppercase or q.peek() in string.ascii_lowercase:
try:
readAtom()
except Exception:
print("Unknown atom at end of row "+getRest())
sys.exit()
You can learn more about exceptions and SystemExit in the docs.
Note that you should ideally catch something more specific than Exception (which is very broad, and may catch exceptions you don't intend to catch).
Because in python exit event is processed as SystemExit exception