IF语句错误新变量输入python

2024-05-19 16:35:52 发布

您现在位置:Python中文网/ 问答频道 /正文

这里的问题是我不能让python检查Currency1是否在string中,如果不是,则打印有错误,但是如果Currency1在string中,则继续并要求用户输入Currency2,然后再次检查。你知道吗


Tags: 用户string错误currency1currency2
2条回答

您可以使用try-except

def get_currency(msg):
    curr = input(msg)
    try:
        float(curr)
        print('You must enter text. Numerical values are not accepted at this stage')
        return get_currency(msg)  #ask for input again
    except:
        return curr               #valid input, return the currency name

curr1=get_currency('Please enter the currency you would like to convert:')
curr2=get_currency('Please enter the currency you would like to convert into:')
ExRate = float(input('Please enter the exchange rate in the order of, 1 '+curr1+' = '+curr2)) 
Amount = float(input('Please enter the amount you would like to convert:'))
print (Amount*ExRate)

输出:

$ python3 foo.py

Please enter the currency you would like to convert:123
You must enter text. Numerical values are not accepted at this stage
Please enter the currency you would like to convert:rupee
Please enter the currency you would like to convert into:100
You must enter text. Numerical values are not accepted at this stage
Please enter the currency you would like to convert into:dollar
Please enter the exchange rate in the order of, 1 rupee = dollar 50
Please enter the amount you would like to convert: 10
500.0

你实际上是想:

if type(Currency1) in (float, int):
   ...

但是isinstance在这里更好:

if isinstance(Currency1,(float,int)):
   ...

或者更好,您可以使用numbers.Number抽象基类:

import numbers
if isinstance(Currency1,numbers.Number):

尽管。。。Currency1 = str(raw_input(...))将保证Currency1是字符串(不是整数或浮点)。实际上,raw_input提供了这个保证,这里多余的str只是多余的:-)。你知道吗

如果您想让函数检查字符串是否可以转换为数字,那么我认为最简单的方法就是尝试一下,看看:

def is_float_or_int(s):
    try:
        float(s)
        return True
    except ValueError:
        return False

相关问题 更多 >