Valid checking, Raising an exception - python-3.x

The code I'm trying to write take a string in the format 'command arg1 arg2', Right now, I'm stuck and not sure how to write a valid command check, where the valid command is 'add' or 'sub' or 'mul' or 'div'. If the command is not a valid command, it raises InvalidCommand().
Here's my code:
class InvalidCommand(Exception):
pass
def validate_input(string):
"""
validate_input(str) -> (str, [float])
If string is a valid command, return its name and arguments.
If string is not a valid command, raise InvalidCommand
Valid commands:
add x y
sub x y
mul x y
div x y
Arguments x and y must be convertable to float.
"""
li = []
if len(string.split(' ')) != 3:
raise InvalidCommand()
else:
try:
float(string.split(' ')[1])
float(string.split(' ')[2])
except ValueError:
raise InvalidCommand()
x = float(string.split(' ')[1])
y = float(string.split(' ')[2])
li.append(x)
li.append(y)
z = (string.split(' ')[0], li)
return z

I think this can do bro
VA=['add', 'sub', 'mul', 'div']
string=string.split()
if string[0] not in VA:
raise InvalidCommand()
elif len(string) !=3:
raise InvalidCommand()
else:
try:
return (string[0],[float(string[1]),float(string[2])])
except ValueError:
raise InvalidCommand()

Related

Why does my number reverser function produce an infinite loop

Whenever i try print the number reverser function i always get an infinite loop,instead of my expected output 54321. Can someone help find the problem? Thanks.
def order(num):
x=str(num)
if x==False:
return None
else:
return order(x[1:])+(x[0])
print (order(12345))
Welcome to your community.
There are some problems with your code:
First:
A string never will be equal to False.
for instance:
'0' is not equal to False.
'' is not equal to False.
Second:
You cannot add a String to None.
This Error will be thrown: TypeError: can only concatenate str (not "NoneType") to str
Modify your code like this:
def order(num):
x=str(num)
if x=='':
return ''
else:
return order(x[1:])+(x[0])
print (order(12345))
Tip 1: A string can be equal to '' (empty string).
In your function, you compare the string x with the boolean False. This is not a correct way to test whether string x is an empty string or not.
In addition, if string x is empty, then you shouldn't return None, but an empty string: reversing an empty string should logically return an empty string.
Here I present two ways to fix your function, which I implemented under the names reverse0 and reverse1. I also present a few other alternatives to achieve the same result using python features, under the names reverse2 to reverse6. Finally I present three other ways to reverse nonnegative integers, under the names reverse7 to reverse9.
def reverse0(num):
x = str(num)
if len(x) == 0:
return ''
else:
return reverse0(x[1:]) + x[0]
def reverse1(num):
x = str(num)
if not x:
return ''
else:
return reverse1(x[1:]) + x[0]
def reverse2(num):
return str(num)[::-1]
def reverse3(num):
return ''.join(reversed(str(num)))
def reverse4(num):
x = str(num)
return ''.join(x[len(x)-1-i] for i in range(len(x)))
def reverse5(num):
x = str(num)
return ''.join(x[-i] for i in range(1, len(x)+1))
def reverse6(num):
y = ''
for c in str(num):
y = c + y
return y
# reverse7 only works for nonnegative integers
def reverse7(num):
if num < 10:
return str(num)
else:
return str(num % 10) + reverse7(num // 10)
# reverse8 only works for nonnegative integers
def reverse8(num):
l = []
while num > 9:
l.append(num % 10)
num = num // 10
l.append(num)
return ''.join(str(d) for d in l)
# reverse9 only works for nonnegative integers
# reverse9 returns an int, not an str
def reverse9(num):
y = 0
while num > 0:
y = 10 * y + (num % 10)
num = num // 10
return y
Relevant documentation:
builtin reversed;
str.join;
An informal introduction to string slices such as x[::-1].

Why am I getting a syntax error for "except ValueError"

I keep on getting a syntax error for the line "except ValueError"
I tried many things including using 'pass' but it still didn't work.
y=0
while y==0:
x= input ('Enter the time(hour) ')
val = int(x)
if val <0 or val >= 24:
raise ValueError
break
except ValueError:
pass
print("Invalid integer. The number must be in the range of 0-24.")
if val>=12:
print (x + "pm")
else:
print (x + "am")
I wanted the program to return an error and print invalid integer if the 'val' was above or equal to 24 or lower than 0.
The reason you are getting a syntax error is that there is no valid standalone except statement. The correct usage of the except keyword is in a try...except statement.
y=0
while y==0:
x= input ('Enter the time(hour) ')
try:
val = int(x)
if val < 0 or val >= 24:
raise ValueError
break
except ValueError:
print("Invalid integer. The number must be in the range of 0-24.")
if val>=12:
print (x + "pm")
else:
print (x + "am")
Above is your example altered to show the proper use of the except keyword.

How to make variable accept strings

I want to make this code keep going? I tried put an x == to str, but I think that could not be the answer.
while True:
x = int(input("Please enter an integer:
"))
if x < 0:
x = 0
print('Negative changed to zero')
elif x == 0:
print('Zero')
elif x == 1:
print('Single')
else:
x == str :
input("please enter a string")
The first line of your loop can have one of two effects: either x is guaranteed to be an int, or you'll raise a ValueError. Catch the error and restart the loop, or continue with the body knowing that x is an int
while True:
x_str = input("Please enter an integer: ")
try:
x = int(x)
except ValueError:
print("{} is not an integer; please try again".format(x))
continue
if x < 0:
x = 0
print('Negative changed to zero')
elif x == 0:
print('Zero')
elif x == 1:
print('Single')
I'll try to guess what you wanted. I think you wanted a function that is like input, but with a strange twist: if what is entered (x) can be interpreted as an integer, then it returns the integer itself, not x. For example, if the user enters -72, it returns -72, not '-72'. Of course, if the user enters something that cannot be interpreted as an integer, the function returns it without modification.
Of course, being strongly typed, Python doesn't provide such a function, but it's easy to write one. And you don't even need try if you just intend to accept "ordinary"-looking integers.
def intput(prompt=''):
entered = input(prompt)
if entered[entered.startswith('-'):].isdigit(): return int(entered)
else: return entered
while True:
x = intput('Please enter an integer: ')
if x < 0:
x = 0
print('Negative input changed to zero')
elif x == 0: print('Zero')
elif x == 1: print('Single')
elif isinstance(x, str): print('You have entered a string that cannot be '
'easily interpreted as an integer.')

python3: how to enable strong typing?

Is there a way to get real strong typing in python3, such that one gets a runtime error, when the wrong type is used?
See following example:
def pick(k:int = None):
if k: print("value: ", k)
else: print("no value")
pick()
pick(1000)
pick("error")
this gives the following output:
no value <- can be accepted, and for this example it would be useful
value: 1000
value: error <- here should come a runtime error
Check this, hope will help. This is one of the way to force type checking.
def pick(k:int = None):
assert isinstance(k, int), 'Value Must be of Interger Type'
print("value: ", k) if k else print("no value") # Single Line Statement
In case of None or string it will raise AssertionError
AssertionError: Value Must be of Interger Type
However if you really need ValueError to be raise then
def pick(k:int = None):
if not isinstance(k, int):
raise ValueError('Value Must be of Interger Type')
print("value: ", k) if k else print("no value") # Single line statement
Exception
ValueError: Value Must be of Interger Type

How would I use Try and except in this code?

I don't understand.
I thought TypeError was what I needed.
I looked at some examples online and I thought this was right:
def main():
x = int(input("Input a number:"))
y = int(input("Input another number:"))
result = x * y
while not result:
try:
result = x * y
except TypeError:
print('Invalid Number')
main()
Include input's in try and except statements
def main():
while True:
try:
x = int(input("Input a number:"))
y = int(input("Input another number:"))
break
except ValueError:
print('invalid Number')
result=x*y
print(result)

Resources