【问题标题】:Use variable in randint argument在 randint 参数中使用变量
【发布时间】:2015-03-21 16:26:46
【问题描述】:

这里是初学者,

我正在编写一个为用户掷骰子的程序,我希望它能够根据用户输入更改骰子的面数。我似乎无法让变量 amount_faces 作为 randint() 函数的 int 工作,每次都会出现“TypeError: cannot concatenate 'str' and '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()

有什么线索吗?

【问题讨论】:

    标签: python string int concatenation


    【解决方案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 只是一个字符串。您可以捕获int() 抛出的ValueError 以检测输入不可转换,而是:

    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,而不是使用递归进行程序控制。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-28
      • 2021-01-26
      • 1970-01-01
      • 2014-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-15
      相关资源
      最近更新 更多