[英]How can i check if a given string from the user is a complex number?
用戶正在提供一個字符串,我必須檢查該數字是否為復數。 我嘗試了類似的方法,但是如果實部或虛部大於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
使用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('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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.