Write the code

print(1 * 2)
print(2 * 2)
print(3 * 2)
print(4 * 2)
print(5 * 2)
print(6 * 2)
A program is expected to display all numbers from 1 to 50 multiplied by two. Rewrite the start of this program to make it more efficient.

What is wrong with this code?

num1 = 65
num2 = input()

output = num2 - num1

This program is supposed to subtract 65 from a number but instead it just crashes. Fix the program so that it now displays the correct result such that if the user put in 75 the program would display 10.

String Functions

Learning Intentions

  • Test out functions in Python

  • Understand how strings can be manipulated

Success Criteria

  • I can explain what a function is
  • I can manipulate strings using functions in Python

What is a string?

  • String is the technical name for text in programming.

  • Strings are enclosed in quote marks (" ")

  • Numbers within the quote marks cannot be used as numbers (integers or floats) as the computer reads them as strings

     

Concatenation

  • Concatenation is the joining of two things, in the case of string concatenation, it’s the joining of two strings.

  • This is done with the + sign.

  • For example:

     

firstname = "John"
surname = "Balfour"
output = firstname + surname
print(output)

Functions

  • A function is something that takes something in, processes it and gives us an output.

  • Python’s print is a function which takes in a string from the user and displays it on the screen.

  • A function in Python is normally written as the name followed by brackets with any inputs (arguments) to the function inside the brackets:

     

print("Hello world")

String Functions: to uppercase

  • Strings functions work differently. They are instead chained to the end of a variable name:
     
       

     

myname = "John"
print(myname.upper())

Function readability

  • Python, like many other programming languages, aims to make function names as readable as possible.
  • For instance, isupper() is designed to check if a string is entirely uppercase whereas isnumeric() is used to check if the string is entirely numeric.
     

     

myname = "John"
print(myname.upper())

String functions: substring

  • We can also obtain a substring very easily in Python. This done with the index, which starts at 0. We use the [ ] to access a specific index.

     

     

     

    We can also obtain a several characters in Python in the same way, we just need to specify the range we want within the brackets:

     

first_name = "Joseph"
print(first_name[1])
first_name = "Joseph"
print(first_name[0:3])

Complete the worksheet.
For the first part, you will need to write what you expect to come out of the function and then test functions using Python and write what you get.

Task

JB
6 Software Development : 6.1 String functions
© J Balfour
Tools