Before you start this course, you must login to Replit
If you have forgotten your Replit account user name or password, ask your Coder Coach.
If you have forgotten your Replit account user name or password, ask your Coder Coach.
Students will create brand new code in main to perform specific tasks.
Write a program that:
Be able to read, comprehend, trace, adapt and create Python code using selection that:
The slides to accompany this section are here
The len() function returns the number of characters in a string. It takes the string as its parameter.
It’s one of the simplest built in functions so we will use it to introduce the skill.
Space is counted as a character, as is any punctuation.
This set of tasks will also introduce the concept of coding more efficiently by including the function in the print or selection condition. This can be applied to all of the subsequent functions (examples 3b & 4b), higher ability students will probably prefer this. If students struggle to conceptualise this then encourage them to call the function and return the result into a variable (examples 3a and 3b).
Example 1 – The function on its own
len("Banana")
Returns 6.
Example 2 – Storing the returned value in a variable
Returns the number 6 into the variable word_length
word_length = len("Banana")
Prints the data in the word_length variable
print(word_length)
Example 3a- Getting input and finding out its length
Gets input and stores it in the word variable
print("Enter a word")
word = input()
Returns the length of the string in the word variable into the variable
word_length
word_length = len(word)
Prints the data in the word_length variable
print(word_length)
Example 3b – A more efficient way of coding example 3a
Gets input and stores it in the word variable
print("Enter a word")
word = input()
Uses the len() function as part of the print() function. Removes the need for the word_length variable.
print(len(word))
Example 4a – len with selection
Gets input and stores it in the word variable
print("Enter a word")
word = input()
Returns the length of the string in the word variable into the variable word_length
word_length = len(word)
Prints a message if the string in word_length has more than 50 characters in it.
If word_length > 50:
print("Wow, what a long word!")
**Example 4b – a more efficient way of coding **
Gets input and stores it in the word variable
print("Enter a word")
word = input()
Uses the len() function as part of the condition. Prints a message if the string in word_length has more than 50 characters in it.
if len(word) > 50:
print("Wow, what a long word!")
Make sure that you check for the following things: