在randint参数中使用变量

时间:2015-01-22 18:34:29

标签: python string int concatenation

这里的初学者,

我正在编写一个为用户掷骰子的程序,我希望它能够根据用户输入更改骰子的面数。我似乎无法使变量amount_faces作为randint()函数的int工作,我得到一个“TypeError:每次都无法连接'str'和'int'objetcts”错误:

from sys import exit
from random import randint

def start():
    print "Would you like to roll a dice?"
    choice = raw_input(">")
    if "yes" in choice:
        roll()
    elif "no" in choice:
        exit()
    else:
        print "I can't understand that, try again."
        start()

def roll():
    print "How many faces does the die have?"
    amount_faces = raw_input(">")
    if amount_faces is int:
        print "The number of faces has to be an integer, try again."
        roll()
    else:            
        print "Rolling die...."
        int(amount_faces)
        face = randint(1,*amount_faces)
        print "You have rolled %s" % face
        exit()

start()

任何线索?

1 个答案:

答案 0 :(得分:1)

int(amount_faces)不会就地更改amount_faces。您需要分配函数返回的整数对象:

amount_faces = int(amount_faces)

amount_faces不是可迭代的,因此您无法在此处使用*arg语法:

face = randint(1,*amount_faces)

您必须删除*

face = randint(1, amount_faces)

您也没有正确测试整数:

if amount_faces is int:

int是一个类型对象,amount_faces只是一个字符串。您可以捕获ValueError引发的int()来检测输入是否无法转换,而是:

while True:
    amount_faces = raw_input(">")
    try:
        amount_faces = int(amount_faces)
    except ValueError:
        print "The number of faces has to be an integer, try again."
    else:
        break

print "Rolling die...."
face = randint(1, amount_faces)
print "You have rolled %s" % face

您可能想要查看Asking the user for input until they give a valid response而不是使用递归进行程序控制。