在Python中,查询输入是int还是str


from colorama import init, Fore, Style
import os
if Name == "Germany" or Name == "Italy" or Name == "Poland": 
Height = int(input("How high should the image be? Maximum is 4608 pixels."))
if Height < 1:
print(Fore.RED + "This is not a valid height!")
exit()
elif height > 0:
Width = int(Height * (16 / 9))

以下问题:

到目前为止,程序已经可以确定输入是否低于1,这对于图像来说是无效的高度。但是,如果我想防止当输入一封信或其他东西时,出现这样一条丑陋的错误消息,而程序却出现,我该怎么做呢

print(Fore.RED + "This is not a valid height!")
exit()

执行

如果需要更多的代码来理解上下文,请让我知道

ValueErrorTypeError外,您可以轻松使用Exception

代码语法

try:
Height = int(input("How high should the image be? Maximum is 4608 pixels."))
if Height < 1:
print(Fore.RED + "This is not a valid height!")
exit()
elif height > 0:
Width = int(Height * (16 / 9))
except (TypeError, ValueError):
print(Fore.RED + "This is not a valid height!")
exit()

最新更新