2012-08-11 119 views
0

input()獲得不同的數據類型時,我想打印不同的東西。我有以下腳本:如何根據數據(輸入)類型打印某些內容?

#!/usr/bin/env python 
#-*- coding:utf-8 -*- 

f = input("Please enter a number: ") 

if f == type(int): 
    print("That's good") 
elif f == type(str): 
    print("That isn't a number.") 
else: 
    print("BrainOverflow") 

此腳本始終返回else部分。

回答

1

它不建議做類型檢查的蟒蛇,所以你可以嘗試這樣的事:

f = input("Please enter a number: ") 
try: 
    f=int(f) 
    print("That's good") 
except ValueError: 
    print("That isn't a number.") 

或:

f = input("Please enter a number: ") 
if f.isdigit(): 
    print("That's good") 
else: 
    print("That isn't a number.")