Python syntax

Simple examples of language syntax. If you need more complete description of the language, you should refer to python.org.

Important

Indentation as part of the language. Indentation determines where the body of a loop or function ends.

Branching:

if x+y > 5:
    alert("The sum x + y is enormous!")
elif x<0 or y<0:
    error("Invalid x and y values")
else:
    message("The sum x + y is okay: %i" % (x+y)) 

Loops:

for i in range(5):
    message(i+1)
message("A rabbit went for a walk")

i = 10
while i>=0:
    message(i)
    i -= 1
alert("Start!") 

Functions:

def f1():
    alert("Function without parameters")

def f2(x, y):
    alert("Function with parameters x=%s, y=%s" % (x,y))
    if x > 5:
        alert("Come on, x is greater than 5!")

f1()
f2(3, 4) 

Lists:

lst = ["pastries", "ice cream", "cookies"]
lst.append("candies")
for x in lst:
    alert("I want %s!" % x)
lst.pop(1)
lst += ["cucumbers", "tomatoes"]
alert("And %s!" % lst[4])
first = lst[0]
last = lst[-1]
first_three = lst[:3]
last_three = lst[-3:]
middle = lst[2:3]

lst = [x for x in range(1,5)]
squared = [y*y for y in lst]
file = [x.strip() for x in open("readme.txt")]
words = "we use spaces to split a string into words".split(" ") 

Strings:

x = "Vasily"
y = "Pupkin"
z = x+y
alert(z)
z = " ".join( [x,y] )
alert(z) 

Formatting strings:

pi = 3.1415926
alert("PI accurate to 2 decimal places: %0.2f" % pi)
s = "PI accurate to 3 decimal places: %0.3f" % pi
alert(s)
name = "Vasya"
age = 25
s = "Hi, %s. You're probably %i" % (name, age)
alert(s) 

Formatting time:

import time
message(time.strftime("%H:%M:%S %d.%m.%Y", time.localtime())) 

Lambda expressions let you construct a function call using local variables. The function call can then be returned to be used later. This approach is helpful when interacting with the user and during long operations:

def hello(name, answer, correct):
    if answer==correct: message("Correct, %s!" % name)
    else: message("Actually, it's %s!" % correct)
def check_user_math(name):
    ask("Dear %s, what is 5 x 5?" % name,
        lambda x: hello(name, x, "25"),
        lambda: message("Again nobody wants to talk to a robot."))
ask("What's your name?", check_user_math, None) 

Global variables are easier to understand than lambda expressions:

def hello(answer):
    global name
    if answer==25: message("Correct, %s!" % name)
    else: message("Actually, it's 25!")
def check_user_math(n):
    global name
    name = n
    ask("Dear %s, what is 5 x 5?" % name,
        hello,
        None)
ask("What's your name?", check_user_math, None)