我怎么说,如果变量=任何整数,在Python 2x中

时间:2017-03-15 20:30:09

标签: python

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

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

3 个答案:

答案 0 :(得分:1)

if type(variable) == int:

这将获取变量的类型并将其与类int

进行比较

答案 1 :(得分:0)

您应该使用isinstance()

if isinstance(variable, int):
    do_something()

答案 2 :(得分: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']