Nov 21, 2024

Wiki

Python

Aide

edit SideBar

Search

The instructions if, for and while


The if

Preliminary remark

In the following structures, as is often the case in Python, spaces at the beginning of the line are mandatory.

  • They go by 4.
  • A tab is not a space.

This indentation is the only information allowing to know when the blocks of the different structures (if, while, etc.) start and end.

The if by example

First example

Example of using a "If... then... otherwise...":

  >>> if 'a' <'c':
  ...     print "a is smaller than c"
  ... else :
  ...     print "a is bigger than c"
  ...

In other words, if 'a' is smaller than'c' (in the natural order of letters), then display 'a is smaller than c', otherwise display 'a is larger than c'.

Second example

Example of using a "If... then... otherwise if... then... otherwise..." :

  >>> if 1 > 2 :
  ...     print "1 is bigger than 2"
  ... elif 1 == 2 :
  ...     print "1 is equal to 2"
  ... else :
  ...     print "everything is fine"
  ...

(the elif means "if not...")

Third example

Example of using a "If... is in... then" structure..:

  >>> c = raw_input("Enter a letter")
  >>> if c in "aeiououy":
  ...     print "Vowel!"
  ... else :
  ...     print "Consonant!"
  ...

In short, if the character entered by the user is in the word "aeiouy", then display vowel, otherwise display consonant. With an in, the container (here, the string "aeiouy") can also be a list, such as [0, 2, 4, 6, 8]:

  >>> c = input("Enter a number")
  >>> if c in[0, 2, 2, 4, 6, 8]:
  ...     print "Even!"
  ... else :
  ...     print "Odd!"
  ...

The if in equality

We can put an "if, then, else" in an equality:

  >>> myVariable = myExpression if myCondition else myExpression2

For example, to effectively code the gcd/ppcm:

  >>> def pgcd(a,b): return a if b == 0 else pgcd(b,a%b)
  >>> def ppcm(a,b) : return a*b/pgcd(a,b)

Practical work

  1. Make a program that asks the user his age, and returns you are young or you are old, depending on whether the age is under, or over, 50 years old.
  2. Justify why only the third line below can appear in the program requested just above.
    • if 'n' < 50 :
    • if n <'50':
    • if n < 50 :
  3. Make a second program that asks, once again, the user's age, and displays :
    • "You are a student", if the age is less than 25,
    • "You are an employee", if the age is between 25 and 65 years old,
    • "You're retired," otherwise.

The instruction for

Presentation of the range method

The range method allows you to quickly create lists of integers:

  • The instruction range(n) returns the list of integers from 0 to n-1,
  >>> range(5)
[0, 1, 2, 3, 4]
  • range(a,b) returns the list of integers from a to b-1.
  >>> range(3,8)
[3, 4, 5, 6, 7]
  • range(a,b,c) returns the list of integers from a to b-1, with a step of c.
  >>> range(3,12,2)
[3, 5, 7, 9, 11]
  • This step can be negative:
  >>> range(11,7,-1)
[11, 10, 9, 8]

Finally, it should be noted that the range method only allows you to manipulate integers.

Put it in the for

The for loop can run through any "iterable", the basic iterable being a list of integers.

So, when we write:

  >>> for i in range(5) :
  ...     print i,
  ...

...we get 0 1 2 3 4.

The above should be understood as follows: "For i browsing the list of integer range(5)=[0,1,2,3,4], display i."

Thus, to calculate the sum of the first 100 integers, we can proceed as follows:

  >>> S = 0
  >>> for k in range(101):
  ...     S = S + k
  ...
  >>> print S
  5050

The for and the other iterable ones

A string, such as word, can also be iterated: there is a first character, then a second character, etc. We can therefore use a for here, when we want to ask: for a character in the following string...

  >>> for letter in "mot":
  ...     print letter,
  ...
  word

Thus, as mentioned above, a for loop can go through a list, a tuple or a string of characters.

To choose, it is better to use for with an iterable that cannot be modified (a string, a tuple rather than a list). Indeed, for dynamically evaluates the elements at each cycle, and unpredictable edge effects can occur if the iterated list has been modified.

Compare, for example, the following two loops:

  >>> list =[1, 2, 3]
  >>> for k in list:
  ....    print k
  ...     list = []
  ...  
  1
  2
  3
  >>> list =[1, 2, 3]
  >>> for k in list:
  ...     print list[k-1]
  ...     list = []
  ... 
  1
  Traceback (most recent call last):
    File "<stdin>", line 2, in <module>
  IndexError: list index out of range
  >>> 

Practical work

  • Display the list of squares of all integers between 5 and 15. It should be noted that the power is obtained, in python, by two stars (**):
  >>> 2**5
32
  • Ask the user to enter a word, and display only his vowels. The program could be like this (to be translated into Python):
  For each letter of the word:
       if the letter is a vowel:
           I post it
  • Display the first 30 powers of 2, and calculate their sum.

The instruction while

while by example

A small example of using while..., do...:

  >>> i=0
  >>> while i<4 :
  ...     print i
  ...     i+=1
  ...

For example, if you want to obtain the $n$ such that $1+2+3+...+n$ exceeds 1000 for the first time, you can do this:

  >>> S = 1
  >>> n = 1
  >>> while S < 1000 :
  ... n = n + 1
  ...     S = S + n
  ...
  >>> print n
  45

Note, once again, that you can use a break instruction to exit a while loop:

  >>> i=0
  >>> while 1 :
  ...     i+=1
  ...     if i>5 :
  ...         break
  ...

Practical work

  1. Determine the positive integer $n$ such that $2+4+6+8+...+2*n$ exceeds 1000 for the first time.
  2. Do the same with the odd integers, and the powers of 2.
  3. The harmonic sequence $(H_n)$ is defined by :

$\forall\,n\geq 1,\quad H_n=1+\frac{1}{2}+\frac{1}{3}+\cdots+\frac{1}{n} $ We admit that this sequence is divergent. Find the smallest natural integer $k$ such that $H_k>10$.

pass, continue and break

Presentation

To facilitate loop writing, Python uses three keywords:

  • Pass: Does nothing.
  • Continuous: stops the execution of a loop, but resumes at the beginning of this loop at the next iteration.
  • Break: definitively stops the loop.

Practical work

  1. Test the effect of each of these keywords on the loops presented here.
  2. Write new versions of your programs made above using these keywords. The goal here is not to make a clean or efficient program, but to learn how to use these tools.

Other practical work

  1. Write a program that asks a student for their grade point average and displays:
    • "Admitted" if the average is greater than or equal to 10,
    • "Catching up" if the average is between 8 and 10 (and different from 10),
    • "Refused" if the average is strictly less than 8.

Page Actions

Recent Changes

Group & Page

Back Links