Basics of IronPython

This section provides a set of examples to showcase the basics of IronPython 2.7. To know more, check the official documentation "The Python Language Reference".

1. Mathematics

The interpreter of IronPython can act as a simple calculator. It is possible to type an expression, and it will write back the numerical answer. Expression syntax is straightforward: the operators +, -, * and / work just like in most other languages, and parentheses (()) can be used for grouping.

import math

# Arithmetic operators.
2 / 2 == 1
2 * 3 == 6
2 ** 3 == 8
5 % 2 == 1

math.exp(math.e) == 1
round(math.pi, 2) == 3.14

# Complex number.
(1+2j).conjugate() == 1-2j
(1+2j) ** 2 == (-3+4j)
(1+2j) * complex(3, 4) == -5+10J

# Trigonometric functions
math.cos(math.pi) == -1

2. String

A "string" is one of the built-in types of IronPython. It is a sequence of alphanumeric characters, following a set of rules on the use of special symbols, Ascii or Unicode characters, and escape sequences.

String can be enclosed in single quotes ('…​') or double quotes ("…​") with the same result, but quotes cannot be mixed. The symbol \ can be used to escape quotes or other reserved characters.

# Examples of functions applied to the string 'apple'

'apple'.startswith('a')
'apple'.startswith('app')
'apple'.endswith('e')
'APPLE' == 'apple'.upper() 
'apple'.replace('apple', 'banana') == 'banana'

Another example is:

EXAMPLE = 'apple'
EXAMPLE.startswith('A')
EXAMPLE.startswith('app')

3. List and set

IronPython has a number of compound data types, which are generally used to group together other values. One particularly useful compound data type is the "list", which can be written as a sequence of comma-separated items between square brackets. Lists might contain items of different types, but usually the items all have the same type.

# Populate a list.
fruits = ['apple', 'orange']
print(fruits)

# Modify the list.
fruits.append('hazelnut')

# Check if the list has been modified.
fruits == ['apple', 'orange', 'hazelnut']

fruits.insert(0, 'mango')
fruits == ['mango', 'apple', 'orange', 'hazelnut']

# Get an item in the list by its index.
fruits[0]
fruits[-1]

# Slice the list.
first2fruits = fruits[:2]
first2fruits == ['mango', 'apple']

last2fruits = fruits[2:]
last2fruits == ['orange', 'hazelnut']

# Concatenate two lists.
all_fruits = first2fruits[:]
all_fruits.extend(last2fruits)
all_fruits == first2fruits + last2fruits

# List comprehensions.
prices = [0, 1, 2]
squared_prices = [number ** 2 for number in prices]
squared_prices == [0, 1, 4]

Another compound data type is the "set", which constructs and manipulates unordered collections of unique elements. Common uses of sets include membership testing, removing duplicates from a sequence, and computing standard math operations on sets such as intersection, union, difference, and symmetric difference.

# Populate a set.
another_fruits = {'apple', 'orange', 'mango'}

# Check the length
len(another_fruits)

# Test for membership
'apple' in another_fruits

# Convert a list to a set.
unique_fruits = set(fruits)
unique_fruits == another_fruits

4. Dictionary

Another useful data type built into IronPython is the "dictionary". Unlike a list, which is indexed by a range of numbers, a dictionary is indexed by a key, which can be any immutable type. Think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique. A pair of braces creates an empty dictionary {}. Placing a comma-separated list of key:value pairs within the braces adds items to a dictionary.

The main operations on a dictionary are storing a value with some key and extracting the value given the key. It is also possible to delete a key:value pair with del. If you store using a key that is already in use, the old value associated with that key is forgotten.

# Populate a dictionary.
fruits_prices = {'apple': 0, 'orange': 1}

# Check the price of an apple
fruits_prices['apple'] == 0

# Add new key:value pair.
fruits_prices['mango'] = 2

set(fruits_prices.keys()) == {'apple', 'orange', 'mango'}
set(fruits_prices.values()) == {0, 1, 2}

# Loop through key:value pairs.
# This example works in the IronPython Script Editor
# but not in the Command Window
for fruit, number in fruits_prices.items():
    print 'The key is "%s", and the value is "%d".' % (fruit, number)

# Print the help for "dict".
help(dict)
help(dict.items)

# Print all attributes and methods of "dict".
print dir(dict)

5. Comparisons and Boolean operations

Comparison operations are supported by all objects. They all have the same priority and can be chained arbitrarily. For example, x < y ⇐ z is equivalent to x < y and y ⇐ z, except that y is evaluated only once, and z is not evaluated at all when x < y is found to be false. The basic Boolean operations are fully supported and have lower priority over comparisons.

# Comparison operators.
1 + 1 == 2
'apple' != 'banana'
2 > 1
2 >= 1
'apple' in ['apple', 'banana']

# Boolean operators

(1 + 1 == 2) and ('apple' != 'banana')

(1 + 1 == 3) and ('apple' != 'banana')

(1 + 1 == 3) or ('apple' != 'banana')

not (1 + 1 == 3)

6. Loops and branching

IronPython allows to implement loops of commands to carry out a set of operations multiple times. The two more common looping commands are while and for. The first execute the set of command while a certain condition holds. The second repeats the instructions a certain number of times.

Branching allows to apply different commands based on the value of certain conditions. The most relevant branching command is if-else.

# These examples works in the IronPython Script Editor
# but not in the Command Window

# Example of while for the Fibonacci sequence

a, b = 0, 1
fibo=[0, 1]
while b < 10:
    a, b = b, a+b
    fibo.append(b)
print(fibo)

# Example of for

words = ['cat', 'window', 'defenestrate']
for w in words:
    print(w, len(w))

# If-elif-else statement.
fruit = 'banana'
if fruit == 'apple':
    price = 0
elif fruit == 'banana':
    price = 1
else:
    price = 2

price == 1

7. Define functions

It is possible to define customized functions in IronPython. The keyword def introduces a function definition, and it must be followed by the function name and the parenthesized list of formal parameters. The statements that form the body of the function start at the next line and must be indented.

# These examples works in the IronPython Script Editor
# but not in the Command Window

def print_fruit(fruit, price):
    """Function to print the doubled price of a fruit.

    Args:
        fruit (string): name of the fruit.
        price (int): price of the fruit.
    """
    print '\n The doubled price of "%s" is %d.' % (fruit, price * 2)


# Call the defined function.
print_fruit('apple', 2)

# Another example with the Fibonacci sequence
def fib(n):    # write Fibonacci series up to n
    """Print a Fibonacci series up to n."""
    a, b = 0, 1
    fibo = [0,1]
    while a < n:
        fibo.append(a)
        a, b = b, a+b
    print fibo

# Now call the function we just defined:
fib(2000)

Once a function is defined, it can be used and recalled in the command window.