The personal wiki of ...

Exercise: Computation

A key part of most languages is their ability to do maths. Python is no different. Go back to your hangman.py script and add the following lines.

%CODE{"python" nocontrols="on"}% print 2+33+66 print 33333333 * 44444444 n=123456789 print n*n*n %CODE{"python" nocontrols="on"}%

Now run it on the mobile phone, you should see the following.

In Python, plus and minus are normal but times and divide are done using the * and / symbol. Some other symbols to know:

+ plus

- minus

* times

/ divide, rounding down

x = 95 save 95 as x x == 24 is x equal to 24? x < 24 is x less than 24? x > 24 is x more than 24?

len(word) the length of word

str(num) turns num into a string of digits

int(digits) makes a number from a string

What will it do when we say "len(str(1234))"?

Add the following code to your hangman.py, run it and see if you can explain the results.

%CODE{"python" nocontrols="on"}% print(len(secret)) print(len(str(number))) print(number * number) print(number < 50) %CODE{"python" nocontrols="on"}%

You should see something like this:

Next
Contact Us | Section Map | Disclaimer | RSS feed RSS FeedBack to top ^

Valid XHTML and CSS | Built on Foswiki

Page Updated: 20 Jan 2012 by ian. © Victoria University of Wellington, New Zealand, unless otherwise stated