Introduction To Python Programming
Introduction To Python Programming
Introduction To Python Programming
Hello, World!
This is a comment
Write a program that prints out the message: that is not run by the
program
Hello World!
Hello, Vic
operator operation
+ addition
- subtraction
* multiplication
/ division
** to the power of
The power operator is represented by a double asterisk (**) and works like this:
n = 10
print(n**2)
“100”
Investigating strings
Once we've stored a word or sentence in a string variable, we might want to investigate some
of its properties. The simplest of these it its length.
We can find out how long a string is using the len function:
Calculates the
number of characters
in “hello world”
Crazy! It doesn't do what we want at all - the answer should be 11. The reason is that
numbers and strings are treated differently in Python because they are different types of
information. The problem here is that input always gives us back a string regardless of what
the user enters. Let's see that again without the input:
1-Up
Write a program that reads in a number (integer) as input, adds 1 to it, and then prints out the
result. Here is an example interaction between your program and the user:
When you are passing multiple arguments to the print function (using a comma to separate
them), you don't need to convert the numbers to strings:
The + operator is confused here because we cannot add a string and an integer. When this
happens, Python gives a runtime error (in this case, a TypeError). The program syntax is
correct, but the program is logically broken.
To fix it we need to use the str function to turn the integer back to a string:
When you finish solving a question, you're super happy and want to express a larger amount
of happiness by adding more underscores between the carets: ^_____^.
After telling a couple of your friends how happy you are, writing out these emoticons is
becoming tiring. You decide to use your new programming skills to help you out!
Write a Python program to read in a number that indicates how happy your emoticon should
be. For example:
Repeaterbot
In your travels through space time you come across a robot with the useful (?) ability to
repeat everything you say, as many times as you want. Write a program to control this robot.
In the real world we often need to make decisions based on a situation. For example, how we
are going to travel to work or school today:
The diagram shows the two different options of how to get to work, either by taking the bus
or walking. The red diamond which asks 'is it raining?' determines which way the program
will flow.
We can implement this in Python using control structures. The first control structure we will
look at is the if statement.
What if it is raining?
Let's write a program that would help us make a decision about how to get to work. Of course
the computer can't check the weather on its
own, so it will have to ask us.
The first if statement controls the execution of the first print statement because it is
indented under it. If the user says it is raining, the program advises catching the bus.
The second if statement controls the execution of the second print statement because it is
indented under it. If the user says it is raining, the program advises walking.
The if statement is controlling the program by changing its behaviour depending on the
user's input. This why it is called a control structure!
Assignment vs comparison
You will notice in our examples that we are using two equals signs to check whether the
variable is equal to a particular value:
== means EQUALS
EXACTLY THE SAME
V. Farrell (based on Grok Learning notes 2015)
This can be very confusing for beginner programmers.
A single = is used for assignment. This is what we do to set variables. The first line of the
program above is setting the variable name to the value "Grok" using a single equals sign.
A double == is used for comparison. This is what we do to check whether two things are
equal. The second line of the program above is checking whether the variable name is equal
to "Grok" using a double equals sign.
If you do accidentally mix these up, Python will help by giving you a SyntaxError. For
example, try running this program:
Open sesame!
Ali Baba is trying to open a cave door to find the treasure. His brother overhears thieves
saying the password, but he can't quite work out what it is.
Write a program to ask Ali for a password. If the password is correct, the cave door will be
opened. Otherwise nothing will happen.
Your program should work like this when Ali says "Open sesame!":
You can check whether the conditional expression is evaluating to True or False by testing it
directly:
For example, we may want to welcome a friend, but find out more about someone we don't
know. We can do that using an else clause:
Here, either the first or second print statement will be executed but not both. Notice the
condition in the else clause must be followed by a : character, just like the if statement.
As well as being neater, the else statement is more efficient because it does not have to
perform another conditional evaluation.
If the user enters "Earth" the response makes sense. However, if the user enters "Jupiter"
the response doesn't really make sense (try it).
This is because in the real world, there are more than two planets, but our program only deals
with two cases. We will solve this problem later in the module.
Access denied
You are trying to log in to your old computer, and can't remember the password. You sit for
hours making random guesses... I'm sure you thought it was funny back when you came up
with that password (chEEzburg3rz).
Write a program that tells you whether your guess is correct. If it is correct, it should grant
access like this:
Operation Operator
equal to ==
not equal to !=
less than <
less than or equal to <=
greater than >
greater than or equal to >=
Experimenting with
comparison
Let's try some more examples to demonstrate how conditional operators work. Firstly, we
have less than or equal to (<=)
In the black
Write a program that works out whether your bank balance is in the red. If the number of
dollars is zero or positive it should work like this:
In the program below we have indented one if statement inside another one. That means the
second condition will only be tested if the first condition is True.
There is only one value of x that will cause both of these messages to be printed. Experiment to work
out what it is.
Interplanetary
visitor
Remember our program that tried to greet
interplanetary visitors correctly? We can
now extend this so that it makes sense
regardless of what planet the user is from.
Method of transportation
Write a program to tell you which method of transport to use for your next outing.
The first step in this decision is based on the weather. If it is currently raining, you should
take the bus.
If it is not currently raining, your method of transport should be determined by the distance
you need to travel. If the distance is greater than 10km, you should take the bus. If it is
between 2km and 10km (inclusive), you should ride your bike, and if it less than 2km, you
should walk. The distance should always be a whole number.
Your program should only ask for the distance if it is relevant to the answer. That is, if it is
raining, it shouldn't ask you how far you need to travel.
The first thing we are going to do is check the contents of a string, to see if it contains a
particular character. To do this, you can use the conditional operator in, like this:
Notice that at the moment the program can only deal with lowercase letters (try entering Xavier).
We'll solve this problem in the next section.
Aardvark!
The aardvark ("digging foot") is a medium-sized, burrowing, nocturnal mammal native to
Africa.
Write a program to detect aardvarks in an input string. Your program needs to find cases
where the aardvark appears in lower case (it could be inside a longer word). For example:
The method we are using here is lower. The msg string contains a message in mixed case,
and when you call the lower method it returns a message
in lowercase only.
If we wanted to correct the user's input so that their name had traditional English capitalisation (the
first letter capitalised), we could use the capitalize method:
Don't SHOUT!
We all know how annoying it is when people on forums SHOUT all the time. Write a
program to convert their SHOUTING (uppercase characters) to polite talking (lowercase
characters).
For example, to work out how many times 'l' appears in 'hello world':
Remember that the convention for calling string methods is that the string we are manipulating comes
first, and then the method name, with any other information that is required passed in as arguments.
You can also access strings from the other end using a negative index:
The string 'hello world' only has 11 characters, and we are trying to access character 12
(remember we start counting from 0).
Broken keyboard
Your friend's keyboard is misbehaving, and her "a", "e", and "o" keys are broken. To
compensate, when she wants to type an o, she types ###. For an e she types ##, and for an a
she types %%. Fed up with trying to interpret this ridiculous code, you decide to write a
program to decipher her messages instead.
Write a program to read in some text typed by your friend, and output the corrected text.
Your program should work like this:
If the name has 3 or fewer letters, your program should work like this: