python - 为什么循环在编程时不起作用?
问题描述
当我尝试执行以下代码时,我在循环迭代中遇到了一些问题,无法弄清楚问题可能是什么。
def string_splosion(s):
"""Takes a non-empty string s like "Code" and
returns a string like "CCoCodCode"
"""
for i in range(len(s)):
return s[i] * (i+1)
print(string_splosion('Code'))
解决方案
如果您在循环中返回内部,则循环仅运行一次。
def string_splosion(s):
"""Takes a non-empty string s like "Code" and
returns a string like "CCoCodCode"
"""
a='' ## empty String
for i in range(len(s)):
a += s[0:i] +s[i] ## this is beter way to do this "CCoCodCode"
return a ## out of the "for" loop
print(string_splosion('Code'))
推荐阅读
- python - Flask:如何在 SQLAlchemy 中使用多个表
- vue.js - Axios 捕获错误只显示网络错误而不是来自服务器的消息
- python - xslt转换时lxml缺少节点
- javascript - 在获得该功能的响应后,我如何重新执行特定功能?
- node.js - 反应本机 - 图像上传:节点发布 API 没有被 fetch 调用
- css - 我如何在 div 之外左右制作 CSS 背景图像?
- r - 当需要“大小”美学和 geom_smooth 时更改图例外观
- python - 如何从具有位置(X,Y)和强度的点加速创建图像?
- java - 是否可以在@Repository 中调用服务?
- java - Tomcat 端口已使用 8084