为啥我的代码跑起来一直是请输入书名?
books = []
num = 0
choice = 1
while 1:
if num < 3:
while choice:
name = input('请输入书名:')
for book in books:
if book.get('书名') == name:
print('添加书名重复,重新添加')
else:
choice = 0
break
author = input('请输入作者:')
price = input('请输入价格:')
books.append({'书名': name, '作者': author, '价格': price})
num += 1
print(books)
else:
print('图书信息添加完成!')
print(books)
break
我的想法是如果书名输入不重复choice重新赋值为0,while循环跳出,break跳出for循环
判断输入的书名是否重复,如果重复提示重新输入,不重复继续输入作者和价格
books = []
num = 0
choice = 1
while 1:
if num < 3:
choice = 1
while choice:
name = input('请输入书名:')
for book in books:
if book.get('书名') == name:
print('添加书名重复,重新添加')
break
else:
choice = 0
break
author = input('请输入作者:')
price = input('请输入价格:')
books.append({'书名': name, '作者': author, '价格': price})
num += 1
print(books)
books = [{'书名': 'sun', '作者': 'sun', '价格': '12'},{'书名': 'li', '作者': 'li', '价格': '12'}]
choice=1
num=0
def _append(name,num,books):
author = input('请输入作者:')
price = input('请输入价格:')
books.append({'书名': name, '作者': author, '价格': price})
num += 1
if num < 3:#不知道为啥,只存三本书?
while choice:
needadd=1
name = input('请输入书名:')
for i in books:
if name in i.get('书名'):
print("添加书名重复,重新添加")
needadd=0
if needadd==1:
_append(name,num,books)
choice = 0
break
else:
print("num>3")
print('图书信息添加完成!')
print(books)
这样也是一样的
books = [{'书名': 'sun', '作者': 'sun', '价格': '12'},{'书名': 'li', '作者': 'li', '价格': '12'}]
choice=1
num=0
if num < 3:#不知道为啥,只存三本书?
while choice:
needadd=1
name = input('请输入书名:')
for i in books:
if name in i.get('书名'):
print("添加书名重复,重新添加")
needadd=0
if needadd==1:
author = input('请输入作者:')
price = input('请输入价格:')
books.append({'书名': name, '作者': author, '价格': price})
num += 1
choice = 0
break
else:
print("num>3")
print('图书信息添加完成!')
print(books)