iT邦幫忙

0

Python 代码测试问题

我有一个简短的代码,返回city 和 county。
直接调用是正常的:
https://ithelp.ithome.com.tw/upload/images/20190717/20099494wUBuNRTsC2.png

但我使用 unittest 去测试这段代码的时候,却发生了错误:https://ithelp.ithome.com.tw/upload/images/20190717/20099494kSCjwui7tU.png
https://ithelp.ithome.com.tw/upload/images/20190717/20099494WAidCENfyz.png

但我把 print 改成 return 就好了:
https://ithelp.ithome.com.tw/upload/images/20190717/20099494hzLhbZvgYD.png

这是为什么,如果我想使用 print,应该怎么修改我的测试代码?

看更多先前的討論...收起先前的討論...
froce iT邦大師 1 級 ‧ 2019-07-17 10:33:56 檢舉
print以後return啊,又不互相影響...
他看起來在這邊問了很多問題都沒用
他還是搞不懂print跟return差在哪
print跟return功能是風馬牛不相及(以此例而言),不知他在糾結什麼?是不是認為print之後location就會結束並回傳?
小魚 iT邦大師 1 級 ‧ 2019-07-17 11:17:36 檢舉
> 他看起來在這邊問了很多問題都沒用
小A的魔咒...
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

0
japhenchen
iT邦超人 1 級 ‧ 2019-07-17 10:35:52

重點是你的第5行
location_city=location("shanghai","china")

當你的location函式裡只有 print而無return回傳值,則location_city == None ,就出現那個錯誤訊息

print之後再return一起用不可以嗎?

0
dragonH
iT邦超人 5 級 ‧ 2019-07-17 10:43:18

這很正常呀

因為他是用你 location 的 return 結果來比對

你用 print 當然就沒有 return 值了

是說為什麼要堅持用 print 呢?

用 return 也不錯呀

def location(city, country): 
    return city.title() + ',' + country.title()

print(location('shanghai', 'China')) # 這樣使用 location

我要發表回答

立即登入回答