2017-03-15 68 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()