Expressions

Definition: An expression is an construct of symbols that the python interpreter can evaluate. The expression we can type in the inpreter, and that the interpreter can evaluate meaningfully are

  • numerical expressions
  • textual expressions
  • logical expressions

Numerical Expression


In [1]:
x = 5; y = 700; z = 821

In [2]:
x + y
x * y
x ** y

# etc.


Out[2]:
1901091566295159823515072405835103109264871206373519032441746057565854249277472203557201497052621863202610629503298188674778262443788623503544624583852527978187847081031734592912357695384795280342176118255040207774382160198963856151525515423826657984269000422536358621400702420807052018353350982292716419484982535110142249297056924906488555403892140062791926661918530613262656492971667990518503399759909868494802563030058676203176091173708076110583121975938780678916373290121555328369140625L

Textual Expression

The simplest "textual expression" is a string, i.e., a sequence of characters (i.e., alphanumeric symbols, plus puntuation marks, plus special escape sequences).

To let python Know that your text is a string, and not the name of a variable, you need to use quotes:

  • single quotes: '
  • double quotes: "
  • triple quotes: """

In [3]:
"Once upon a time\nthere was a little rabbit\nwho liked carrots two much."


Out[3]:
'Once upon a time\nthere was a little rabbit\nwho liked carrots two much.'

In [4]:
"""Once upon a time
there was a little rabbit
who liked carrots two much
He said
I'd live another carrot"""


Out[4]:
"Once upon a time\nthere was a little rabbit\nwho liked carrots two much\nHe said\nI'd live another carrot"

Operations on strings


In [8]:
x = "Benoit"
y = "Dherin"

z = x + ' ' + y
print z


Benoit Dherin

In [12]:
x = "Hello "
8*x


Out[12]:
'Hello Hello Hello Hello Hello Hello Hello Hello '

String formatting


In [25]:
name = 'Bob'; age = 32; job ='Teacher'; teeth = 12.5
name2 = 'Marcelluscatapultus'; age2 = 3320; job2 ='Yogi'; teeth2 = 122.82

In [26]:
print name + job + str(age) + str(teeth)


BobTeacher3212.5

In [41]:
formatted_string  = "| %-20s | %-20s | %-4d | %-8.2f |" % (name, job, age, teeth)
formatted_string2 = "| %-20s | %-20s | %-4d | %-8.2f |" % (name2, job2, age2, teeth2)

print '_'* 65
print formatted_string
print formatted_string2
print '_'* 65


_________________________________________________________________
| Bob                  | Teacher              | 32   | 12.50    |
| Marcelluscatapultus  | Yogi                 | 3320 | 122.82   |
_________________________________________________________________

Logical Expression


In [ ]:


In [6]:
True


Out[6]:
True

In [7]:
False


Out[7]:
False

In [20]:
x = True; y = False

In [23]:
x and y


Out[23]:
False

In [24]:
x or y


Out[24]:
True

In [25]:
not x


Out[25]:
False

In [26]:
(x or y) and not x


Out[26]:
False

In [ ]: