Мои отступы для моих петель выглядят странно, это нормально? (питон 2) - PullRequest
0 голосов
/ 18 апреля 2019

Я пытаюсь создать циклы, когда выполняются определенные условия, и пока что это работает, но когда я пытаюсь создать больше условий, мне нужно еще больше сделать отступ, чтобы заставить мою программу работать.

def terrain(surface):
    surface = raw_input("What surface will you be driving on? ")
    while surface != "ice" and surface != "concrete" and surface != "soil" and surface != "asphalt" :
        surface = raw_input("Surface not valid. Please enter a valid surface: ")
    if surface == "ice":
                u = raw_input("what is the velocity of the car in meters per second? ")
                u = int(u)
                while int(u) < 0:
                    u = raw_input("Velocity must be a positive integer: ")
                                while int(u) == 0:
                                    u = raw_input("Velocty must be a number greater than zero: ")
                        while int(u) > 72:
                                                                u = raw_input("This vehicle cannot reach this speed: ")
                a = raw_input("How quickly is the vehicle decelerating? ")
                a = int(a)
                while int(a) > 0:
                    a = raw_input("Deceleration cannot be a positive integer: ")
                else: 
                        s1 = u**2
                        s2 = 2*.08*9.8
                    s = s1/s2
                    print "This is how far the vehicle will travel on ice: "
                    print ("The vehicle will travel %i meters before coming to a complete stop" % (s))
terrain("ice")

Я просто хочу иметь возможность создавать больше циклов без диких отступов

Ответы [ 3 ]

0 голосов
/ 18 апреля 2019

Есть много проблем с вашим кодом, я укажу некоторые из них.Также вы должны начать использовать python3.x вместо python2. Вы можете напрямую анализировать вводимые пользователем данные как int(raw_input("xyz"))
Учитывая все вышесказанное, приведенный ниже код должен работать

import sys

def terrain():
    surface = raw_input("What surface will you be driving on? ")
    vel = -1
    while surface != "ice" and surface != "concrete" and surface != "soil" and surface != "asphalt" :
        surface = raw_input("Surface not valid. Please enter a valid surface: ")
    if surface == "ice":
        vel = int(raw_input("what is the velocity of the car in meters per second? "))
    while vel < 0:
        vel = int(raw_input("Velocity must be a positive integer: "))
    while vel == 0:
        vel = int(raw_input("Velocty must be a number greater than zero: "))
    while vel > 72:
        vel = int(raw_input("This vehicle cannot reach this speed: "))
    acc = int(raw_input("How quickly is the vehicle decelerating? "))
    while acc > 0:
        acc = int(raw_input("Deceleration cannot be a positive integer: "))

    s1 = vel**2
    s2 = 2*.08*9.8
    s = s1/s2
    print ("This is how far the vehicle will travel on ice: ")
    print ("The vehicle will travel %i meters before coming to a complete stop" % (s))

terrain()

Читайте о том, как работают отступы в python, потому что они являются способом запуска новых блоков кода, и попробуйте добавить больше условий поверх кода, который я отформатировал для вас, тогда вы сможете лучше понять его.

0 голосов
/ 18 апреля 2019
  1. Всякий раз, когда вы делаете отступ, вы всегда должны добавлять одинаковое количество отступов.Нет необходимости использовать 4 пробела в одном месте и 12 пробелов в другом месте.Наиболее распространенным соглашением является использование 4 пробелов.
  2. Добавлять уровень отступа можно только при запуске нового блока, т. Е. После строки, которая заканчивается двоеточием.
  3. При завершении блокаследующая строка должна соответствовать ключевому слову, с которого начинается этот блок.Конечно, это может означать превышение уровня более чем на один уровень, если несколько блоков заканчиваются одновременно.

Вот как может выглядеть ваш код без синтаксических ошибок, связанных с отступом:

def terrain(surface):
    surface = raw_input("What surface will you be driving on? ")
    while surface != "ice" and surface != "concrete" and surface != "soil" and surface != "asphalt" :
        surface = raw_input("Surface not valid. Please enter a valid surface: ")
    if surface == "ice":
        u = raw_input("what is the velocity of the car in meters per second? ")
        u = int(u)
        while int(u) < 0:
            u = raw_input("Velocity must be a positive integer: ")
            while int(u) == 0:
                u = raw_input("Velocty must be a number greater than zero: ")
            while int(u) > 72:
                u = raw_input("This vehicle cannot reach this speed: ")
        a = raw_input("How quickly is the vehicle decelerating? ")
        a = int(a)
        while int(a) > 0:
            a = raw_input("Deceleration cannot be a positive integer: ")
        else: 
            s1 = u**2
            s2 = 2*.08*9.8
            s = s1/s2
            print "This is how far the vehicle will travel on ice: "
            print ("The vehicle will travel %i meters before coming to a complete stop" % (s))
terrain("ice")
0 голосов
/ 18 апреля 2019

Вот что я понимаю, если я ошибаюсь:
1. получить значение для поверхности
2. если (поверхность недействительна) запросить другое значение
3. если (поверхность ледяная):
а. получить значение для u
б. получить значение для
с. рассчитать с помощью формулы
s1 = u**2
s2 = 2*.08*9.8
s = s1/s2
д. дисплей с 4. Если поверхность не айс, ничего не делайте (согласно опубликованному коду, но ее можно отредактировать так, чтобы в ней были похожие блоки, например if surface == "soil") Если так, то

def terrain():
    surface = raw_input("What surface will you be driving on? ")
    valid_surface = ["ice", "concrete", "soil", "asphalt"]
    while surface not in valid_surface:
        surface = raw_input("Surface not valid. Please enter a valid surface: ")
    if surface == "ice":
        u = raw_input("what is the velocity of the car in meters per second?")
        while int(u) < 0:
            u = raw_input("Velocity must be a positive integer: ")
        while int(u) == 0:
            u = raw_input("Velocty must be a number greater than zero: ")
        while int(u) > 72:
            u = raw_input("This vehicle cannot reach this speed: ")
        a = raw_input("How quickly is the vehicle decelerating? ")
        a = int(a)
        while int(a) > 0:
            a = raw_input("Deceleration cannot be a positive integer: ")
        while int(a) < -55: #note all while blocks are at same level
            #Do stuff  #contents inside while is indented by 4 spaces
            a = raw_input("This vehicle cannot have this deceleration. Please input another value: ")

        s1 = u**2
        s2 = 2*.08*9.8
        s = s1/s2
        print "This is how far the vehicle will travel on ice: "
        print ("The vehicle will travel %i meters before coming to a complete stop" % (s))

Я обычно определяю функцию как:

def get_int(prompt, error):
    variable = input(prompt)
    while True:
        try:
            variable = int(variable) 
        except ValueError:
            variable = input(error)
            continue
        break
    return variable

и используйте его как:

v1 = get_int("Enter value for accn: ", "Please input integer: ")
v2 = get_int("Enter value for velocity: ", "Please input integer: ")

Вам может потребоваться изменить некоторые вещи, например, изменить variable = int(variable) на variable = float(variable), если вам нужно принять плавающее (например, 1,25) значение.

...