如何在Python中获得两个输入变量之间的差异

时间:2014-04-13 17:37:35

标签: python

我目前正在使用Python编写程序。我来了一个小补丁。我想做的很简单。计算用户输入程序的两个数字之间的差异。

nameA = input("Enter your first German warriors name: ")

print( nameA,"the noble.")

print("What shall",nameA,"the noble strength be?") 

strengthA = input("Choose a number between 0-100:")

print("What shall",nameA,"the noble skill be?") 

skillA = input("Choose a number between 0-100:")

#Playerb

nameB = input("Enter your first German warriors name: ")

print( nameB,"the brave.")

print("What shall",nameB,"the noble strength be?") 

strengthB = input("Choose a number between 0-100:")

print("What shall",nameB,"the brave skill be?") 

skillB = input("Choose a number between 0-100:")

我试图计算用户输入的StrengthA和StrengthB之间的差异。

这个问题可能有点小说。但是,我们都必须学习。 谢谢。

2 个答案:

答案 0 :(得分:1)

只需使用-运算符,然后找到abs()运算符即可获得两个数字之间的差异。

abs(StrengthA - StrengthB)

但是,您必须首先确保使用整数。这样做:

StrengthA = int(input())  # Do the same with StrengthB.

修改

要找到整体除以5,您只需:

(abs(StrengthA - StrengthB)) / 5

答案 1 :(得分:0)

代码结构非常适合让您的程序更易于理解和维护:

def get_int(prompt, lo=None, hi=None):
    while True:
        try:
            value = int(input(prompt))
            if (lo is None or lo <= value) and (hi is None or value <= hi):
                return value
        except ValueError:
            pass

def get_name(prompt):
    while True:
        name = input(prompt).strip()
        if name:
            return name.title()

class Warrior:
    def __init__(self):
        self.name     = get_name("Enter warrior's name: ")
        self.strength = get_int("Enter {}'s strength [0-100]: ".format(self.name), 0, 100)
        self.skill    = get_int("Enter {}'s skill [0-100]: "   .format(self.name), 0, 100)

def main():
    wa = Warrior()
    wb = Warrior()

    str_mod = abs(wa.strength - wb.strength) // 5

if __name__=="__main__":
    main()