在Python中循环 [英] For Loop in Python

查看:45
本文介绍了在Python中循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码是我用JavaScript编写的,但是我试图将其转换为Python可以理解的内容,特别是 for循环.我尝试阅读一下Python中 for循环语法的读取方式,但是我似乎无法完全理解,因为它与许多流行的Web开发语言中的等效语言非常不同.有人可以最好以简单的方式解释它的编写方式和工作方式.谢谢!!

The following code I wrote in JavaScript, but I'm trying to convert it into something Python can understand, specifically the for loop. I tried reading up on how the for loop syntax in Python reads, but I just can't seem to wrap my head around it, since it's very different to its equivalent in many popular web dev languages. Can someone explain to how it's written and how it work, preferably in simple terms. Thank you!!

name = prompt("enter a name"); 

for (var i = 0; i < name.length; i++) {
    name = name.replace(".", "").replace("'", "").replace("-", "");
    name = name.toLowerCase();

}

alert(name); 

仔细考虑一下,For循环显然是没有用的.由于将用户输入与值列表进行比较,我有点困惑,但是考虑到用户将始终输入要比较的一个值,因此无需循环.感谢所有对此发表评论的人,并对我的大脑冻结感到抱歉!

Thinking about it closely the For Loop is evidently useless. I got a bit confused since the user input is going to be compared to a list of values, but considering that the user will always enter one value to be compared, there's no need to loop. Thanks to everyone who commented and sorry for my brain freeze!

推荐答案

感叹.为了完整起见,并且由于其他张贴者似乎致力于错误地回答此问题,因此编写遍历 name 中所有字符的for循环的方法是简单地做到:

Sigh. For the sake of completeness, and because other posters seem committed to answering this question incorrectly, the way to write a for loop that iterates over all the characters in name is to simply do:

for char in name:
    print char  # gives you the character directly

仅此而已.您不应该永远使用 range(len(name)):这是非常不符合Python风格的.如果出于某种原因需要索引,请使用 enumerate :

That's all. You should not ever use range(len(name)): that's horribly un-Pythonic. If you do for whatever reason need an index, then use enumerate:

for i, char in enumerate(name):
    print i     # the index
    print char  # the character

无论如何,正如在其他地方所提到的,此代码中不需要任何类型的循环.

Anyway, as is mentioned everywhere else, there is no need for a loop of any kind in this code.

这篇关于在Python中循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆