Py学习  »  问与答

请教下,如何控制input函数输入的数据类型,不知道何时输入是数字类型,何时是字符串类型?谢谢

yefengzju • 6 年前 • 1408 次点击  

例1: num=input('enter a number:') if num>0: print('positive') elif num<0: print('negative') else: print('zero') enter a number:42 Traceback (most recent call last): File "C:/Users/HP/AppData/Local/Programs/Python/Python36/yeah's program/判断数字.py", line 2, in <module> if num>0: TypeError: '>' not supported between instances of 'str' and 'int'

例2:

x=input('x:') x:34 y=input('y:') y:22 print xy SyntaxError: Missing parentheses in call to 'print'. Did you mean print(xy)? print(xy) Traceback (most recent call last): File "<pyshell#57>", line 1, in <module> print(xy) TypeError: can't multiply sequence by non-int of type 'str'

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/5562
 
1408 次点击  
文章 [ 1 ]  |  最新文章 6 年前
Py站长
Reply   •   1 楼
Py站长    6 年前

无法知道 你得自己进行判断 和 转换