【问题标题】:In python putting 2 variables in a print在 python 中,将 2 个变量放入打印中
【发布时间】:2014-02-26 18:43:08
【问题描述】:
     import random

     characterNameOne=str(input("Please input first character's name"))
     characterNameTwo=str(input("Please input second character's name"))

     print("The characters have 2 attributes : Strength and Skill")

     dieOne = random.randint(1,4)
     dieTwo = random.randint(1,12)

     print ("A 12 and 4 sided dice are rolled")

     print("Each character is set to 10")

     characterOneStrength = 10
     characterOneSkill = 10
     characterTwoStrength = 10
     characterTwoSkill = 10

     DivisionValue=round((dieTwo/dieOne),0)

     print("The number rolled on the 12 sided dice is divided by the number rolled on     the 4 sided dice")

     characterOneStrength += DivisionValue
     characterOneSkill += DivisionValue
     characterTwoStrength += DivisionValue
     characterTwoSkill += DivisionValue

     print ("The value of the divided dice is added to the character's attributes")

     print('Character one , your strength:',str(characterOneStrength) + '\n')
     print('Character one, your strength:',str(characterOneSkill) + '\n')
     print('Character two, your strength:',str(characterTwoStrength) + '\n')
     print('Character two, your strength:' ,str(characterTwoSkill) + '\n')


     fileObj = open("CharacterAttributes.txt","w") 
     fileObj.write('str(CharacterNameOne),your strength:' + str(characterOneStrength) + '\n')
     fileObj.write('str(characterNameOne), your skill:' + str(characterOneSkill) + '\n')
     fileObj.write('str(characterNameTwo),your strength:' + str(characterTwoStrength) + '\n')
     fileObj.write('str(characterNameTwo), your skill:' + str(characterTwoSkill) + '\n')
     fileObj.close()

您好,我将这段代码作为学校受控评估的草稿编写。任务是:

在确定游戏角色的某些特征时,骰子组合上的数字用于计算某些属性。

其中两个属性是力量和技能。

在游戏开始时,当创建角色时,会掷出一个 4 面骰子和一个 12 面骰子,以使用以下方法为每个角色确定每个属性的值:

每个属性最初设置为 10。 12 面骰子的分数除以 4 面骰子的分数并向下取整。 该值被添加到初始值。 对每个字符的每个属性重复此过程。 使用合适的算法描述这个过程。

编写并测试代码以确定一个字符的这两个属性,并将两个字符的示例数据(包括合适的名称)存储在一个文件中。

我想知道如何在这段代码中添加具有用户输入的字符名称的变量。我试过了,但是不行:

print('第一个字符,你的实力:',str(characterOneStrength) + '\n')

另外,关于如何使代码更短或更高效的任何建议。谢谢

【问题讨论】:

  • 引发了什么异常?如果您希望解决问题的这一部分,也可以在 CodeReview 上提出。

标签: python


【解决方案1】:

字符串格式应该适用于您需要的任何情况

message = "Character x, your strength: {} \n".format(characterXStrength)
print(message)

请注意,print 本身就已经添加了一个换行符,因此如果您需要其中两个,请仅包含 \n

【讨论】:

  • 这是正确的方法 (tm),IMO。
【解决方案2】:
    print('Character one , your strength:',str(characterOneStrength) + '\n') 

快到了:应该是

    print("character one your strength is:"+str(characterOneStrength)+"

你需要两边都有加号

【讨论】:

    【解决方案3】:

    这是一个扩展版本 - 跟踪它,你应该学到很多:

    import random
    import sys
    
    if sys.hexversion < 0x3000000:
        # Python 2.x
        inp = raw_input
        rng = xrange
    else:
        # Python 3.x
        inp = input
        rng = range
    
    NAMES = [
        "Akhirom", "Amalric", "Aratus", "Athicus", "Bragoras", "Cenwulf", "Chiron",
        "Crassides", "Dayuki", "Enaro", "Farouz", "Galbro", "Ghaznavi", "Godrigo",
        "Gorulga", "Heimdul", "Imbalayo", "Jehungir", "Karanthes", "Khossus"
    ]
    NUM_CHARS = 5
    OUTPUT = "CharacterAttributes.txt"
    
    def roll(*args):
        """
        Return the results of rolling dice
        """
        if len(args) == 1:      # roll(num_sides)
            sides, = args
            return random.randint(1, sides)
        elif len(args) == 2:    # roll(num_dice, num_sides)
            num, sides = args
            return sum(random.randint(1, sides) for _ in rng(num))
        else:
            raise TypeError("roll() takes 1 or 2 arguments")
    
    class Character:
        def __init__(self, name=None):
            if name is None:
                name = inp("Please input character name: ").strip()
            self.name = name
            self.strength = 10 + roll(10) // roll(4)
            self.skill    = 10 + roll(10) // roll(4)
    
        def __str__(self):
            return "{}: strength {}, skill {}".format(self.name, self.strength, self.skill)
    
    def main():
        # generate names  (assumes len(NAMES) >> NUM_CHARS)
        names = random.sample(NAMES, NUM_CHARS - 1)
    
        # make a character for each name
        chars = [Character(name) for name in names]
    
        # add an unnamed character (prompt for name)
        chars.append(Character())
    
        # write characters to file
        with open(OUTPUT, "w") as outf:
            for ch in chars:
                outf.write("{}\n".format(ch))
    
    if __name__=="__main__":
        main()
    

    并且,出于兴趣,这里是力量和技能属性的期望值分布:

    10: ******     (15.0%)
    11: ********** (25.0%)
    12: *********  (22.5%)
    13: *****      (12.5%)
    14: ***        ( 7.5%)
    15: **         ( 5.0%)
    16: *          ( 2.5%)
    17: *          ( 2.5%)
    18: *          ( 2.5%)
    19: *          ( 2.5%)
    20: *          ( 2.5%)
    

    【讨论】:

      最近更新 更多