用户正在给出一个字符串,我必须检查该号码是否是一个复数。我尝试了类似的东西,但如果真实部分或想象部分大于9,它就不起作用。谢谢。
def validation(command):
command=command.list()
if len(command)==3:
if command[0]=="-" and command[1].isnumeric()==True and command[3].isnumeric()==True and command[3]=="i" and (command[2]=="+" or command[2]=="-"):
return True
if len(command)==4:
if command[0].isnumeric()==True and command[2].isnumeric()==True and command[3]=="i" and (command[1]=="+" or command[1]=="-"):
return True
return False
答案 0 :(得分:0)
使用try and except
并尝试将输入转换为复数:
try:
c = complex(input('enter a complex number: ')) # convert input to complex
except ValueError:
print('you need to enter a complex number!') # failed
complex不需要导入。它是一个内置的:
>>> complex('4+5j')
(4+5j)
>>> complex('30')
(30+0j)
>>> complex('30a')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: complex() arg is a malformed string