Remember that when you see a line of code with
>>> you should type in the code and run it immediately.
When you see a block of code without
>>> you should type in all the code before running it.
In English we have the if-then construction: "if the soil is dry then I water my plants''. I check to see whether not the statement "the soil is dry'' is true, and in the case that it is, I perform the operation "water my plants''.
Concept 1. A conditional statement in a program is a statement that only performs some operations when some condition is met.
In Python we use the
if command for conditional statements. Type in the following program, taking care to notice the colon and the indentation. What do you think the program will do? (Remember that
a % b is the remainder when
a is divided by
# A program to see if a number is odd. number = int(input("Enter an integer: ")) if number % 2 == 1: print("That is odd.") print("But not too odd.") print("Thank you.")
Run this program a few times and understand which print statements are printed when. Note how the indentations make a difference.
In general, a Python
if statement has the following form:
if boolean_expression: do_this and_do_this carry_on_here
The indented lines are executed only if the Boolean expression is
True, otherwise they are ignored. There can be more than two indented lines.
If you want to do something different in the case that the Boolean expression is
False, you can use the
else statement. Add two lines to the middle of your program so that it now looks like this (taking care with colons and indentations):
# A program to see if a number is odd or even. number = int(input("Enter an integer: ")) if number % 2 == 1: print("That is odd.") print("But not too odd.") else: print("That is even.") print("Thank you.")
Again, run it a few times to see what happens.
Exercise 3.1. Write a program using
else (but not using
max()) that inputs two numbers and prints out the larger of the two.
A string is basically a piece of text, but it can have other symbols in it.
>>> menu_item = "Spam & eggs" >>> print(menu_item) >>> type(menu_item)
A string is denoted by having quotation marks at each end, either using double quotation marks (
") or a single quotation mark (
'), but with the same at each end of the string. Use the up-arrow to change the first line above to
>>> menu_item = 'Spam & eggs'
Then re-execute the next two lines, make sure that it gives the same answer.
To join together, or concatenate, two strings you use the
>>> special_menu_item = menu_item + " with extra spam" >>> print(special_menu_item)
We can use
+ on numbers and on strings. What might happen if you add a number to a string? Guess what the following would output, then type it in.
>>> string = "6" >>> number = 5 >>> print(number + string)
Python doesn't know what to do: this is called a type error.
We need to make sure that they are both strings, or both numbers.
We can try to convert a string to a number using
int(), and can convert a number to a string using
Which of the following commands will Python not like? Try and see.
>>> int("7") >>> float("7") >>> int("7.5") >>> str(7) >>> float("parrot")
We can now 'add' the number and string in two different ways.
>>> print(str(number) + string) >>> print(number + int(string))
Make sure you understand why you get two different answers.
There is a Python function
len() that tells you the length of a string.
Exercise 3.2. Use the functions
len() to find out how many digits there are in 2100. (On the last worksheet you had to count them by hand.) Why did you have to use
Each character in a string has an index that denotes its position. Typing
string[i] gives the character at index
i. However it is important to note the following important convention:
Python starts counting from zero!
Counting from zero is a common feature of computer languages and there are good reasons for it, however, it often trips up beginners from time to time. This means that the index of the first character in a string is 0 and the index of the final character is one less than the length of the string.
>>> bird_name = "parrot" >>> print(bird_name) >>> print(bird_name) >>> print(bird_name, bird_name)
What do you think would happen if you type in
bird_name? Try it!
Type in the following program, replacing
Your Name by your own name. See if you can guess what it will do, then run it.
my_name = "Your Name" index = 0 while index < len(my_name): print(index, my_name[index]) index = index + 1
You can also count from the end of a string by using negative indices. In that case, an index of -1 corresponds to the last character in a string.
>>> "spam"[-1] >>> "spam"[-3]
When you use
print() with a list of items, it places a space between each item.
>>> print("spam", "egg", "beans")
You can change this behaviour by adding
sep=str to the end of the print statement, where
str is the string you want to separate the items with.
[You don't put spaces around this equals sign as it's not an assignment; we'll return to this in two weeks' time.]
Change the last line you typed in to the following.
>>> print("spam", "egg", "beans", sep=":")
You can remove all separation between the items by using the empty string:
Try it in the above example.
Exercise 2.3. Write a program that takes a string as input. If the length of the string is odd it prints out the middle character. If the length is even it prints out the middle two characters.
There are certain special characters you can include in a string by using the backslash '
\', to form an escape sequence.
A new line is obtained with
A tab (like pressing the tab key in a word processor) is obtained with
This can be useful for aligning text.
A tab will move the cursor to the next tab stop and these are located every eight characters.
Using the escape characters for inverted commas and apostrophes allows us to form strings like:
He said "Don't do that!"
This would otherwise not be possible.
Try the following and then try it without the backslashes.
>>> print("He said \"Don\'t do that!\"")
At the end of a
end=str to the print statement.
Try the following.
i = 0 while i < 100: print(i, end="\n") i = i + 1
end="\n" with, e.g.,
string = "hello" i = 0 print(string) while i < len(string): print(string[i], end=":") i = i + 1 print(string)
attempt = input("Enter the password: ") if attempt == "password"[-2]: print("You may enter.") else: print("Go away!")
incomparison operator can be used to test if a character is contained in a string. So
"a" in "spam"gives
"i" in "team"gives