如何在Python中获取两个输入变量的差值

0 投票
2 回答
5268 浏览
提问于 2025-04-18 02:35

我现在正在用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

代码结构非常重要,它能让你的程序更容易理解和维护:

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()
1

只需要使用 - 这个符号,然后用 abs() 函数来计算两个数字之间的差值。

abs(StrengthA - StrengthB)

不过,你首先得确保你用的是整数。可以通过以下方法来确认:

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

补充:

如果想要把结果除以五,只需要这样做:

(abs(StrengthA - StrengthB)) / 5

撰写回答