2016-02-24 2 views
1

Краткое описание моей программы, которую я пытаюсь написать. Он предназначен для расчета траектории пушечного шара на основе пользовательских входов для начальной скорости и начального угла траектории. У пользователя три попытки ввести действительные входы до выхода программы. В случае успеха он попросит пользователя, что они хотят рассчитать (время полета, максимальная высота или максимальный горизонтальный диапазон). Затем программа отобразит вычисленный ответ и время, необходимое для достижения максимальной высоты для любого из вариантов пользователя.Ending A Loop in Python 3.x

Две проблемы могут быть найдены в комментариях в коде ...

# Constant(s) 
GRAV = 9.8 

# Accumulator variable(s) 
InvalEntry1 = 0 
Success = 0 

import math 

# Defining functions to calculate max height (hMax), total travel time (tTime), and max range (rMax) 
def hMax(): 
    height = ((iVelocity**2) * math.pow(math.sin(math.radians(iTrajectory)), 2))/(2 * GRAV) 
    return height 

def tTime(): 
    time = (2* iVelocity * (math.sin(math.radians(iTrajectory))))/GRAV 
    return time 

def rMax(): 
    rangeMax = ((iVelocity**2) * math.sin(math.radians(2 * iTrajectory)))/GRAV 
    return rangeMax 

# Assigning user inputs for the initial velocity and initial trajectory to variables 
iVelocity = float(input('Please Enter an Initial Velocity Between 20 to 800 m/s: ')) 
iTrajectory = float(input('Please Enter a Initial Trajectory Angle Between 5 to 80 Degrees: ')) 

print ('\n') 


# FIRST PROBLEM... I am having trouble with this loop. If the user enters 
# valid numbers on the third attempt, the program will shut down regardless. 
# OR if they enter invalid numbers on the third attempt, it will display 
# the warning message again, even though they are out of attempts when the 
# program should shut down. Lastly, if valid numbers are entered on the 
# second attempt, it will continue to the next input function, but will 
# still display the warning message. 


# Giving the user 3 attempts at providing valid inputs 
while (InvalEntry1 < 3): 

    # Determining if user inputs are valid 
    if (iVelocity < 20) or (iVelocity > 800) or (iTrajectory < 5) or (iTrajectory > 80): 
     print ('INVALID ENTRY\n') 
     InvalEntry1 = InvalEntry1 + 1 
     iVelocity = float(input('Please Enter an Initial Velocity Between 20 to 800 m/s: ')) 
     iTrajectory = float(input('Please Enter a Initial Trajectory Angle Between 5 to 80 Degrees: ')) 
     print ('\n======================================================================') 
     print ('WARNING!!! You have ONE attempt left to input a correct number for') 
     print ('initial velocity and initial trajectory before the program will quit.') 
     print ('======================================================================\n') 

    else: 
     # Determining what the user wants to calculate 
     print ('What would you like the program to calculate?') 
     uCalculate = int(input('Enter 1 for Max Height, 2 for Time, or 3 for Max Horizontal Range: ')) 
     print ('\n') 


     # SECOND PROBLEM... after the user successfully inputs the 
     # correct numbers and the program displays the answers using the 
     # functions, instead of ending the program, it loops back to 
     # the else statement above. I can't seem to figure out how to 
     # close the loop and end the program. I tried using 
     # while (Success < 1): to close the loop, but it continues to 
     # loop anyways. 


     # Determining which variable(s) the user wants the program to calculate 

     if (uCalculate == 1): 
      print ('Maximum Height = %.2f' %(hMax())) 
      print ('Total Time = %.2f' %(tTime())) 
      Success = Success + 1 

     elif (uCalculate == 2): 
      print ('Total Time = %.2f' %(tTime())) 
      Success = Success + 1 

     elif (uCalculate == 3): 
      print ('Maximum Horizontal Range = %.2f' %(rMax())) 
      print ('Total Flight Time = %.2f' %(tTime())) 
      Success = Success + 1 

     else: 
      print ('INVALID ENTRY') 

Спасибо заранее за любую помощь или совет вы можете дать.

+1

Пожалуйста отступы ваш код правильно. То, что вы опубликовали, не может работать. Также, пожалуйста, напишите КОРОТКОЙ фрагмент кода, который вы можете собрать, что показывает проблему, о которой вы просите. – kindall

+0

Я исправил ошибки в отступлении (извините, переместить его с python на здесь может быть сложно). Если я сломаю код еще больше, и вы попытаетесь его запустить, разве это не даст вам ошибок, потому что определенные вещи не будут определены? – MikeD

+0

По крайней мере, вам не нужен оператор if/elif/else 4-case, чтобы продемонстрировать вашу проблему. Это ненужные детали, которые вы можете удалить из [минимального, полного и проверяемого примера] (http://stackoverflow.com/help/mcve). – chepner

ответ

1

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

Чтобы повторить вашу проблему в более абстрактных, многоразовых терминах. У вас есть функция, требующая ввода пользователем. Вы хотите проверить, используя следующее: Если вход действителен, вы хотите, чтобы программа продолжалась. Если вход недействителен, вы хотите предупредить пользователя и повторить его. Если входной сигнал по-прежнему недействителен после x попыток, вы хотите, чтобы программа завершила работу. Это общий сценарий, и есть несколько идиом программирования или шаблонов, которые можно использовать. Вот один простой.

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

Во-вторых, используйте цикл петли и половины шаблона в любое время, когда вам нужно проверить состояние, а затем продолжить lopping, пока условие ложно. На других языках вы можете реализовать это, используя цикл do...while, но Python имеет только while.

Вот пример кода.

def get_user_input(): 
    in1 = input("Please enter height") 
    in2 = input("Please enter weight") 
    return in1, in2 


def validate_user_input(x, y): 
    try: 
     # validation code for x 
     _ = int(x) 
    except: 
     return False 
    try: 
     # validation code for y 
     _ = int(y) 
    except: 
     return False 

    # if we get here than all inputs are good 
    return True 


def ask_user(): 
    # Loop and a half pattern 

    max_tries = 3 


    val1, val2 = get_user_input() 
    tries = 1 
    while validate_user_input(val1, val2) is False: 
     if tries >= max_tries: 
      quit("Max tries exceeded") 
     print("Invalid input. Please try again. You have {} attempts remaining".format(max_tries - tries)) 
     tries += 1 
     val1, val2 = get_user_input() 

    # if we get here, input is validated and program can continue 
    print('Thank You') 


if __name__ == '__main__': 
    ask_user() 

Защиту get_user_input():

0

добавлено 2, если заявления проверить if the last attempt left to display warning message и if the run was Successful to exit program

пожалуйста, обратитесь к ### объяснения комментарии

# Constant(s) 
GRAV = 9.8 

# Accumulator variable(s) 
InvalEntry1 = 0 
Success = 0 

import math 

# Defining functions to calculate max height (hMax), total travel time (tTime), and max range (rMax) 
def hMax(): 
    height = ((iVelocity**2) * math.pow(math.sin(math.radians(iTrajectory)), 2))/(2 * GRAV) 
    return height 

def tTime(): 
    time = (2* iVelocity * (math.sin(math.radians(iTrajectory))))/GRAV 
    return time 

def rMax(): 
    rangeMax = ((iVelocity**2) * math.sin(math.radians(2 * iTrajectory)))/GRAV 
    return rangeMax 



# Assigning user inputs for the initial velocity and initial trajectory to variables 
iVelocity = float(input('Please Enter an Initial Velocity Between 20 to 800 m/s: ')) 
iTrajectory = float(input('Please Enter a Initial Trajectory Angle Between 5 to 80 Degrees: ')) 

print ('\n') 


# FIRST PROBLEM... I am having trouble with this loop. If the user enters 
# valid numbers on the third attempt, the program will shut down regardless. 
# OR if they enter invalid numbers on the third attempt, it will display 
# the warning message again, even though they are out of attempts when the 
# program should shut down. Lastly, if valid numbers are entered on the 
# second attempt, it will continue to the next input function, but will 
# still display the warning message. 


# Giving the user 3 attempts at providing valid inputs 
while (InvalEntry1 < 3): 


    ### adding if statement to check of the next attempt is last: 
    if InvalEntry1 == 2 : 
     print ('\n======================================================================') 
     print ('WARNING!!! You have ONE attempt left to input a correct number for') 
     print ('initial velocity and initial trajectory before the program will quit.') 
     print ('======================================================================\n') 

    # Determining if user inputs are valid 
    if (iVelocity < 20) or (iVelocity > 800) or (iTrajectory < 5) or (iTrajectory > 80): 
     print ('INVALID ENTRY\n') 
     InvalEntry1 = InvalEntry1 + 1 


     iVelocity = float(input('Please Enter an Initial Velocity Between 20 to 800 m/s: ')) 
     iTrajectory = float(input('Please Enter a Initial Trajectory Angle Between 5 to 80 Degrees: ')) 

    else: 
     # Determining what the user wants to calculate 
     print ('What would you like the program to calculate?') 
     uCalculate = int(input('Enter 1 for Max Height, 2 for Time, or 3 for Max Horizontal Range: ')) 
     print ('\n') 


     # SECOND PROBLEM... after the user successfully inputs the 
     # correct numbers and the program displays the answers using the 
     # functions, instead of ending the program, it loops back to 
     # the else statement above. I can't seem to figure out how to 
     # close the loop and end the program. I tried using 
     # while (Success < 1): to close the loop, but it continues to 
     # loop anyways. 


     # Determining which variable(s) the user wants the program to calculate 

     if (uCalculate == 1): 
      print ('Maximum Height = %.2f' %(hMax())) 
      print ('Total Time = %.2f' %(tTime())) 
      Success = Success + 1 

     elif (uCalculate == 2): 
      print ('Total Time = %.2f' %(tTime())) 
      Success = Success + 1 

     elif (uCalculate == 3): 
      print ('Maximum Horizontal Range = %.2f' %(rMax())) 
      print ('Total Flight Time = %.2f' %(tTime())) 
      Success = Success + 1 

     else: 
      print ('INVALID ENTRY') 

      ### i advice to add here InvalEntry1 += 1 
      #InvalEntry1 = InvalEntry1 + 1 

     ### if success - exit while loop 

     if Success > 0 : 
      print ('Goodbye') 
      break 
+0

согласно моей политике минимальных изменений – Trigremm