Name - Grade - / 37: National 5 Computing Homework
Name - Grade - / 37: National 5 Computing Homework
Name - Grade - / 37: National 5 Computing Homework
CPU
All programming languages can store and manipulate text using string variables and build in functions.
Some examples of string handling, in the programming language Python are shown below:
Length of String sentence = “I never could get the hang of Thursdays” Output from Program
sentencelength = len(sentence) 39
print(sentencelength)
For each of the following problems, think through the code and write down the output from each program.
The problems will get harder and harder.
Output from Program
1. productName = “The Hobbit” (1)
print (productName) The Hobbit
Python has many other functions used to manipulate strings. Here is one more:
Count: #This returns the number of times text is found in a given string
Output from Program
advice = “In winter, sensible people stay indoors”
print (advice.count(“in”)) 2
#Note that the output is 2 because the follow “in”s are found in the advice string:
In winter, sensible people stay indoors
The first “In” has a capital I so isn’t counted.
20. The following program uses string handling to create a simple password. Can you work out what
the password is? (4)
statement = “When Mr. Bilbo Baggins of Bag End announced”
letter1position = statement.count(“a”)
letter2position = statement.count(“e”)
letter3position = statement.count(“i”) Output from Program
letter4position = statement.count(“o”) ehhe
letter1 = statement[letter1position-1:letter1position]
letter2 = statement[letter2position-1:letter2position]
letter3 = statement[letter3position-1:letter3position]
letter4 = statement[letter4position-1:letter4position]
password = letter4 + letter2 + letter3 + letter1
print (password)