这里的问题是,我只是无法得到python来检查如果Currency1是在字符串,如果它不是然后打印,有一个错误,但如果Currency1 IS字符串然后移动和要求用户输入Currency2,然后再次检查。IF语句错误新变量输入python
回答
您可以使用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
谢谢!这种方法效果很好!非常感谢你! :d – ConfusedChild24 2013-03-23 20:32:21
你竟然试图为:
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
嘿谢谢..但这里的实际问题是,我检查后,如果Currency1是一个字符串,我不能设法让用户输入Currency2的下一个值。它给我一个语法错误。 elif: Currency2 = str(input('请输入您想转换成的货币:')))#此位不起作用 – ConfusedChild24 2013-03-23 20:02:21
- 1. C# - IF语句中变量的错误
- 2. 输入错误的If语句
- 3. 输入if语句
- 4. JavaScript if if语句变量
- 5. if语句中的Python语法错误
- 6. python If语句语法错误?
- 7. 更改变量if语句(Python)的
- 8. IF语句错误
- 9. 错误if语句
- 10. C#声明变量进入if语句
- 11. Python的错误If-Then语句
- 12. 变量和IF/ELSE语句
- 13. if语句中的变量
- 14. 变量中的if语句
- 15. if语句变量与
- 16. 输入值和If语句
- 17. 变量在输入if语句时被重置?
- 18. if if else语句的多个变量
- 19. Python输入语句
- 20. Python if语句
- 21. C#错误if语句
- 22. if else语句错误
- 23. If-else语句错误'else'without'if'
- 24. Math.random if语句错误
- 25. C++的if语句错误
- 26. if语句错误的bash
- 27. 错误cmake的IF语句
- 28. if语句编译错误
- 29. if语句中的错误
- 30. python if语句语法的变化
否则类型检查python意味着*你做错了*。 – 2013-03-23 19:59:15