这是我在编程介绍中的一个问题,我不太明白如何在不使用Ifs的情况下这样做,因为我们的教授只想要基本的模数和除法。我试图获得3个输出。气球大于儿童(有效),气球等于儿童,只输出0和0,气球少于儿童,不起作用。
# number of balloons
children = int(input("Enter number of balloons: "))
# number of children coming to the party
balloons = int(input("Enter the number of children coming to the party: "))
# number of balloons each child will receive
receive_balloons = int(balloons % children)
# number of balloons leftover for decorations
remaining = children % balloons
print("{:s}""{:d}""{:s}""{:d}".format("Number of balloons for each child is ", receive_balloons, " and the amount leftover is ", remaining))
print(balloons, "", (remaining))
答案 0 :(得分:1)
您需要修改变量赋值,分配错误的变量并实际划分数字以正确获取receive_balloons
:
balloons = int(input("Enter number of balloons: "))
children = int(input("Enter the number of children coming to the party: "))
receive_balloons = balloons // children
remaining = balloons % children
# Alternatively
receive_balloons, remaining = divmod(balloons, children)
print("Number of balloons for each child is {} and the amount leftover is {}".format(receive_balloons, remaining))
输出(10/5):
Enter number of balloons: 10
Enter the number of children coming to the party: 5
Number of balloons for each child is 2 and the amount leftover is 0
输出(10/8):
Enter number of balloons: 10
Enter the number of children coming to the party: 8
Number of balloons for each child is 1 and the amount leftover is 2
注意:在Python2.7中,您应该使用raw_input
。
答案 1 :(得分:1)
您需要使用//运算符表示每个子项的气球数和剩余气球的%
# number of balloons
balloons = int(input("Enter number of balloons: "))
# number of children coming to the party
children = int(input("Enter the number of children coming to the party: "))
receive_balloons, remaining = (balloons // children, balloons % children)
print("{:s}""{:d}""{:s}""{:d}".format("Number of balloons for each child is ", receive_balloons, " and the amount leftover is ", remaining))
print(balloons, "", (remaining))