Итак, я пытаюсь завершить цикл while при вводе пробела для ввода, но проблема в том, что ввод принимает 2 значения, разделенные ",". Мне необходимо сохранить ввод таким образом, а не разделять их, так как это исправить?
print(" Input the productIDs and quantities (input blank to complete transaction)")
productID, quantity = input().split(", ")
quantity = int(quantity)
while quantity >= 1:
self.addProductToTransaction(productID, quantity)
print("why u here bro u ain't buyin nothin")
Когда ввод пуст:
ValueError: not enough values to unpack (expected 2, got 1)
4 ответа
Мне удалось исправить это с помощью try/except.
print(" Input the productIDs and quantities (input blank to complete transaction)")
try:
productID, quantity = input().split(", ")
quantity = int(quantity)
while quantity >= 1:
self.addProductToTransaction(productID, quantity)
except:
print("why u here bro u ain't buyin nothin")
while loop
должен быть внешним, если вы хотите итеративно получать ввод до тех пор, пока не будет передан неверный формат (обрабатывается try-except
).
while True:
try:
productID, quantity = input("Input the productIDs and quantities (input blank to complete transaction)").split(", ")
except ValueError:
print("why u here bro u ain't buyin nothin")
break
if quantity >= 1:
self.addProductToTransaction(productID, quantity)
Вам даже не нужна обработка исключений. Просто возьмите строку, а затем разделите на '
print(" Input the productIDs and quantities (input blank to complete transaction)")
user_in = input()
if user_in !='':
productID, quantity = user_in.split(',')
print(quantity)
quantity = int(quantity)
while quantity >= 1:
self.addProductToTransaction(productID, quantity)
else:
print("why u here bro u ain't buyin nothin")
Пробные выходы #
Input the productIDs and quantities (input blank to complete transaction)
why u here bro u ain't buyin nothin
Есть три способа сделать это. Использование len()
или с try..except
или с if
если
while True:
var = input("Input the productIDs and quantities (input blank to complete transaction)")
if len(var) == ‘’:
print("why u here bro u ain't buyin nothin")
break
productID, quantity = Var.split(", ")
quantity = int(quantity)
if quantity >= 1:
self.addProductToTransaction(productID, quantity)
LEN ( )
while True:
var = input("Input the productIDs and quantities (input blank to complete transaction)")
if len(var) == 0:
print("why u here bro u ain't buyin nothin")
break
productID, quantity = Var.split(", ")
quantity = int(quantity)
if quantity >= 1:
self.addProductToTransaction(productID, quantity)
попробуй… кроме
while True:
try:
productID, quantity = input("Input the productIDs and quantities (input blank to complete transaction)").split(", ")
quantity = int(quantity)
if quantity >= 1:
self.addProductToTransaction(productID, quantity)
except ValueError:
print("why u here bro u ain't buyin nothin")
break
Три ноты:
- Если вы печатаете сообщение для ввода, передайте строку в функцию ввода. И если вы хотите, чтобы пользователь вводил в следующей строке, передайте escape-чат новой строки в строке
"Foo..string\n"
- Я думаю 🤔 вы пытаетесь создать цикл, который неоднократно запрашивает у пользователя ввод, а затем передает его другой функции класса
addProductToTransaction()
. Если ничего не передано, в этом случае выходим из цикла. Для этого вы можете поставить цикл перед вводом. - Приведенные выше решения упорядочены в соответствии с предпочтениями и производительностью (от высокого к низкому).
Похожие вопросы
Новые вопросы
python
Python — это мультипарадигмальный многоцелевой язык программирования с динамической типизацией. Он предназначен для быстрого изучения, понимания и использования, а также обеспечивает чистый и унифицированный синтаксис. Обратите внимание, что Python 2 официально не поддерживается с 01.01.2020. Если у вас есть вопросы о версии Python, добавьте тег [python-2.7] или [python-3.x]. При использовании варианта Python (например, Jython, PyPy) или библиотеки (например, Pandas, NumPy) укажите это в тегах.