[英]why are both if and else statement getting executed {python}
我在商店中提到过 class 方法搜索返回 None 如果 for 循环结束并且仍然没有返回,并且在 main 中我只写了如果它是 none 然后什么都不打印但它仍然打印“无”我认为没有任何缩进正如在类似类型的问题中指出的那样
class book:
def __init__(self,_id,name,tech,price,auth):
self._id=_id
self.name=name
self.tech=tech
self.price=price
self.auth=auth
def _print(self):
print(self._id)
print(self.name)
print(self.tech)
print(self.price)
print(self.auth)
class store:
def __init__(self,bookdb,name='abc'):
self.bookdb=bookdb
self.name=name
def search(self,b_name,book_list):
for i in book_list:
if i.name==b_name:
return i._print()
else:
return None
def discount(self,tech,book_list):
amt=0
for i in book_list:
if i.tech==tech:
amt+=i.price
return amt*(0.9)
if __name__=="__main__":
t = int(input())
b_list=[]
bookdb=dict()
for i in range(t):
_id=int(input())
name=str(input())
tech=str(input())
price=int(input())
auth=str(input())
b_list.append(book(_id,name,tech,price,auth))
bookdb[i]=book(_id,name,tech,price,auth)
title=str(input())
tech=str(input())
store_i=store(bookdb)
if store_i.search(title,b_list)== None:
print('nothing')
else:
store_i.search(title,b_list)
if store_i.discount(tech,b_list)== 0:
print('0.0')
else:
print(store_i.discount(tech,b_list))
**Input**
3
1
TIC
CPP
300
在线的
2
铬
JAVA
500
瓦米
3
BR
JAVA
700
拉贾
TIC
JAVA
Output
1
TIC
CPP
300
Online
nothing
1080.0
需要 output
1
TIC
CPP
300
Online
1080.0
PS bookdb dic 在这里没有任何用处
class书中的_print()方法没有返回语句,因此 python 将隐式返回 None。 然后在搜索function 时,当您返回 i._print()时,它也返回None ,这就是您看到“无”output 的原因。
由于您要测试结果,您不妨让search()返回一个 boolean,这是一个建议的编辑:
def search(self,b_name,book_list):
for i in book_list:
if i.name==b_name:
i._print()
return True
else:
return False
您的代码有很多问题。
...
name=str(input("Enter Book Name: "))
...
Python
对代码的(视觉)结构(即缩进级别)非常敏感。 因此,例如,“if”的“else”必须始终位于相同的缩进级别。 def search(self,b_name,book_list):
for i in book_list:
if i.name==b_name:
return i._print()
else:
return None
return
语句必须在for
循环之后i._print()
不会返回i
,除非_print
function 返回i
作为其最后一条语句。有了这些言论,你应该尝试
def search(self,b_name,book_list):
for i in book_list:
if i.name==b_name:
i._print()
return i
return None
另外,一般来说
t
或不明显的缩写等变量。...
print("Book Name: ", self.name)
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.