For Loop in Python

大兔子大兔子 提交于 2021-02-11 14:30:43

问题


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); 

Edit: 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!


回答1:


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

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.




回答2:


The for loop in python is structured in the following way:

for iteration_variable in iteratable_object:
    # do task with iteration_variable
    # repeat with next iteration variable

here is an example of printing out numbers:

for i in range(1,10):
    print i

And will output

1
2
3
.
.
.
9

Abbreviated to save typing.

For strings (str is the type ascribed to regular strings) this can be done via a list:

my_string_array = ['abc','def','ghi']

for my_string in my_string_array:
    print my_string

And will output

abc
def
ghi

Now to discuss a few of the comparable commands to the javascript commands you used. To handle user input python has a few options. The best for simple string input is raw_input, and is used in the following way:

variable = raw_input("Hello, who are you?")

This will print out Hello, who are you?, the user can then enter any text they like and hit the enter key and it will be stored in variable now for your use.

If you want to replace a character in a string, python's str type has a method called replace, which works in the following way:

my_variable = 'abc.def'
my_variable = my_variable.replace('.','')
print my_variable

will output

abcdef

the method str.replace will return the string with all character strings matching the first argument replaced with the second argument in the same way the javascript function works. The method only returns the new string though, it does not automatically change the value of the variable, so if you desire to keep it save it into a variable (saving it into itself is a valid option as seen in my example).

To make a string lowercase you can use str's the built in command lower. In a similar way to replace, the updated string is returned and not saved into the variable and should be stored somewhere again if further use is required.

my_var = 'ABC_DEF'
my_var = my_var.lower()
print my_var

and will output

abc_def

Putting this all together we can convert your javascript loop into python in the following way:

name = raw_inpout("enter a name"); 

for i in range(len(name)): # len is the python method to
                           # get the length of an object
    name = name.replace(".", "").replace("'", "").replace("-", "")
    name = name.lower()

print name

This is a direct translation of your code. In python you can iterate directly over characters in a string and that is usually preferred:

my_string = 'abc'
for character in my_string:
    print character

will output

a
b
c

It might be helpful to know that in your case you do not actually need the for loop in either the javascript or the python case:

# Python
name = raw_inpout("enter a name"); 
name = name.replace(".", "").replace("'", "").replace("-", "")
name = name.lower()

print name

And

# Javascript
name = prompt("enter a name"); 

name = name.replace(".", "").replace("'", "").replace("-", "");
name = name.toLowerCase();    

alert(name); 

This is because both the javascript and python methods apply to the whole string already and you do not need to make changes character by character. Indeed you do not use the index reference to which you are looping over anyway! You just end up making the same change to the string as many times as the string is long.

Hopefully this gives you a better picture of for loops and a brief look at python! Happy python-ing!




回答3:


In javascript your code could simply be:

name = prompt("enter a name"); 
name = name.replace(".", "").replace("'", "").replace("-", "");
name = name.toLowerCase();
alert(name);

the equivalent in python is:

name = raw_input("enter a name") 
name = name.replace(".", "").replace("'", "").replace("-", "")
name = name.lower()
print(name)



回答4:


There is a type of objects in python called iterators. For such objects you can tell python interpreter to yield you it's elements one by one. And for iterator objects you can call "for" loop.

sequence = [1, 2, 3, 4, 5]

for i in sequence:
    i += 10
    print i

this code means that you get the list called "sequence" and ell the interpreter "give me the first element of list and and assign it's value to the variable i, add 10 to i and print it (this code will print "11"), then give me the second element, assign it's value to i, add 10 and print(phis will print "12") and iterate it untill the end of the list"

So the output of this programm will be

>>>11
>>>12
>>>13
>>>14
>>>15



回答5:


As others have mentioned, this is pointless as you can just as well remove the for loop. To convert your code directly:

name = raw_input("enter a name")

for i in range (0,len(name)):
    name = name.replace(".", "").replace("'", "").replace("-", "")
    name = name.lower()

print name

However you can get the exact same result in both JavaScript and Python like this as the loop does nothing:

name = raw_input("enter a name")
name = name.replace(".", "").replace("'", "").replace("-", "")
name = name.lower()
print name

I assume this question is to help you understand for loops in Python in future it would be best to use an example that does something, the main difference in the languages that might need some understanding here is the range() function which replaces what's in bold here:

var i = 0; i < name.length; i++

So I would recommend looking into the function to understand whats happening https://docs.python.org/2/library/functions.html#range

EDIT:

As a caveat in Python we generally do not use range to iterate. If I were to loop over a string like this a much easier and cleaner way would be:

for char in name:
    do stuff


来源:https://stackoverflow.com/questions/34340130/for-loop-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!