2017-03-15 41 views
-3
import random 

print ("hello") 

user_friend1 = raw_input("Name one of your friends: ") 

user_friend2 = raw_input("Name another friend: ") 
# inputs for user 
friends = [user_friend1,user_friend2] 

best_friend = random.sample(friends, 1) 

我想循環播放,這樣,如果用戶鍵入一個問題一個整數,然後它會再次提出這樣的問題,我需要它,這兩個問題user_friend 1和2我怎麼說,如果變量=任意整數,在Python 2倍

print ("your best friend is %s") % (best_friend) 
+0

[谷歌](http://stackoverflow.com/q/3501382/1790644)嗎? –

+0

'if type(variable)== int:#do something' –

+2

'isinstance(variable,int)'會更pythonic,不是嗎? @JoshuaNixon –

回答

0

使用此

import random 
while True: 
    friend1 = raw_input("Name one of your friends: ") 
    try: 
     val = int(friend1) 
    except ValueError: 
     break 
    print("Enter valid name") 
while True: 
    friend2 = raw_input("Name another friend: ") 
    try: 
     val = int(friend2) 
    except ValueError: 
     break 
    print("Enter valid name") 
friends = [friend1,friend2] 
best_friend = random.sample(friends, 1) 
print("your bestfriend is %s" %(best_friend)) 

輸出

Name one of your friends: 1 
Enter valid name 

Name one of your friends: 1 
Enter valid name 

Name one of your friends: tilak 

Name another friend: varma 
your bestfriend is ['varma'] 
+0

這有助於您完成工作 –

+0

我想問這個問題兩次,那麼我該怎麼做?輸入兩次? –

+0

現在查看編輯答案 –

1
if type(variable) == int: 

這得到了變量的類型,並將其與類int

0

您應該使用isinstance()

if isinstance(variable, int): 
    do_something() 
相關問題