Dec. 7, 2012, 6:43 p.m. by Rosalind Team
Topics: Introductory Exercises, Programming
Conditions and Loops
If you need Python to choose between two actions, then you can use an
elsestatement. Try running this example code:a = 42 if a < 10: print 'the number is less than 10' else: print 'the number is greater or equal to 10'
Note the indentation and punctuation (especially the colons), because they are important.
If we leave out an
else, then the program continues on. Try running this program with different initial values of
b:if a + b == 4: print 'printed when a + b equals four' print 'always printed'
If you want to repeat an action several times, you can use a while loop. The following program prints
Helloonce, then adds 1 to the
greetingscounter. It then prints
greetingsis equal to 2, then adds 1 to
greetings. After printing
greetingsbecomes 4, and the
greetings <= 3is no longer satisfied, so the program would continue past the
whileloop.greetings = 1 while greetings <= 3: print 'Hello! ' * greetings greetings = greetings + 1
Be careful! If you accidentally create an infinite loop, your program will freeze and you will have to abort it. Here's an example of an infinite loop. Make sure you see why it will never exit the
whileloop:greetings = 1 while greetings <= 3: print 'Hello! ' * greetings greetings = greetings + 0 # Bug here
If you want to carry out some action on every element of a list, the
forloop will be handynames = ['Alice', 'Bob', 'Charley'] for name in names: print 'Hello, ' + name
And if you want to repeat an action exactly
$n$times, you can use the following template:n = 10 for i in range(n): print i
In the above code,
rangeis a function that creates a list of integers between
$0$and $n$, where $n$is not included.
Finally, try seeing what the following code prints when you run it:print range(5, 12)
More information about loops and conditions can be found in the Python documentation.
Given: Two positive integers
Return: The sum of all odd integers from
You can use
a % 2 == 1to test if a is odd.