Jon Reades - j.reades@ucl.ac.uk
1st October 2025
| Name | Value | Type |
|---|---|---|
| msg | ‘Hello world’ | type(msg)==str |
| answer | 42 | type(answer)==int |
| pi | 3.14159 | type(pi)==float |
| c | complex(5,2) | type(c)==complex |
| correct | True | type(correct)==bool |
Message starts as a string:
But we can change it to an integer like this:
And back to a string:
And notice:
One to remember for the session on objects and classes:
Rules for variable names:
item3 is valid, 3items is not._ is allowed: my_variable is valid, my-variable, my$variable, and my variable are not.myVar is different from both myvar and MYVARmy_var is more ‘Pythonic’, though myVar is also widely used; but don’t mix these!bldg_height vs. bh vs. max_building_height_at_eaves.Do not try to use any of these as variable names. Python may not complain, but strange things will happen when you run your code.
| and | del | from | not | while |
| as | elif | global | or | with |
| assert | else | if | pass | yield |
| break | except | import | ||
| class | exec | in | raise | |
| continue | finally | is | return | |
| def | for | lambda | try |
Let’s start with x=10 and y=5…
| Operator | Input | Result |
|---|---|---|
| Sum | x + y |
15 |
| Difference | x - y |
5 |
| Product | x * y |
50 |
| Quotient | x / y |
2.0 |
| ‘Floored’ Quotient | x // y |
2 |
| Remainder | x % y |
0 |
| Power | pow(x,y) or x**y |
100000 |
| Equality | x==y |
False |
When you do things with strings the answers can look a little different. Let’s start with x="Hello" and y="You" and z=2…
| Operator | Input | Result |
|---|---|---|
| Sum | x + y |
'HelloYou' |
| Difference | x - y |
TypeError |
| Product | x * z |
HelloHello |
| Equality | x==y |
False |
Python has no fewer than three ways output information:
+;<str>.format(<variables>); andf"{variable_1} some text {variable_n}".There are pros and cons to each:
Always pay attention to precedence:
And here’s a subtle one:
The full list is here.
For numeric variables comparisons are easy.
| Operator | Input | Result |
|---|---|---|
== |
10 == 5 |
False |
!= |
10 != 5 |
True |
<, <= |
10 < 5 |
False |
>, >= |
10 > 5 |
True |
But notice:
Why is 4a greater than both 365 and 42?
Notice the very subtle visual difference between = and ==!
Remember this!
Here’s the output from some attempts at comparison:
This last line produces:
If we want to compare them then we’ll need to change their type:
Here are some links to videos on LinkedIn Learning that might help, and YouTube will undoubtedly have lots more options and styles of learning: