python - 为什么我不能在这里调用函数?
问题描述
大家好,我正在编写购物清单创建者代码,但最后我遇到了一个惊喜。
我的代码:
import time
import math
import random
dict_of_lists={}
def addlist():
while True:
try:
listname=str(raw_input("=>Name of the list:\n"))
dict_of_lists[listname]={}
break
except ValueError:
print "=>Please enter a valid name.\n"
print "=>You added a new list named %s.\n" % (listname)
def printlists():
for lists in dict_of_lists:
return "-"+lists
def addproduct():
while True:
try:
reachlistname=input("=>Name of the list you want to add a product,Available lists are these:\n %s \nPlease enter one:\n" % (printlists()))
break
except ValueError:
print "=>Please enter a valid list name.\n"
while True:
try:
productname=raw_input("=>Name of the product:\n")
break
except ValueError:
print "=>Please enter a valid name.\n"
while True:
try:
productprice=input("=>Price of the product:\n")
if isinstance(float(productprice),float):
break
except ValueError:
print "=>Please enter a valid number.\n"
while True:
try:
productcount=input("=>Amount of the product:\n")
if isinstance(int(productcount),int):
break
except ValueError:
print "=>Please enter a valid number.\n"
dict_of_lists[reachlistname][productname]={"price":productprice,"count":productcount}
dict_of_lists[reachlistname]={productname:{"price":productprice,"count":productcount}}
allevents="1-Add a list"+" 2-Add a product to a list"
def eventtochoose():
while True:
try:
event=raw_input("=>What would you like to do? Here are the all things you can do:\n %s\nPlease enter the number before the thing you want to do:" % (allevents))
if not isinstance(int(event),int):
print "\n=>Please enter a number.\n"
else:
if event==1:
addlist()
break
elif event==2:
addproduct()
break
except ValueError:
print "\n=>Please enter a valid input.\n "
while True:
print "%s" % ("\n"*100)
eventtochoose()
所以,问题是(我建议你运行代码)它说“=>你想做什么?这是你可以做的所有事情:1-添加列表2-将产品添加到列表请输入你想做的事情之前的数字:”当我回答它时,它根本不会调用函数。
如果我把 1 它应该调用 fucntion addlist 但我认为它没有。没有什么可以解释的,我想如果你想帮助鳄鱼的话,只要看看代码就可以找到问题。谢谢
解决方案
在比较之前,您没有将输入转换为整数,因此比较总是错误的:
'1' == 1 # false
尝试:
event = raw_input("=>What would you like to do? Here are the all things you can do:\n %s\nPlease enter the number before the thing you want to do:" % (allevents))
try:
event = int(event)
if event == 1:
addlist()
elif event == 2:
addproduct()
break
except ValueError:
print('Please enter a valid input')
推荐阅读
- javascript - 如何在 Google Earth Engine 中找到参与拼接的图像 ID
- android - 谷歌地图在安卓应用程序中无法正常工作
- javascript - Jquery将菜单项保持在一行
- javascript - 如何使用反应在全日历中添加事件?
- javascript - 在 Javascript 函数中设置新的事件目标
- reactjs - 动画在使用 {keyframes} 的样式组件中不起作用
- mysql - 在 where 和 orderby 子句中使用两个单列索引
- r - 如何在 R 中的函数中使用子列表?
- jupyter-notebook - 笔记本升级后出现这样的错误 - TypeError: Cannot cast array data from dtype('O') to dtype('float64') based on the rule 'safe'
- statistics - 如何在调整宗教权重的同时调整人口权重?