Tuesday, March 12, 2024

Subroutine

 

Subroutine

So far, when we wanted to repeat code, we have had to use loops or copy and paste code.
What if I told you there was a way to use code or call it and use it anytime anywhere??
That is a subroutine!!
A subroutine tells the computer that a piece of code exists and to go run that code again and again...

Just like a recipe

Subroutines work like a recipe in a cookbook. If you want to know how to make a cake, you don't have to start from scratch every time. You can use a recipe to get the same quality each time.

How do we define a subroutine?

A subroutine is defined by:

def (which stands for definition)

You need to give the subroutine a name (and just like with a variable, you can't have spaces).


You need to add () even if there are no arguments followed by a colon :. The code needs to be indented.

Let's roll a random number on a six-sided dice. Copy the code below and click run.
def rollDice():
  import random
  dice = random.randint(1, 6)
  print("You rolled", dice)  

In this code, We have defined how to roll a dice , but we have not actually 'called' the program to run.

Call the Subroutine
Calling the subroutine means telling it to run.
We need to 'call' the code by adding one more line to our code with the name of the subroutine and the empty ():

def rollDice():
  import random
  dice = random.randint(1, 6)
  print("You rolled", dice)

rollDice()

Note that when you call the subroutine, you need to ensure you do NOT indent.

I can even add a range and roll the dice 100 times by adding this code:

def rollDice():
  import random
  dice = random.randint(1, 6)
  print("You rolled", dice)
for i in range(100):
  rollDice()

Note - Just like with variables, you cannot have spaces with subroutines (onlyCamelCase or_using_underscores). You need to add () in the first line, even though there is no argument. & When you call your subroutine, make sure it is NOT indented.

Coding Challenge : - 
1.Create a subroutine with both a username and password.
2.Create a loop to prompt the user again and again until they put in the correct login information.

What is your username?: name
What is your password? password

Whoops! I don't recognize that username or password. Try again!

What is your username? Angshu
What is your password? Loveu

print("Login System")
print()
def welcome_login():
  while True:
     user_name= input("what is your name:")
     password = input("what is your password:")
     if user_name=="Angshu" and password =="loveu" :
        print("Welcome to replit")
        break
     elif user_name!="Angshu" and password !="loveu":
        print("Whoops! I don't recognize that username or password. Try again!")
        continue

welcome_login()

No comments:

Post a Comment

  2D Dictionaries Remember that dictionaries are very similar to lists, except that they store data as key:value pairs. The value is what it...