Learn to Code via Tutorials on Repl.it!

← Back to all posts
How to use a subroutine in Python
DigitCommander (35)

I have used my Quiz V2 repl in this tutorial because it has a subroutine in line 169.

So, first we use the define function:

def inputAnswer()

This is the name of the subroutine.
Next we use userAns (which stands for user's answer)

def inputAnswer()
  userAns = ""
  while userAns not in ["A", "B", "C", "D", "E"]:

This is the part when the user hasn't selected an answer yet.
Thirdly, we input a message that tells the user what to select.

def inputAnswer()
  userAns = ""
  while userAns not in ["A", "B", "C", "D", "E"]:
     userAns = input("Select answer A, B, C, D or E: ").upper()

The upper function returns the uppercased string from the given string, i.e. userAns = input... would be the given string, and while userAns not in... would be the uppercased string.

Lastly, we return the subroutine. This is the completed code.

def inputAnswer()
  userAns = ""
  while userAns not in ["A", "B", "C", "D", "E"]:
     userAns = input("Select answer A, B, C, D or E: ").upper()
return userAns

This subroutine is based around the userAns variable, so that is why the return function was labelled userAns.

You can find the quiz below this tutorial.

I hope you found this useful, so feel free to give feedback in the comments and upvote this.

  • DigitCommander
Comments
hotnewtop