Python函数返回一个奇怪的字符串

时间:2018-02-07 19:25:18

标签: python

在我尝试学习Python时,我正在编写一本名为“练习程序员”的书。

https://pragprog.com/book/bhwb/exercises-for-programmers

在练习8中,我遇到了一些麻烦;我打算编写一些代码,提示有多少人要点披萨,每个多少片,然后必须根据切片总数(每个人*切片)计算必须订购的披萨数量(1披萨= 8片) )和剩余切片的数量(如果有的话)。

我认为我已经设法将其排除在外,但是一旦执行了计算剩余切片数量的方法就会打印出一个奇怪的字符串(它还包含一个十六进制值?)。

我已将所有内容调整为两个文件(试图建立良好的习惯);

文件01:

main.py

import pizza as p

while True:

number_of_people = input("How many people are hungry for pizza? ")
number_of_slices_per_person = input("And how many slices per person? ")

try:
    val = int(number_of_people) or int(number_of_slices_per_person)

    print("\n" + number_of_people + " people have ordered " +
          str(p.number_of_pizzas(number_of_people, number_of_slices_per_person)) + " pizzas.")

    if int(number_of_slices_per_person) == 1:
        print("Each person would like just a " + number_of_slices_per_person + " slice of pizza.")
    else:
        print("Each person would like " + number_of_slices_per_person + " slices of pizza.")

    print("There are " + str(p.number_of_leftover_slices) + " pizza slices left over.")
    break
except ValueError:
    print("Please enter a valid number")

文件02:

pizza.py

def number_of_pizzas(p1, s1):
    """Calculates the number of pizzas according to the specified 
    requirements"""
    total_pizzas = 0
    total_slices = int(p1) * int(s1)
    for s2 in range(0, total_slices):
        if s2 % 8 == 0:
            total_pizzas = total_pizzas + 1
return total_pizzas


def number_of_leftover_slices(total_pizzas):
    """Calculate the number of leftover slices of pizza"""
    import main as m
    total_pizzas = total_pizzas
    leftover_slices = (int(total_pizzas) * 8) % 
        int(m.number_of_slices_per_person)
return leftover_slices

这是我得到的输出;

'4 people have ordered 2 pizzas.'

'Each person would like 3 slices of pizza.'

'There are < function number_of_leftover_slices at 0x7f0a95e2c7b8 > pizza slices left over.'

我的问题是打印的字符串而不是我预计会计算的数字。对我可能做错了什么的想法?

感谢。

1 个答案:

答案 0 :(得分:1)

你有两个问题。首先,您需要在return

的末尾缩进number_of_leftover_slices

接下来,当您在对象上调用print时,Python将尝试使用该对象的_repr__str_方法来获取该对象的字符串表示形式。您所看到的是number_of_leftover_slices 功能的字符串表示形式。您要打印的内容实际上是该函数的输出。

n = p.number_of_pizzas(number_of_people, number_of_slices_per_person)
remain = p.number_of_leftover_slices(n)
print(remain)