Introduction to Python, Operators and Data Types

Weekly Topics

In this weeks lecture and lab we will look at the following areas:

The basic types of programming languages,

How high-level code becomes code that actually runs on the processor,

The Python programming language,

How to use variables,

Data types, their importance, and how we can use them,

Operators we can use to manipulate data, and

User input and display.
3
Types of Programming Languages

The three main types of programming language are:

Imperative

These are the most common types of languages.

They consist of a series of statements where we specify the order in which the statements take place to perform some job or task.

Examples:

Python, Java, C++, C#, Basic etc.

Functional

These are less common and tend to map mathematical relationships.

Like imperative languages, we specify the order of statements, but they tend to feed-back on themselves where the result of running one function is fed as input into another function, and the result of that is fed back into yet another function… and so on!

Examples:

Lisp, Haskell etc.
4
Types of Programming Languages (Cont’d)

Logic

Logic programming languages are the least common type of language, and are kind of like an ‘intelligent database’.

To work with a logic programming language, we specify a series of facts and rules.

Once these facts and rules are defined, we can ask the program a question –and if it has enough facts and rules to work out the answer then it’ll do so!

Examples:

Prologis the main one, there are about a dozen little known/used others*.

In logic programming languages –we do not specify a precise sequence of steps to work out the answer to our question (i.e. it’s a nonprocedurallanguage).

The language itself uses what’s called predicate logic to figure out the answer!

  • = https://en.wikipedia.org/wiki/Category:Logic_programming_languages
    5
    Programming Domains

    Programming languages can be used in a vast variety of different areas, from controlling nuclear power plants to providing video games for mobile devices.

    However, it makes sense for us to break up software into a few broad categories / domains, broadly speaking these are:

    Scientific Applications,

    Business Applications,

    Artificial Intelligence,

    Systems Programming, and

    Web Software.
    Question: Where would you say Video Games fit in the above categories?
    6
    What Type of Programming Language is Python?

    We’ve already said that Python is an imperativelanguage…

    …but it’s also a general purpose language which we can write pretty much any type of application in!

    Business apps, games, scientific, web, data analytics, artificial intelligence… The list goes on! We can write them all in Python if we wanted to due to the languages rich set of features.

    However -that doesn’t necessarily meanthat it’s the BEST language to write anapp in any given field…

    …but it ISa very useful ‘jack-of-all-trades’language, with a clean, attractive syntaxthat makes it easy to learn and use.
    7
    What Type of Programming Language is Python? (Cont’d)

    Now we’ve said that:

    Python is a imperative language -we specify a sequence of steps using operands and operators.

    Python is a general purpose language -it has the tools and flexibility to be used for pretty much any purpose.

    Python is also an interpretedlanguage.

    This means that the way it actually executes any given program is to:
    1.
    Read a line of code,
    2.
    Convert that line of code into machine code which the CPU can run,
    3.
    Read a line of code,
    4.
    Convert that line of code into machine code which the CPU can run,
    5.
    Read a line of code,
    6.
    [ No prizes for guessing what step six is! Or seven! Or eight! Or… =P ]
    8
    Executing Programs

    There are three different ways in which we can convert a program in a high-level language like Python into a version that can be executed on a CPU:

    Compilation

    All program code is converted into machine code before the program executes. Once a program has been compiled into machine code it is ready to be executed -this typically means that the code can execute very quickly.

    Pure Interpretation

    Each line of program code in converted into machine code for execution (one line at a time) as the program executes. This typically means that the code executes less quickly than compilation.

    Hybrid Implementation

    In hybrid implementation, the program code is translated into an intermediate programming languagewhich is designed to be able to be interpreted quickly before the program executes. Once this has been done, it is this intermediate codethat is actually interpreted into machine code. This typically results in code that executes relatively quickly.
    Note: So the execution speed hierarchy from fastest to slowest is: Compilation, then Hybrid Interpretation, then Pure Interpretation.
    9
    Executing Programs (Cont’d)

    To paraphrase the previous slide, we could say:

    Compilation

    Your source code is converted to an executable file BEFOREyou run it.

    Pure Interpretation

    Your source code is converted into executable instructions AS you run it.

    Hybrid Implementation

    Your source code is converted to an intermediate format BEFORE you run it (compilation)…

    …and then than intermediate format is converted into executable instructions AS you run it (interpretation).

    Think of Java -your Test.javagets compiledinto Test.class, and then that Test.classgets interpreted into machine code in order to actually run!
    10
    Pure Interpretation

    Pure interpretation is largely the opposite approach to compilation.

    In an interpreted programming language, the program source code is interpreted line-by-line at runtime, with no intermediate translation whatsoever.

    You can think of the interpreter program as a simulation of a machine whose fetch-execute cycle deals with high-level language programs rather then machine code instructions.
    Source Program
    Interpreter
    Computer
    Results
    Input data to go with program
    Machine code
    Source code to machine code
    11
    Compilation [Just for fun! You won’t be tested on this!]
    = or language similar to an actual assembly language -it varies with the language / compiler chain. Source Program Lexical Analyser Syntax Analyser Intermediate Code Generator & Semantic Analyser Code Generator Computer Results Symbol Table Optimisation (optional) Lexical units Parse trees Intermediate code Machine code Input data to go with program Source code to assembly language
    Assembly* to machine code
    12
    Hybrid Implementation Systems [Just for fun -no test!]
    Source Program
    Lexical Analyser
    Syntax Analyser
    Intermediate Code Generator
    Interpreter
    Computer
    Results
    Lexical units
    Parse trees
    Intermediate code
    Machine code
    Input data to go with program
    Source code to Byte code
    Byte code to machine code
    13
    Hybrid Implementation Systems Just for fun -no test!

    In a Just In Time implementation system (i.e. JIT compiler) translates programs to an intermediate language -then during executionof the intermediate code, it compiles the intermediate version into machine code which can be used..

    …but here’s the clever bit: It then keeps the compiled machine code version around, and uses that for any further calls to that particular code.

    So in effect, when translating any given piece of code in a Hybrid language:

    The first time that a given piece of code runs it must be interpreted, but…

    …any further callsto that same code are executed via the compiled machine codeversion for speed of execution! How clever is that?! =D

    Quiz: Can you name an example of any Hybrid language?
    14
    Pure Interpretation (Again)

    Interpretation is the only type of language we care about in this course, and as we said, an interpreted programming language is where the program source code is interpreted line-by-line at runtime so that each line of source code is translated directly into machine code, which the computer understands.
    Source Program
    Interpreter
    Computer
    Results
    Input data to go with program
    Machine code
    Source code to machine code
    15
    Hello, World!

    The first program any programmer should write in any programming language (even one they know the language well and have just installed the development tools) is called HelloWorld.

    As you no doubt know, it prints the text “Hello, World!” to the screen.

    The reason we should write this program first is two-fold:
    1.
    It’s probably the simplest program we can possible write, and
    2.
    When it works, it proves that our development environment has been installed and set up correctly.

    In Python, the ‘hello world’ program is simply this:
    print(“Hello, World!”)

    When we run the program, it prints the message and we’re happy! =D
    No trailing semi-colon required! i.e. ;
    16
    Hello, World -Explained

    When we have a Python program with the following code:
    print(“Hello, World!”)

    The print part is a function-which is part of the Python language.

    When the program is executed by the Python interpreter:

    The Python interpreter negotiates with the operating system to determine when it can run (as in, “Can I run now or are you busy?”),

    When the operating system says “Now is fine -you can run”, the Python interpreter looks at the line of code and converts the high-level code into machine code the processor [CPU] can understand, then

    The operating system provides the resources requested by the code (in this case just for the print function) and allows the machine-code version of our program to execute.
    17
    Hello, World -Explained (Cont’d)

    But…
    We don’t care about any of that!

    Why? Because it’s not our job to care*!

    WE just write the high-level code! That is “do this, do that” -we don’t care HOW it gets done!

    It’s the job of the Python interpreter and the Operating System to utilise the hardware (CPU, RAM etc.) to carry out the commands it’s given -not ours.

    We just say:
    ” Here’s some Python code -run it.”

    And it runs -and if all works correctly we high-five =D
  • = Also, it’s outside the scope of this course! This is just an introduction to programming and problem solving. If we were writing an interpreter, or an operating system or fabricating hardware then we’d care a lot!
    18
    Getting Python

    There are two main version of Python, and these have slight differences which mean that they aren’t fully compatible with each other.

    In this class we’ll be using Python 3, instead of the legacy Python 2 as it fixes a number of issues and inconsistencies of Python 2*.

    Python 3 can be freely downloaded from:
    https://www.python.org/

    The default installer comes with:

    The interpreter (which we obviously need),

    An interactive terminal (i.e. “shell”) where we can type a Python command and get a result. For example: print(2+2) would return us the value 4, and

    A basic Python IDE called IDLE-which is what we’ll be using for this course.
  • = http://python-notes.curiousefficiency.org/en/latest/python3/questions_and_answers.html#why-is-python-3-considered-a-better-language-to-teach-beginning-programmers
    19
    Data Types

    All programming languages like to know what type(i.e. “what kind”) of data they’re working with so that they can work with the data correctly.

    If an interpreter or compiler doesn’t know the type of data it’s working with, then it might be able to “guess” or convert the data, but then again it might not! It all depends on the circumstances!

    Even if it does guess, it might guess wrong, which could lead to undesirable outcomes such as:

    Calculations being incorrect,

    The program crashing, or

    Some bizarre undefined behaviour (i.e. works first time, fails second time etc.)

    So let’s take a look at some of the most common types of data (which are called “data primitives”)…
    20
    Basic Data Types: bool

    bool values (short for boolean) are the absolute simplest type of data you can have, and equate to a simple True or False value.

    In fact, these two values are the onlyvalid values for any booldata -ever!:

    True(capital “T” in True is important!)

    False(capital “F” in False is important!)

    Despite only having two possible values, bools are still very, very useful.

    Also, a useful aspect of a booleanvalue is that we know that if a value is NOTTrue, then it mustbe False!

    And, of course, if it’s NOTFalse, then it mustbe True!

    If we enter: type(True)or type(False)into the Python shell it responds:

    Question: Why do you think it says this? Why are Boolean values so useful?
    21
    Why Boolean Values Are Awesome

    They’re small (i.e. they don’t take up much memory -you canstore a bool as a single bit -that is, a single 1 or a 0 if necessary*)

    If they’re not True they’re False, and vice versa. Which has surprisingly wide-ranging applications in logic.

    They’re the basis for CPUs -via transistors we can make logic gates such as AND, OR, NOT, NAND, and XOR etc.

    In hardware terms this means:

    True -if a transistor is allowing electrons to flow, or

    False -if a transistor is blocking electrons from flowing.

    And from this, you can do things like make circuits which can perform arithmetic -which is all computers ever, ever, ever do!

  • = but we often don’t. Ask me why if you’re curious… =D
    22
    Basic Data Types: int

    intdata (short for integer) is just a whole number without any fractions or decimal places or anything like that.

    Examples of intdata could be:

    0(zero)

    123(one hundred and twenty three)

    -123(minus one hundred and twenty three)

    123456789(one hundred and twenty three million four hundred and fifty six thousand seven hundred and eighty nine!)

    So an intcan be a value like 1, but it CANNOTbe a value with any decimal places like 1.0or 5.5etc.

    If we enter: type(1)or type(-5)into the Python shell it responds:

    Quiz: What would say the difference is between the values 1 and 1.0 or 1.0f?
    23
    Basic Data Types: float

    floats are like ints, but they CANhave decimal places.

    Examples of floatdata could be:

    0.0(zero point zero)

    123.4(one hundred and twenty three point four)

    -123.456(minus one hundred and twenty three point four five six)

    3.142(three point one four two)

    Floats can generally hold any value which can be represented as an int, but not vice-versa! (Or at least not without discarding all the decimal places!) By this I mean, we can decide to convert the intvalue 123into a float 123.0without losing any data, but we can’t convert the float value 123.4into an intwithout losing the .4part!

    If we enter: type(1.23)into the Python shell it responds:

    Note: A widening conversion, say from intto float is nearly always safe (no data lost), while a narrowing conversion, such as from float to intis typically NOT safe!
    24
    Basic Data Types: str

    Strings are containers for alphanumerical characters, and generally can’t be used for math. The actual name of the string type in Python is str.

    Examples of stringdata could be:

    “Hello”

    “This is a string”

    “To be or not to be, that is the question.”

    Strings can be of any length up to the available RAM you have available on your system, so if you really wanted to store several copies of the book “War and Peace” in a single string, you could!

    If we enter: type(“I bet this is a string”)into the Python shell it responds:

    25
    Basic Data Types: str(Cont’d)

    When we specify strdata, we mustenclose it in somekind of quotes so the interpreter knows to treat it as string (i.e. alphanumerical) data!

    We can use quotation marks: “like this”

    Or we can use single quotes: ‘like this’

    Or we can use three-sets of quotation marks: “””like this”””

    If we want to actually use quotes in our data, for example:
    “I’m putting this in “quotes” because I can.”

    Then we can either do what’s called escaping the quotes we want to include in our data by placing a blackslash( ) before them, so our example becomes:
    “I’m putting this in ”quotes” because I can.”
    Single quote in I’m
    Backslashes directly before any quotation mark we want included
    Two quotation marks
    This will NOT work!
    26
    Basic Data Types: str(Cont’d)

    If we decide to enclose our string in a set of three quotation marks, then the formatting of our string is preserved across multiple lines and we don’t need to escape any ‘or “characters. For example:
    “””I’m putting this in “quotes”
    because I can.”””

    Will come out as:
    I’m putting this in “quotes”
    because I can.

    Which is exactly as we laid it out in the first place!
    Blank line here!
    Blank line here, too! (i.e. formatting preserved).
    27
    Basic Data Types: str(Cont’d)

    The reason it’s important to put string data in quotation marks of some kind is so that the interpreter knows how to deal with the data.

    For example if we enter the following into the Python command line we get a valid result:

2.2 + 3.3
5.5

But how about if you enter the following?
2.2 + “Bob”

What do you think will happen?
28
Basic Data Types: str(Cont’d)

What we get it this:
2.2 + “Bob”
Traceback(most recent call last):
File “”, line 1, in
TypeError: unsupported operand type(s) for +: ‘float’ and ‘str’

Which basically means that Python doesn’t know how to use the + (plus) operator with a floatand a str! And rightly so! It doesn’t make a lot of sense to add a number to something which isn’t a number!

Okay, so now let’s see if you can guess what happens when you enter this:
“2.2” + “Bob”
Notice the quotation marks around “2.2”!
29
Basic Data Types: str(Cont’d)

That worked without complaint, and we got the result:
“2.2” + “Bob”
‘2.2Bob’

So why did: 2.2 + “Bob”fail, while “2.2” + “Bob”worked?

In this case, it’s because Python knows that if you have two pieces of string data, and you “add” them together, then it should concatenatethe two separate strings into a single new string!

We can add up as much as we like! For example:
“There’s” + “Not” + “Much” + “Whitespace” + “In” + “This” + “String”

Would become:
“There’sNotMuchWhitespaceInThisString”
Concatenate: verb,link (things) together in a chain or series.
30
Standard Mathematical Operators

Now we know about some of the most common types of data we might want to work with, it’s time to move on to some of the operators than help us perform calculations.

If you’ve programmed in any language before then you’ll already be familiar with many of them, although there are some Python-specific operators, too.

The standard “big four” operators are:
Operator Symbol
Operator Name
Example
+
Plus

10 + 2 equals 12

Minus
10 -2 equals 8
*
Multiply
10 * 2 equals 20
/
Divide
10 / 2 equals 5
31
Operator Precedence

The order in which operators are applied to data is really important, and there’s a simple rule that governs which “value-pairs” in a calculation get calculated before others!

For example, what’s the result of the following calculation?
2 + 10 * 5 = ?!?

Clue: BODMAS!
32
Operator Precedence (Cont’d)

In the previous question, we could either say the answer is 60 by calculating:
(2 + 10) * 5 = 60

Or we could say that the correct answer is 52 by calculating:
2 + (10 * 5) = 52

If you said52 then you’d be correct! Because according to BODMAS, the order in which we calculate the “value-pairs” is:

Brackets

Orders (i.e.powers and roots like 32or 9)

Division

Multiplication

Addition

Subtraction
33
Operator Precedence (Cont’d)

Let’s do some examples… What is:
1.
5 + 6 -7
2.
5 + 6 * 7
3.
(5 + 6) * 7
4.
32/ 3 + 4 -5
5.
42/ 2 + 4 * 5
BODMAS
Brackets
Order
Division
Multiplication
Addition
Subtraction
34
Operator Precedence (Cont’d)

Let’s do some examples… What is:
1.
5 + 6 -7= 5 + -1= 4
2.
5 + 6 * 7= 5 + 42= 47
3.
(5 + 6) * 7= 11 * 7= 77
4.
32/ 3 + 4 -5= 9 / 3 + 4 -5= 3 + 4 -5= 3 + -1= 2
5.
42/ 2 + 4 * 5
= 16 / 2 + 4 * 5= 8 + 4 * 5= 8 + 20= 28
BODMAS
Brackets
Order
Division
Multiplication
Addition
Subtraction
35
Working With Variables

A variable is a piece of data which we can give a name.

For example, to define (i.e. create)e a variable called luckyNumberwhich stores the number 6we could use the command:
luckyNumber= 6

Weknow that 6 is an int-but how does Python know that you’re storing an integer? Like we saw earlier, and just like us -it looks at the value and determines the type of data automatically!

If we now enter: type(luckyNumber), it says:


So far, so good!
36
Working With Variables (Cont’d)

Now if we want to change the value of the luckyNumbervariable, we can simply give it a new value by issuing a statement such as:
luckyNumber= 16

And to display the number we can use the print()function like this:
print(luckyNumber)

Which will give the following output:
print(luckyNumber)
16

What if we want the original value of 6 back? Do we have a copy stored somewhere? Nope! When we overwrote the old value with the new value -that’s exactly what happened -it got overwritten!
Question: What could we do if we wanted to keep track of the old (i.e. original) number?
37
Working With Multiple Variables

Let’s say we create two variables like this:
firstNum= 3
secondNum= 4

Now we can add them up and print out the sum like this:
print(firstNum+ secondNum)

In the above scenario we’ll get 7

What if we said: print(firstNum-secondNum)?

What about: print(firstNum* secondNum)?

Now what happens when we use the divideoperator?
38
Working With Multiple Variables (Cont’d)

In Python 3, when we divide one int(eger) by another int-the resultWILL ALWAYS BE AFLOAT!

This is NOT THE SAME AS MOST LANGUAGES!

You and I know that 3 divided by 4 is 0.75, but in integer math it’s not.

Instead, 3divided by4 is 0i.e. it rounds down to zero because integers can’t store any decimal places, such as the 0.75!

But Python 3 changes the result of ANYdivision to a float!

Let’s take a look at an example…
UNUSUAL!
39
Working With Multiple Variables (Cont’d)

Try this:
first = 2
second = 4
result = first / second
print(result)
type(result)

Then this:
first = 2
second = 4
result = second / first
print(result)
type (result)

In summary -all standard division results in a value that is a float, even if the value involved are integers. In most languages the integer value 2 divided by the integer value 4 would be 0, and 4 divided by 2 would be 2(NOT2.0)!
2 / 4 = 0.5

4 / 2 = 2.0

While normal for Python, this is notnormal in most languages!
40
Working With Multiple Variables (Cont’d)

But… we can use an integer division operatorinstead for division to act as we might expect in to -which in Python 3 is the double-slash:
first = 3
second = 4
result = first // second
print(result)
type(result)
FYI: // in most languages is a comment, not integer division!
3 // 4 = 0

While used in Python, this operator doesn’t even exist in most languages!
41
Working With Multiple Variables (Cont’d)

Why can variables change type?

Because Python is a loosely-typed language that can easily change the data ‘type‘ associated with any variable name whenever it chooses!

And it chooses to give an accurate result for division rather than rounding that result, unless you demand otherwise!

In fact, after every change to the value of a variable it MUST re-check the type to ensure it has an up-to-date value type in order to process any further calculations using that variable correctly.
42
Working With Multiple Variables (Cont’d)

What this also means is that we can change the type of our variable whenever we choose.

This makes the Python language very flexible, but if we’re not careful it can lead to errors -for example, the following sequence of statements is legal:
luckyNumber= 6
luckyNumber= 6.0
luckyNumber= “six”
luckyNumber= “elephants”

But what happens if we divided a value by our luckyNumbervariable after this sequence of statements?

Nothing great -because you can’t divide a value by a string!So in this instance, we’d need to either keep track of the typeof our luckyNumbervariable, or wrap its usage in exception handlingcode to make it safer to use (more on which in week 7).
43
Command Line Vs. Scripts

So far we’ve used the Python command line to interactively do a small amount of programming, but as soon as we close down the window all our code will be gone!

The more common way of writing programs is to place them in a document which we can save, and then execute them through the interpreter.

The file extension for python scripts is: .pyi.e. test.py, MyProgram.pyetc.

To create a new Python script, simply right-click on the desktop and choose New | Text Document, and then give it a name that ends with the .pyextension. For example HelloWorld.py
44
Command Line Vs. Scripts (Cont’d)

To run a saved Python script in IDLE (Python’s default IDE) we can launch the IDLE editor, then go File | Open and select our .pyscript, then either choose Run | Run module or hit F5 (shortcut) to run it:
45
Hello, Bob!
•Now let’s start working with variables a little more. Let’s create a second new file called 2-HelloBob.pyand open it to edit it then put the following code:
name = “Bob”
print(“Hello, ” + name + “!”)
•Which when run will produce the following output:
46
Hello, [Name]!

Now we’re going to start getting input from the user -so let’s create another new file called 3-HelloName.pyand open it to edit:

This time, we’ll enter the following two lines of Python script:
name = input(“Please enter your name: “)
print(“Hello, ” + name + “!”)

As I’m sure you’ve guessed -this will ask for your name, and then say hello to you!
47
The inputFunction

When we want to get console input from the user, we use the input method.

We typically assign the result of running the input method to a variable as we just saw when we wrote:
name = input(“Please enter your name: “)
print(“Hello, ” + name + “!”)

When using the input function, the typeof the data returned is always a string.

This will cause us problems if we did something like this:
number = input(“Please enter a number between 1 and 10: “)
sum = number + 5
print(“Adding 5 to that gives: ” + sum)
Nope!
48
The inputFunction (Cont’d)

The reason we’re going to have a problem is because we’re getting some data and assigning it to a variable called number…

…and then we’re trying to add together that numbervariableand an integer -but the input function converts whatever data is entered into a string!

And as we saw previously -we can’t add an intand a stringtogether!
49
The inputFunction (Cont’d)

So how do we get around this problem?

We have to convert the entered data into the type we want it to be!

For example:
number = input(“Please enter a number between 1 and 10: “)
sum = int(number)+ 5
print(“Adding 5 to that gives: ” + sum)

The intfunction attempts to convert whatever is in the brackets after it into an integer.

It will fail if we give it data which cannot be converted into an int, for example if we wrote the following then the conversion would fail:
number = int(“This won’t convert to int!”)
50
The inputFunction (Cont’d)

We could also do it like this, if we wanted to:
number = int( input(“Please enter a number between 1 and 10: “) )
sum = number + 5
print(“Adding 5 to that gives: ” + sum)

They both work the exam same way and provide the same result.

Wherewe do the conversion doesn’t matter -thatwe do the conversion matters!

Also, this “conversion” has a special name -it’s called a cast. So you might “castan intto a float” or “casta string to an int” etc.

Make sure you know what castingis (i.e. changing the data typeof a variable) -it’s a very important thing to know. Trust me on this.
51
String / Print Substitution

As we’ve seen, we can mix string literals (i.e. “Enter a number”, “The sum is: “, “Hello!”) with variables by using the + operator when either creating or printing strings:
luckyNumber= 6
print(“My lucky number is ” + luckyNumber)

Or, we could do it like this :
luckyNumber= 6;
sentence = “My lucky number is ” + luckyNumber
print(sentence)

But there’s another way that we can do which is by substitution -you might prefer to do things this way, it’s entirely up to you!
Now: Give me at least three examples of “string literals”!
Same result!
52
String / Print Substitution (Cont’d)

So we could write some code like this:
num1 = int( input(“Please enter the first number: “) )
num2 = int( input(“Please enter the second number: “) )
sum = num1 + num2
print(“The sum of”, num1, “+”, num2, “is:”, sum)

We can also achieve the same output as the above by making the final line:
print( “The sum of + is “.format(num1, num2, sum) )

Each set of curly-braces, , in the above line will have the relevant variable substituted in its place, in the order they’re declared:
print( “The sum of + is “.format(num1, num2, sum) )
53
String / Print Substitution (Cont’d)

What if we make a mistake in the order of the value to substitute?
print( “The sum of + is “.format(sum, num1, num2) )

If we has num1has the value 1and num2hasthe value 2-then because we messed up thesubstitution order it would output:
The sum of 3 + 1 is 2

Which is obviously not right -and that’s a mistake on our part.

Point being: If you use order substitution then be careful with the order of your substitutions -because one looks exactly like another -and you have to make them match up correctly if you want things to make sense!

But…
Wrong order!
D’oh!
54
String / Print Substitution (Cont’d)

We can do a better job by substituting like this:
print( “The sum of 0 + 1 is 2”.format(sum, num1, num2) )

This has the benefit that when have a numbered(or “indexed”) substitution, we could do something like this if we wanted and it would all work out alright:
print( “The sum of 2 + 0 is 1”.format(num2, sum, num1) )
…but tocompensate…
Note: The order that we specify the variables to substitute is always the same, the first is 0, the second is 1 and so on!
0
1
2
0
1
2
Order has also changed!
Order has changed!
Order cannot change!
0
1
2
55
String / Print Substitution (Cont’d)

The final nice thing we can do if we use indexed substitution i.e. 0, 1 etc. is we can re-use substituted value, like this:
likeColour= “blue”
dislikeColour= “red”
print ( “I like 0 more than 1 because 0 is a calming colour”.format(likeColour, dislikeColour) )

This will produce the output:
I like blue more than red because blue is a calming colour

The post Introduction to Python, Operators and Data Types appeared first on My Assignment Online.

WeCreativez WhatsApp Support
Our customer support team is here to answer your questions. Ask us anything!
šŸ‘‹ Hi, how can I help?
Scroll to Top