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...
A subroutine is defined by:
def (which stands for definition)
You need to add () even if there are no arguments followed by a colon :. The code needs to be indented.
def rollDice():
import random
dice = random.randint(1, 6)
print("You rolled", dice)
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()
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