Fundamentals (Good) Exercises

Exercise 1 (f-strings to the rescue)  

Python allows you to solicit information from the user.
One way to do this is using the input() function. Here is an example of how to use it.

user_input = input('Please provide me with a number?')
print('You entered', user_input)

Ask for the name of the user and then print out the greeting:

“How you doin NAME!”

I realise that most of you are far too young to recognise this reference; so see here

Ask for the name of the user, then ask for the age of the user and print out the introduction:

“My name is NAME and I am AGE years old.”

You are given the value of \(\pi\) as \(3.141592653589793\).

Define the variable pi with this value and then use it to produce the following using f-strings.

The value of pi to 2 decimal places is: 3.14
The value of pi to 3 decimal places is: 3.142
The value of pi to 4 decimal places is: 3.1416
Fruit Price
Apple $0.99
Banana $0.59
Orange $1.29

Use the data in the table to produce the following printout.

Apple      $ 0.99
Banana     $ 0.59
Orange     $ 1.29
********** $*****

Note that the names occupy a span of 10 units while the prices occupy 5 units. These are separated by a single space. I have indicated these using *.

Exercise 2 (What is your grade?) Write a Python program that takes a numerical grade (0-100) as input and outputs the corresponding letter grade based on the following criteria:

Grade Score Range
A 70 - 100
B 50 - 69
C 35 - 49
Fail 0 - 34

Note:

  • Here is an example of the type of exchange expected.

    Enter the student's score: 85
    The student's letter grade is: A
  • Ensure your program handles unexpected inputs gracefully and displays a relevant error message.

Exercise 3 (Debugging Code) The code below shows a Python function that calculates the factorial of a given number. However, there are three errors. Your task is to identify and fix the errors, complete the code, and ensure it runs correctly.

Yes! You do not yet know what functions are and how loops work. But the errors in the code are related to what we just discussed!

def factorial(n):
    if n > 0:
        return "Invalid input"
    elif n != 0:
        return 1
    else:
        result = 1
        for number in range(1, n+1):
            result += number
        return result


print(factorial(5))   # Testing, expected output: 120
print(factorial(-1))  # Testing, expected output: Invalid input
Back to top