пока цикл в питоне не останавливается - PullRequest
2 голосов
/ 24 сентября 2019

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


print("what is your name")
name = input("")
print("hello " + name)
print("how many inventory items do you want to buy")
items = input()
while (items > 0):
         print("what is the inventory number of the item")
         inventoryNum = int(input())
         if (inventoryNum >= 1000 and inventoryNum <= 1999 ):
             print("the item is on the lower level")

         elif (inventoryNum == 8005 or inventoryNum == 8000):
             print("the item is on the mezzanine")

         elif (inventoryNum > 1999 and inventoryNum <= 5000 or inventoryNum > 9000):
             print("the item is on the main floor")

         elif (inventoryNum > 5000 and inventoryNum <= 9000 and inventoryNum != 8005 and inventoryNum != 8000):
             print("the item is on the upper level")
             items = items - 1

Ответы [ 4 ]

1 голос
/ 24 сентября 2019

Другим способом решения этой проблемы может быть создание функции для запроса, хотите ли вы продолжить выполнение программы, например:

def Continue():
   answer = input("Do you want to continue? (Yes/No - Y/N)")
      if(answer == "Yes" or answer == "Y"):
         pass
      elif(answer == "No" or answer == "N"):
         print("Goodbye")
         sys.exit();

Я заметил, что ваши операторы if не имеют каких-либоточка завершения, например, в if < 1000, так что каждый раз, когда вы вводите любое значение, меньшее этого интервала, который вы должны вводить снова и снова, я исправлял ваши входные данные (как это уже делали некоторые помощники выше) иВы должны поставить еще один оператор в финал, когда ваш инвентарный номер не относится ни к одной категории:

name = input("what is your name: ")
print("hello " + name)
items = int(input("how many inventory items do you want to buy: "))
while (items > 0):
         inventoryNum = int(input("what is the inventory number of the item: "))
         if (inventoryNum >= 1000 and inventoryNum <= 1999):
             print("the item is on the lower level")
             Continue()
         elif (inventoryNum > 1999 and inventoryNum <= 5000 or inventoryNum > 9000):
             print("the item is on the main floor")
             Continue()
         elif (inventoryNum == 8005 or inventoryNum == 8000):
             print("the item is on the mezzanine")
             Continue()
         elif (inventoryNum > 5000 and inventoryNum <= 9000 and inventoryNum != 8005 and inventoryNum != 8000):
             print("the item is on the upper level")
             Continue()
         else:
             print("item is not registered")
             Continue()
             items = items - 1

Таким образом, каждый раз, когда вы вводите Да, он продолжается, в противном случае он закрывает приложение

1 голос
/ 24 сентября 2019

Посмотрите на код ниже.В основном в вашем коде есть две проблемы, которые комментируются:

print("what is your name")
name = input("")
print("hello " + name)
print("how many inventory items do you want to buy")
items = int(input()) #You forgot to convert the input from str to int
while (items > 0):
    print("what is the inventory number of the item")
    inventoryNum = int(input())
    if (inventoryNum >= 1000 and inventoryNum <= 1999):
        print("the item is on the lower level")

    elif (inventoryNum == 8005 or inventoryNum == 8000):
        print("the item is on the mezzanine")

    elif (inventoryNum > 1999 and inventoryNum <= 5000 or inventoryNum > 9000):
        print("the item is on the main floor")

    elif (inventoryNum > 5000 and inventoryNum <= 9000 and inventoryNum != 8005 and inventoryNum != 8000):
        print("the item is on the upper level")
    #you put the code in the scope of elif; it should be in the scope of while loop.
    #the problem arised due to the indentation.
    items = items - 1
1 голос
/ 24 сентября 2019

Я вижу вашу проблему и заметил несколько вещей:

  1. Первая проблема незначительна, но может быть быстро исправлена:
items = input()

Этодолжно быть:

items = int(input())

Поскольку всякий раз, когда мы хотим получить значение из входной функции, мы собираемся получить строковый тип, независимо от того, передаете ли вы через него число.Чтобы исправить это, мы превращаем строку в целое число, помещая перед ней int

Упрощение кода и проблема отступа:
print("what is the inventory number of the item")
inventoryNum = int(input())

Можно упростить до:

inventoryNum = int(input("What is the inventory number of the item: "))

-Кроме того, в конце, так как кажется, что все элементыкоторые не являются частью первых трех условий, связанных с inventoryNum, находятся на первом этаже, вы можете просто использовать оператор else.Вот так:

if(inventoryNum >= 1000 and inventoryNum <= 1999):
        print("The item is on the lower level")
    elif(inventoryNum == 8005 or inventoryNum == 8000):
        print("The item is on the mezzanine")
    elif(inventoryNum > 1999 and inventoryNum <= 5000) or (inventoryNum>9000):
        print("The item is on the main floor")
    else:
        print("The item is on the upper level")
Наконец, для того, чтобы цикл while работал, уменьшение значения элемента на 1 должно иметь отступ снаружи, иначе значение будет уменьшаться только на единицу, когда один из операторов elif является путем, по которому он идет:
   print("the item is on the upper level")
             items = items - 1

Должно быть:

    inventoryNum = int(input("What is the inventory number of the item: "))

    if(inventoryNum >= 1000 and inventoryNum <= 1999):
        print("The item is on the lower level")
    elif(inventoryNum == 8005 or inventoryNum == 8000):
        print("The item is on the mezzanine")
    elif(inventoryNum > 1999 and inventoryNum <= 5000) or (inventoryNum>9000):
        print("The item is on the main floor")
    else:
        print("The item is on the upper level")
    #items -= 1 is indented outside of the if/elif/else statement since you want the value of items to decrease after each iteration    
    items -= 1 #Simpler way of saying items = items - 1, works with + and / as well

print("All items registered. End of program") #Thought that this would be a nice way of notifying the user that they've reached the end of the program 

Надеюсь, это поможет.

1 голос
/ 24 сентября 2019

Это просто проблема с отступом. Outdent ваш items = items - 1, поскольку он находится внутри вашего последнего elif заявления.

while (items > 0):
  print("what is the inventory number of the item")
  inventoryNum = int(input())
  if (inventoryNum >= 1000 and inventoryNum <= 1999 ):
      print("the item is on the lower level")

  elif (inventoryNum == 8005 or inventoryNum == 8000):
      print("the item is on the mezzanine")

  elif (inventoryNum > 1999 and inventoryNum <= 5000 or inventoryNum > 9000):
      print("the item is on the main floor")

  elif (inventoryNum > 5000 and inventoryNum <= 9000 and inventoryNum != 8005 and inventoryNum != 8000):
      print("the item is on the upper level")
  items = items - 1
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...