Как вычислить площадь и отформатировать ее в виде таблицы? - PullRequest
0 голосов
/ 13 июля 2020

Это моя домашняя работа:

Напишите программу, которая вычисляет площадь квадрата, треугольника, круга и прямоугольника. Затем программа распечатает результат в красиво отформатированной таблице, как показано в примере ниже. Ваша программа должна быть реализована как минимум с 3 функциями и строками документации. Вы должны создать новый модуль «area_tools» со следующими функциями: Square(base), Triangle(base,height), Circle(radius) и Rectangle(base,height). Ваша основная программа должна использовать функции вашего модуля.

Example of the table:

Vars | square | Triangle | circle | rectangle

10,10 | 100 | ??? | 345.56 | 4567

Я знаю, что сделал это неправильно, и не знаю, как go отсюда. Я получаю сообщение об ошибке:

TypeError: Square() missing 1 required positional argument: 'base'

Я действительно не знаю, что делать. Это то, что я делал до сих пор. В файле с именем area_tools.py я сделал это:

 def Triangle():
    '''Finds the area of the triangle'''
    base = int(input("Enter the base: "))
    height = int(input("Enter the height: "))
    triangle_area = (base * height) / 2
    return triangle_area

def Rectangle():
    '''Finds the area of the rectangle'''
    base = int(input("Enter the base: "))
    height = int(input("Enter the height: "))
    rectangle_area = base * height
    return rectangle_area

def Circle():
    '''Finds the area of the circle'''
    radius = int(input("Enter the radius: "))
    pi = 3.14159
    circle_area = pi * radius ** 2
    return circle_area

def Square():
  base = int(input("Enter the base: "))
  square_area = base ** 2
  return square_area

Во втором файле я сделал следующее:

import area_tools
import pandas as pd

data = {'square': [Square()],
        'triangle': [Triangle()],
        'circle': [Circle()],
        'rectangle': [Rectangle()],
        }

df = pd.DataFrame(data,columns=['square', 'triangle', 'circle','rectangle'])
df

РЕДАКТИРОВАТЬ: Я скопировал и вставил здесь код, поэтому легче понять, о чем я говорю: https://repl.it/@fgffdsfj / StrangeInfantileDisks # main.py

Ответы [ 2 ]

2 голосов
/ 13 июля 2020

В втором файле при вызове функции вы не отправляли аргумент функции, поэтому она возвращает ошибку

Вы можете удалить аргумент функции в первом файле и получить вместо этого

def Triangle():
    '''Finds the area of the triangle'''
    base = int(input("Enter the base: "))
    height = int(input("Enter the height: "))
    triangle_area = (base * height) / 2
    return triangle_area

def Rectangle():
    '''Finds the area of the rectangle'''
    base = int(input("Enter the base: "))
    height = int(input("Enter the height: "))
    rectangle_area = base * height
    return rect_area

def Circle():
    '''Finds the area of the circle'''
    radius = int(input("Enter the radius: "))
    circle_area = pow(math.pi * radius, 2)
    return circle_area
1 голос
/ 13 июля 2020

Вы должны использовать input() вне своих функций и отправлять значения в качестве аргументов

def Triangle(base, height):
    '''Finds the area of the triangle'''
    return base * height / 2

def Rectangle(base, height):
    '''Finds the area of the rectangle'''
    return base * height

def Circle(radius):
    '''Finds the area of the circle'''
    pi = 3.14159
    return pi * radius ** 2

def Square(base):
    return base ** 2

my_base   = int(input("Enter the base/width/radius: "))
my_height = int(input("Enter the height: "))
#my_radius = int(input("Enter the radius: "))

# only for fast test
#my_base   = 3
#my_height = 4

result_square = Square(my_base)
result_triangle = Triangle(my_base, my_height)
result_circle = Circle(my_base)
result_rectangle = Rectangle(my_base, my_height)

А позже вы можете использовать форматирование строки (выравнивание по левому краю, правому краю или центру) для создания таблицы.

print('| {:^7} | {:^10} | {:^10} | {:^10} | {:^10} |'.format('Vars', 'Square', 'Triangle', 'Circle', 'Rectangle'))
print('| {:>3},{:<3} | {:^10} | {:^10} | {:^10} | {:^10} |'.format(my_base, my_height, result_square, result_triangle, result_circle, result_rectangle))

Результат

|  Vars   |   Square   |  Triangle  |   Circle   | Rectangle  |
|   3,4   |     9      |    6.0     |  28.27431  |     12     |

Подробнее о форматировании строк в PyFormat.info

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...