Quantcast
Channel: CodeSection,代码区,Python开发技术文章_教程 - CodeSec
Viewing all articles
Browse latest Browse all 9596

Python for loops

$
0
0

It’s always interesting to explain a new programming language to students. python does presents some challenges to that learning process. I think for loop can be a bit of a challenge until you understand them. Many students are most familiar with the traditional for loop like Java:

for (i = 0; i < 5; i++) { ... }

Python supports three types of for loops a range for loop, a for-each expression, and a for loop with enumeration. Below are examples of each of these loops.

A range for loop goes from a low numerical value to a high numerical value, like:

for i in range(0,3): print i

It prints the following range values:

A for-each loop goes from the first to the last item while ignoring indexes, like: list = ['a','b','c'] for i in list: print i

It prints the following elements of the list:

a b c

A for-each loop goes from the first to the last item while ignoring indexes, like: list = ['a','b','c'] for i, e in enumerate(list): print "[" + str(i) + "][" + list[i] + "]"

The i represents the index values and the e represents the elements of a list. The str() function casts the numeric value to a string.

It prints the following:

[0][a] [1] [2][c]

This should help my students and I hope it helps you if you’re trying to sort out how to use for loops in Python.


Viewing all articles
Browse latest Browse all 9596

Trending Articles