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()

starting of Libraries

 

Libraries

Libraries are collections of code that other people have written. Video games often use massive libraries (for example: game engines) to create the epic water reflections, 3-D graphics, etc.

We are going to start a bit smaller by just generating random numbers. (After all, random numbers are the basis of most games).

Random Library

We can use a library by writing import and then the library name.
This should always be one of the first lines of code.

Let's import a library that will generate random numbers:  

import random

How random works 

In the code below, we have created a variable, 'myNumber'. making it equal to a random number given to  by the randint (random integer) library. I add the lowest number (1) and the highest number (100) that can be picked and the computer will generate a number at random.

import random
myNumber = random.randint(1,100)
print(myNumber)

The way libraries work. The names of functions and variables in libraries may be similar to the names I chose for my functions and variables. The way to access functions and variables in other libraries is to put random. in front of the library name.


Now the computer knows to "go in the random library, find randint, and give me a number between 1-100."

import random
for i in range(10):
myNumber = random.randint(1, 100)
  print(myNumber)

Number guess challenge :-
Make the number generator completely random between 1 and 1,000,000. Now, the game will always have the user guess a random number each time (now the user can't cheat...
Totally Random One-Million-to-One
What is your guess?: 500000
Too low
What is your guess?: 750000
Too high
What is your guess?: 600000
Too low
What is your guess?: 650000
Correct!
It took you 4 guesses to get the number correct.
Click 'run' to try again with a different number.

print("Totally Random One-Million-To-One")
print()
import random
rand_number= random.randint(1,10000)
attempt=1
for i in range(1000): 
  guess_number= int(input("Guess a number between 1 to 10000:"))
  if rand_number == guess_number :
    print("you guess it right ")
    attempt += 1
    break
  elif rand_number > guess_number and rand_number - guess_number>5000:
    print("you guess it wrong and it is too low ")
    attempt += 1
    #continue
  elif rand_number > guess_number and rand_number - guess_number<=500:
    print("you guess it wrong and it is low ")
    attempt += 1
    #continue
  elif rand_number < guess_number and  guess_number-rand_number >5000:
    print("you guess it wrong and it is too high")
    attempt += 1
    #continue
  elif rand_number < guess_number and rand_number - guess_number<=500:
    print("you guess it wrong and it is high ")
    attempt += 1
    #continue
print("total attempt is",attempt)

 

For Loop

A while loop is perfect to use when we don't know how many times we want the loop to repeat.

If we have an idea of how many times we want the loop to repeat, we can use a for loop to loop code in exactly the same way the while loop did.

However, we can set up the variable, control condition, and increment all in ONE line of code.


Let's compare:-

Here is how we created a counter with a while loop:

counter = 0
while counter < 10:
  print(counter)
  counter += 1  

And here is the same counter using a for loop:

for counter in range(10):
  print(counter)

Range

range(10)

Note: The variable is only there during the loop, not after it is completed.

Coding Challenge 
Building a loan calculator where inputs are total amount of loan , for how much years and the interest rate will be the input. output will be the total amount to be paid back after the tenures.

print("Loan Calculator")
print("")
total_loan =0
loan_amount=int(input("How much money u want to take as a loan:"))
APR_percentage=int(input("tell me the APR percentage:"))
total_years = int(input("How many years u need to pay the loan:"))
total_loan_yoy = loan_amount
for total_years in range(total_years):
  total_loan_yoy= total_loan_yoy + (total_loan_yoy*APR_percentage)/100
print("year",total_years+1,"is",round(total_loan_yoy,2))


What can range really do?

Give range one number, and it will count up to that number. However, you can actually give the range function a few options...
starting value: what number do you want to start with?
ending value: the number after the number you want to end with (example: if you type 10 as the ending value, the computer will count until 9)
increment: How much should it increase by every time it loops? (example: Do you want to count by 1s, 5s, 10s?)


The ending value has an unsaid 'less than'. Meaning the computer will stop one number before the ending number that is written in the range.

Let's try it out

The first number in this range, 100, is the starting value. The second number in this range, 110, is the ending value (Remember to always put the ending number as one more than where you want to end up).

for i in range(100, 110):
  print(i)

What do you expect to print with the range below?

for i in range(1, 7):
  print("Day", i)

Did you notice that the counter stopped at 'Day 6'? Change the ending value to be one more than the last number you want shown---in this case, 8 because we want to display 7 days of the week

for i in range(1, 8):
  print("Day", i)

Code - Thirteen Times Table

print("Thirteen Times Table")
for i in range(1, 13):
  print(i, "x 13 =", i * 13)

Increments
We know that this range will start at 0 and continue to 999,999 (which is the number right before the ending value written). The number will increase in increments of 25 each time.

for i in range (0, 1000000, 25):
print(i) 

Counting Backward  

In this example, we are starting at 10 and counting backward to 0 (because 0 is what comes right before the ending value listed), and counting backward 1 each time.

for i in range(10, -1, -1):
print(i)


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