110 likes | 225 Views
Computer Science 101. For Statement. For-Statement . The For-Statement is a loop statement that is especially convenient for loops that are to be executed a specific number of times (not controlled by user input, etc.). The For-Statement is also convenient for working with lists.
E N D
Computer Science 101 For Statement
For-Statement • The For-Statement is a loop statement that is especially convenient for loops that are to be executed a specific number of times (not controlled by user input, etc.). • The For-Statement is also convenient for working with lists.
For-Statement (cont.) • Syntax: for <variable> in <list> : <list of statements> • The variable is called the loop index. • Semantics: For each value in the list, the loop index takes on the value and the loop body is executed.
Range • range provides a list of consecutive numbers. • If num is a positive integer, then range(num)gives the list [0,1, …, num-1] • If num1 < num2, then range(num1, num2)gives the list [num1, num1+1, …, num2-1]