2013-10-03 4 views
0

Я пытаюсь сделать эту программу на Python, которая запрашивает площадь поверхности и объем цилиндра. В конце он запрашивает у пользователя, хочет ли он рассчитать объем/площадь поверхности. Однако, если они вводят Да, ничего не происходит. Что не так с моим кодом?Почему Python внезапно останавливается, если вход Yes?

Во-вторых, я пытаюсь использовать math.pi, но это не сработало, что мне делать.

Код долго так только прокрутите вниз до важных частей:

print("Welcome to the volume and surface area cylinder calculator powered by Python!") 
response = input("To calculate the volume type in 'vol', to calculate the surface area, type in 'SA': ") 
if response=="vol" or response =="SA": 
    pass 
else: 
    print("Please enter a correct statement.") 
    response = input("To calculate the volume type in 'vol', to calculate the surface area, type in 'SA': ") 

if response=="vol": 
    #Below splits 
    radius, height = [float(part) for part in input("What is the radius and height of the cylinder? (e.g. 32, 15): ").split(',')] 
    PI = 3.141592653589793238462643383279502884197169399375105820974944592307816406286 
    volume = PI*radius*radius*height 
    decimal_places = int(input("How many decimal places do you want it to?: ")) 
    print("The volume of the cylinder is {0:.{1}f}cm\u00b3".format(volume, decimal_places)) 
    verify = input("Do you want to find out the surface area (type in Yes or No): ") 
    verify = verify.capitalize 
    if verify == "Yes": 
     radius, height = [float(part) for part in input("What is the radius and height of the cylinder? (e.g. 32, 15): ").split(',')] 
     PI = 3.141592653589793238462643383279502884197169399375105820974944592307816406286 
     SA = int(2)*PI*radius*radius+int(2)+radius*radius*height 
     decimal_places = int(input("How many decimal places do you want it to?: ")) 
     print("The surface area of the cylinder is {0:.{1}f}cm\u00b2".format(SA, decimal_places)) 
    if verify == "No": 
     pass 

if response =="SA": 
    #Below splits 
    radius, height = [float(part) for part in input("What is the radius and height of the cylinder? (e.g. 32, 15): ").split(',')] 
    PI = 3.141592653589793238462643383279502884197169399375105820974944592307816406286 
    SA = int(2)*PI*radius*radius+int(2)+radius*radius*height 
    decimal_places = int(input("How many decimal places do you want it to?: ")) 
    print("The surface area of the cylinder is {0:.{1}f}cm\u00b2".format(SA, decimal_places)) 
    verify = input("Do you want to find out the volume (type in Yes or No): ") 
    verify = verify.capitalize 
    if verify == "Yes": 
     radius, height = [float(part) for part in input("What is the radius and height of the cylinder? (e.g. 32, 15): ").split(',')] 
     PI = 3.141592653589793238462643383279502884197169399375105820974944592307816406286 
     volume = PI*radius*radius*height 
     decimal_places = int(input("How many decimal places do you want it to?: ")) 
     print("The volume of the cylinder is {0:.{1}f}cm\u00b3".format(volume, decimal_places)) 
    if verify == "No": 
     pass 
+0

«Я пытаюсь использовать math.pi, но это не сработало». При обращении за помощью вам нужно быть более конкретным. – SethMMorton

+0

Также, святая копия и вставка, Бэтмен! Даже если 'math.pi' не работает, почему вы считали, что вам нужно переопределить' PI' 4 раза? – SethMMorton

ответ

0

Это моя отлажены версия. Это позволяет избежать много повторений.

from math import pi 

print("Welcome to the volume and surface area cylinder calculator powered by Python!") 
response = raw_input("To calculate the volume type in 'vol', to calculate the surface area, type in 'SA': ").lower() 
while response not in ["vol", "sa"]: 
    print("Please enter a correct statement.") 
    response = raw_input("To calculate the volume type in 'vol', to calculate the surface area, type in 'SA': ").lower() 

radius, height = [float(part) for part in raw_input("What is the radius and height of the cylinder? (e.g. 32, 15): ").split(',')] 

r2 = radius ** 2 
SA = 2 * pi * r2 + 2 + pi * radius * height 
volume = pi * r2 * height 

decimal_places = int(raw_input("How many decimal places do you want it to?: ")) 

if response=="vol": 
    print("The volume of the cylinder is {0:.{1}f}cm\u00b3".format(volume, decimal_places)) 
    verify = raw_input("Do you want to find out the surface area (type in Yes or No): ") 
    if verify.lower() == "yes": 
     print("The surface area of the cylinder is {0:.{1}f}cm\u00b2".format(SA, decimal_places)) 

if response =="sa": 
    print("The surface area of the cylinder is {0:.{1}f}cm\u00b2".format(SA, decimal_places)) 
    verify = raw_input("Do you want to find out the volume (type in Yes or No): ") 
    if verify.lower() == "yes": 
     print("The volume of the cylinder is {0:.{1}f}cm\u00b3".format(volume, decimal_places)) 
+0

Примечание: raw_input() был изменен для ввода в Python 3.x – Turbo

+0

Я лично чувствовал, что этот ответ был лучшим, поскольку я мог бы сделать прямое сравнение с моим и посмотреть, что я мог бы улучшить. Отличная работа Грэм Стюарт! – Turbo

3

Вы заменили verify с методом:

verify = verify.capitalize 

Это никогда не будет соответствовать либо 'Yes' или 'No', потому что это уже не строка. Вызов метода вместо:

verify = verify.capitalize() 

Обратите внимание, что ваш тест на "No" только может быть отброшено, нет смысла в тестировании на строку, то просто pass Инг.

Использование math.pi вместо PI иначе работает просто отлично:

>>> import math 
>>> math.pi 
3.141592653589793 
>>> radius, height = 32, 15 
>>> 2 * math.pi * radius ** 2 + 2 * math.pi * radius * height 
9449.910701998098 
>>> math.pi * radius ** 2 * height 
48254.86315913922 
+0

только что из любопытства, я не знаю, python.in python «да» = «ДА»? –

+0

Как заменить все числа на math.pi? Во-вторых, как я могу заставить его выйти, если проверить == «Нет»? Если я попробую импортировать sys sys.exit(), это не сработает? Еще раз спасибо – Turbo

+0

@KaushikSivakumar: это не так. Строки сопоставляются случайным образом. –