What is an algorithm? An algorithm is a set of instructions or a recipe for a computer to carry out.
By default, 1 / 2 yields 0 in python. This is integer division.
Solution: from __future__ import division
What is a variable? A variable is a name that refers to some value (could be a number, a string, a list etc.)
Store the value 42 in a variable named foo
foo = 42
Store the value of foo+10 in a variable named bar
bar = foo + 10
What is the difference between an expression and a statement? An expression is something, and a statement does something.
Ask the user to input a number, and store it as the variable foo
foo = input("enter a number: ")
What is the value of foo now?
Add foo and bar together
foo + bar
Calculate the average of foo and bar, and save it as a variable named avg
avg = (foo + bar)/2
What is a function? A function is a mini-program. It can take several arguments, and returns a value.
What is a module? Python is easily extensible. Users can easily write programs that extend the basic functionality, and these programs can be used by other programs, by loading them as a module
load the math module
import math
Round 35.4 to the nearest integer
math.round(35.4)
Round the quotient of foo and bar down to the nearest integer
math.floor(foo/bar)
Script File: hello.py
[language=python] #!/usr/bin/env python # this script prints ’hello, world’, to stdout print "hello, world" Add executable permission:
chmod a+x hello.py
Run the program:
./hello.py
Strings must be enclosed in quotes (double or single)
Strings can be concatenated using the + operator