在python 3中实现((n-1)(n))/ 2

时间:2017-08-28 02:16:26

标签: python python-3.x

根据人数计算房间内独特握手的数量。其中n是人数。

我正在尝试计算给定房间中人们交换的握手数量,考虑到python中的人数。这是用Python 3编写的。

people = input("How many people were there?")
no_handshakes = ((people - 1) *people)/2
print("No. of people: ", people)
print("No. of handshakes: ", no_handshakes)

当我在python shell中运行此代码时,它会生成此错误。

Traceback (most recent call last):
  File "C:\Users\Tanaka\Desktop\Cloud\python101\peoplehandshakescalculator.py", line 2, in <module>
    no_handshakes = ((people - 1) *people)/2
TypeError: unsupported operand type(s) for -: 'str' and 'int'

1 个答案:

答案 0 :(得分:0)

人们手动输入people var作为字符串,因此有必要使用

将其转换为整数/数字
int()

然后指令将无缝执行,如下所示。

    people = input("How many people were there?")
    no_handshakes = ((int(people)-1)*int(people))/2

    print("No. of people: ", people)
    print("No. of handshakes: ", no_handshakes)