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)


Thursday, March 7, 2024

While Loop Extended

 

While Loop Extended

So far we've used break in the while True loop. break leaves the loop completely and runs the next unindented line of code. However, you may want to stop the code and start the loop from the top again. (This is ideal for building games!)


while True:
  print("You are in a corridor, do you go left or right?")
  direction = input("> ")
  if direction == "left":
    print("You have fallen to your death")
    break  

In the code above, the game runs and the user is asked if they want to go left or right. If the user chooses left, they fall to their death, and break will kick the user out of the loop.

The Continue Command

The continue command stops executing code in the loop and starts at the top of the loop again. Essentially, we want to kick the user back to the original question.



while True:
  print("You are in a corridor, do you go left or right?")
  direction = input("> ")
  if direction == "left":
    print("You have fallen to your death")
    break
  elif direction == "right":
    continue
  else:
    print("Ahh! You're a genius, you've won")

Adding continue will start the code from the start and ask the first question again: "Do you go left or right?".

The else statement refers to any input besides left or right (up or esc). Since the user is a winner, we do not want to use break or it would say they have failed.


Proceed to the Nearest Exit

The previous code continues to loop even after the user has won. Let's fix that with the exit() command


The exit() command completely stops the program and it will not run any more lines of code.

lets have an example 

while True:
  print("You are in a corridor, do you go left or right?")
  direction = input("> ")
  if direction == "left":
    print("You have fallen to your death")
    break
  elif direction == "right":
    continue
  else:
    print("Ahh! You're a genius, you've won")
    exit()
print("The game is over, you've failed!")

another example :- 
print("Let's play chutes and ladders. Pick ladder or chute.")
while True:
  print("Do you want to go up the ladder or down the chute?")
  direction = input("> ")
  if direction == "chute":
    print("Game over!")
    break
  elif direction == "ladder":
    continue
  else:
    print("Game over!")
    exit ()
print("Thanks for playing!")

problem solving :-

We are going to build a "Guess the Number" guessing game.

You are going to use a while loop and some of the concepts from the past few days.
1.Start by picking a number between 0 and 1,000,000. This will be your first variable.
2.Create a while loop to keep asking the user to guess your number.
3.If they are too low, tell them "too low." If they guess too high tell, them "too high."
4.If the user guesses correctly, tell them they are a winner (maybe add a fun emoji too!)
5. Count the number of attempts it took for the user to guess number. Make sure you only show that after they get the answer correct.

print ("One million to one")
print("")
guees_N = 89456
count = 0
while True:
  count += 1
  oneTime = int(input("Guess your number to match:"))
  if oneTime == guees_N :
    print("Correct")
    break
  elif  oneTime > 0 and oneTime > guees_N and oneTime-guees_N >= 5001 :
    print("too high")
    continue
  elif  oneTime > 0 and oneTime > guees_N and oneTime-guees_N <= 5000 :
    print("high")
    continue
  elif  oneTime >0 and oneTime < guees_N and guees_N - oneTime >= 5000 :
    print("too low")
    continue
  elif  oneTime > 0 and oneTime < guees_N and guees_N - oneTime <= 5000 :
    print("low")
    continue
  elif oneTime < 0:
    print("I don't want to play anymore")
    exit()
print("till run total guess",count)


Wednesday, March 6, 2024

 

All About Loops

While Loop :- 

A while loop allows your code to repeat itself based on a condition you set.

It is similar to an if statement in that you ask a question, and as long as the answer is true, the computer will repeatedly run the code.


Example - 

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

In the code above, the variable is called counter and starts at zero. The while loop has the condition saying, "while the counter is less than ten do this..."

In this case, print the variable and then add +=1 to that variable. As long as variable is less than 10, the loop will repeat the code.

Infinite Loop
You have to be really careful that you don't accidentally invoke an infinite loop! This is where the computer will loop code until the end of time. Without a break. Forever.
counter = 0
while counter >10:
  print(counter)
  counter +=1  

In this above case counter will not print anything upto 10 but it will start printing from 11 as there is counter >10 but the while loop will never break because the while loop condition is always fulfilled here.

Code as an example with reason of coding :

Write a program that loops. Inside the loop, ask the user what animal sound they want to hear. 

What animal do you want?: Cow
A cow goes moo.

Do you want to exit?: no

What animal do you want?: A Lesser Spotted lemur
Ummm...the Lesser Spotter Lemur goes awooga.

Do you want to exit?: yes

exit = "no"
while exit == "no":
  animal_sound = input("What animal sound do you want to hear?")
  
  if animal_sound == "cow" or animal_sound == "Cow":
    print("🐮 Moo")
  elif animal_sound == "pig" or animal_sound == "Pig":
    print ("🐷 Oink")
  elif animal_sound == "sheep" or animal_sound == "Sheep":
    print ("🐑 Baaa")
  elif animal_sound == "duck" or animal_sound == "Duck":
    print("🦆 Quack")
  elif animal_sound == "dog" or animal_sound == "Dog":
    print("🐶 Woof")
  elif animal_sound == "cat" or animal_sound == "Cat":
    print("🐱 Meow")
  else: 
    print("I don't know that animal sound. Try again.")


  exit = input("Do you want to exit?: ")

you learned how to create a while loop. However, there are a lot of moving parts that can turn the while loop into an accidental infinite loop...and a nightmare.

while True Loop

Introducing the while True loop...


while True:
  print("This program is running")
print("Aww, I was having a good time 😭")

What do you think the above code does?
Remember you can use the big Stop button on the top if your program does not end.

This type of loop only has two conditions: True and False. Make note of the capital "T" and "F".

Make it stop

There is a way to stop the loop with the word break. This exits the loop and stops all code at that point. Even if there is more code written after break that is inside the loop.

After break, the computer jumps out of the loop to the next unindented line of code.



while True:
    print("This program is running")
    goAgain = input("Go again?: ")
    if goAgain == "no":
        break
print("Aww, I was having a good time 😭")

Run the code below and notice how the loop will continue until break. Here in the above code when while is True it will keep on printing the print function everytime and it will ask through input that "Go again" if it is no then the loop will break and if it is other than "no" then the loop will continue.

Lets see another example :-

counter = 0
while True:
  answer = int(input("Enter a number: "))
  print("Adding it up!")
  counter += answer
  print("Current total is", counter)
  addAnother = input("Add another? ")
  if addAnother == "no":
    break
print("Bye!")

Lets get into another example :-
Create a "Name the Lyrics" game. Write your favorite song lyrics with a word or two missing. The user has to figure out the correct song lyric in as few attempts as possible. Find the true lyric master among you!

print("Fill in the blank lyrics!")
print("(Type in the blank lyrics and see if you are as cool as me.)")
print("")
count = 0
while True:
print("Never going to ______ you up.")
option = input("what will be the blank word:")
count=count+1
if option == "give":
break
print("Total Attempt", count)


Thursday, February 29, 2024

 Project -2 : Lets Play Rock(R) , Paper(P) and Scicessors(S) Game



So far you have learned
  • input and output,
  • if/elif/else statements,
  • basic mathematics,
  •  casting as float and int.
For this version, you have two players. Player 1 and Player 2.
You will need to create if statements (and probably nesting) to decide who has won, lost or if the game is a tie.
Make it fun and add emojis or epic comments as your players battle it out.
Keep it simple for you. Don't expect the user to type in the words rock, paper, scissors. Instead, encourage them to use R, P, or S. 

Version -1

print("Lets Play Rock(R) , Paper(P) and Scicessors(S)")
print()
player1= input ("player1 choose between R , P & S: ")
player2= input ("player2 choose between R , P & S: ")
if player1 == player2 :
print ("it is a tie")
elif player1 == "R" and player2 == "P":
print("player2 is winner")
elif player1 == "R" and player2 == "S":
print("player1 is winner")
elif player1 == "P" and player2 == "S":
print("player2 is winner")
elif player1 == "P" and player2 == "R":
print("player1 is winner")
elif player1 == "S" and player2 == "R":
print("player2 is winner")
elif player1 == "S" and player2 == "P":
print("player1 is winner")
else:
print("Entered wrong letter")

Version-2

print("E P I C 🪨 📄 ✂️ B A T T L E ")
print()
print("Select your move (R, P or S)")
print()
player1Move = input("Player 1 > ")
print()
player2Move = input("Player 2 > ")
print()
if player1Move=="R":
if player2Move=="R":
print("You both picked Rock, draw!")
elif player2Move=="S":
print("Player1 smashed Player2's Scissors into dust with their Rock!")
elif player2Move=="P":
print("Player1's Rock is smothered by Player2's Paper!")
else:
print("Invalid Move Player 2!")
elif player1Move=="P":
if player2Move=="R":
print("Player2's Rock is smothered by Player1's Paper!")
elif player2Move=="S":
print("Player1's Paper is cut into tiny pieces by Player2's Scissors!")
elif player2Move=="P":
print("Two bits of paper flap at each other. Dissapointing. Draw.")
else:
print("Invalid Move Player 2!")
elif player1Move=="S":
if player2Move=="R":
print("Player 2's Rock makes metal-dust out of Player1's Scissors")
elif player2Move=="S":
print("Ka-Shing! Scissors bounce off each other like a dodgy sword fight! Draw.")
elif player2Move=="P":
print("Player1's Scissors make confetti out of Player2's paper!")
else:
print("Invalid Move Player 2!")
else:
print("Invalid Move Player 1!")

 First simple Project - Grade Generator using python with basic understanding of coding ( if , else , print statement ,basic maths)


Giving a grade like A+ , A- , B, C, D .... as per the student obtained in an Exam out of total marks. You have to calculate the percentage and print it with the grade that the student has got.




print("Exam Grade Calculator")
subj= input ("Name of the exam:")
if subj == "cs" :
maxscore = int(input("Max possible score:"))
urscore= int(input("what is your score:"))
percentage = int((urscore/maxscore)*100)
print(percentage)
if percentage >= 90:
print("you got",percentage,"% which is a A+")
    elif percentage >= 80:
       print("you got",percentage,"% which is a A-")
    elif percentage >= 70:
       print("you got",percentage,"% which is a B")
     elif percentage >= 60:
       print("you got",percentage,"% which is a C")
    elif percentage >= 50:
       print("you got",percentage,"% which is a D")
    elif percentage >= 40:
       print("you got",percentage,"%which is a E")
    else:
       print("you got",percentage," % which is a F")
else:
       print("we dont deal with the subject")

 

A little bit of math for Python


So far we have introduced the computer to two types of numbers:
float: numbers with a decimal
int:    whole numbers

Copy this code and have a go with trying the different mathematical symbols.

adding = 4 + 3
print(adding)

subtraction = 8 - 9
print(subtraction)

multiplication = 4 * 32
print(multiplication)

division = 50 / 5
print(division)

# a number raised to the power of some number
# in this example we raise 5 to the power of 2
squared = 5**2
print(squared)

# remainder of a division
modulo = 15 % 4
print(modulo)

# whole number division
divisor = 15 // 2
print(divisor)

Lets get into coding again :

How many seconds are in a year?

tSeconds = int(input("1 min in Sec=:"))
tMinutes = int(input("1 hour in Minutes=:"))
tHours = int(input("1 Day in Hours=:" ))
#tDays = int(input("1 year in Days:"))
tYear = int(input("which year it is"))
# lets check for the leap year
if tYear % 4 == 0:
tDays = 366
Totalsecs = tDays*tHours*tMinutes*tSeconds
print("total seconds in year =",Totalsecs)
else:
tDays = 365
Totalsecs = tDays*tHours*tMinutes*tSeconds
print("total seconds in year =",Totalsecs)

Wednesday, February 28, 2024

 

Casting in If statement and using int & float

If statements support more than ==. They support inequality symbols as well. Remember those <, >, and = signs you used in math way back . 

# equal
5 == 5

# not equal
3 ! = 5

# greater than
5 > 3

# greater than or equal to
5 >= 3

# less than
3 < 5

# less than or equal to
3 <= 5

This is because the way input works behind the scenes is it always assumes what you are typing is text (or a string) and gets stored as a variable in " ".

Casting is where we explicitly tell the computer that what we are typing is a number and not a letter.


The code below is saying any score greater than 100,000 is a winner. Anything less, try again.

myScore = input("Your score: ")
if myScore > 100000:
  print("Winner!")
else:
  print("Try again ")



Let's add int

There are two types of numbers the computer will recognize:
  • int whole number (ex: 42)
  • float any number with a decimal (ex: 1.81)
int

To change "your score" to a number, we need to add int in front of the input and place the entire input in ()

Update your code to look like this:

myScore = int(input("Your score: "))
if myScore > 100000:
  print("Winner!")
else:
  print("Try again ")

The way the computer will read this code is by starting with what is in brackets first ("your score"). The computer thinks this is text because of the "". When we add int, we are telling the computer, "This is not text. Please convert this to a whole number." Now the variable, myScore will store the answer as a number.

Let's add float

You would do the exact same thing, except using float for a decimal number. In the code below, I want to find pi to 3 decimal places.

myPi = float(input("What is Pi to 3dp? "))
if myPi == 3.142 :
  print("Exactly!")
else:
  print("Try again ")

We are casting that input as a float which means we are expecting a decimal number. The code will not crash if we put a . and then numbers after it to signify a decimal number.




code for Generation Generator :- 

print("Generation Identifier")
userBorn = int(input("Which year were you born:"))
if userBorn >= 1883 and userBorn <=1900 :
  print("Lost Generation")
elif userBorn >= 1901 and userBorn <=1927 :
  print("Greatest Generation")
elif userBorn >= 1928 and userBorn <= 1945 :
   print("silent Generation")
elif userBorn >= 1946 and userBorn <= 1964 :
   print("Baby Boomers")
elif userBorn >= 1965 and userBorn <= 1980 :
   print("Generation X")
elif userBorn >= 1981 and userBorn <= 1996 : 
   print("Millenials")
elif userBorn >= 1997 and userBorn <= 2012 :
   print("Generation Z")
else:
   print("Generation alpha")




 

Nesting in if statement

Nesting is where we put an if statement within an if statement using the power of indenting. The second if statement within the first if statement must be indented and its print statement needs to be indented one more time.

Here is code using Nesting :- 

tvShow = input("What is your favorite tv show? ")
if tvShow == "peppa pig":
  print("Ugh, why?")
  faveCharacter = input("Who is your favorite character? ")
  if faveCharacter == "daddy pig":
    print("Right answer")
  else:
    print("Nah, Daddy Pig's the greatest")
elif tvShow == "paw patrol":
  print("Aww, sad times")
else:
  print("Yeah, that's cool and all…") 



Today's focus is using all the skills you have learned so far:
  • input and output
  • concatenation
  • if statements
  • nested if statements

print("Wholesome Positivity machine")
userName = input("Who are you?:")
if userName == "appu" or userName == "angshu" or userName == "rana":
  print("Good morning",userName)
  userWant= input("What do you want to achieve:")
  print("That is Good to know that You",userWant)
  userRating=input("On a scale of 1-10 how do you feel today:")
  if userRating == "5" or userRating =="6" or userRating =="7" or userRating =="8" or userRating =="9" or userRating =="10":
    print ("It is pretty good today for you")
    print("Hey",userName,"keep your chin up!Today you are going to Teach people to code! in the most amazing way")
  elif userRating == "1" or userRating =="2" or userRating =="3" or userRating =="4" :
    print("Boost yourself to be more energetic .. I know one day you can win the world.")
else:
  print("we dont know you")

If Statements

 

If Statements

These statements are a bit like asking a question. You are telling the computer: if something is true, then do this specific block of code. Double equals (==) is asking the computer to compare if these two things are exactly the same.

In the code below, I am asking if the variable myName is the same as the string Dravid

myName = input("What's your name?: ")
if myName == "Dravid":   

But that doesn't print anything?

To create a print statement related to the input from the if statement, you must go to the next line and indent once.

An Example as a code  :- 

myName = input("What's your name?: ")
if myName == "Dravid":
  print("Welcome Dude!")   

What is else?

If the condition is not met with the if statement, then we want the computer to do the else part instead. Likewise, if the condition is met in the if statement, then the else bit is ignored by the computer. The else statement must be the first thing unindented after the if statement and in line with it.

myName = input("What's your name?: ")
if myName == "Dravid":
 print("Welcome Dude!")
 print("You're just the baldest dude I've ever seen")
else:
 print("Who on earth are you?!")  

What the elif is this?

The elif command (which stands for 'elseif') allows you to ask 2, 3, 4 or 142 questions using the same input! This command must be in a certain place. You can have as many elif statements as you want, but they must go in between if and else and have the same indentation. The print statements in your elif command need to line up with the indent of the other print statements.

An Example as a code  :- 
print("Secure login into Rude Rows")
userName = input("Tell me your Username:")
password =  input("Put your password here:")
if userName == "Ruderows" and password== "abcd" :
   print("Hey there",userName)
elif userName == "suman"  and password== "efgh":
  print("Hey there",userName)
elif userName == "biman" and password== "ijkl":
  print("Hey there",userName)
else :
  print("Go away")

 

Concatenate more than one input variable including other print function content.

All it really means is combine text (remember, text is called a string) and variables together into single sentences!

Here is the code to concatenate .

myName = input("What's your name? ")
myLunch = input("What are you having for lunch? ")
print(myName, "is going to be chowing down on", myLunch, "very soon!")

  • It turns out print has a super-power. We can give it as many different things to print as we want. All we need to do is put a comma( ,) between every different thing in the ().



 

Taking user input

Let's take a look at the input command and how that works. Input is when the user gives information to the computer.


It's very similar to the print command, except that it'll show the message in the console then wait until the user has typed something into the console and pressed enter. 

Let's get your hands dirty with the below code :- 

myName = input("What is your name ?:  ")
myFood = input("What is your food ?:  ")
myMusic= input("what is your fav music?:")
myLocation = input("where do u live?:")

print("You are")
print(myName)
print("You are probably hungry for")
print(myFood)
print("You must heard of ")
print(myMusic)
print("Living in ")
print(myLocation)

output  /Example 

What is your name ?:  Annat
What is your food ?:  mango
what is your fav music?: Trans
where do u live?: Singapore

You are
Annat
You are probably hungry for
 mango
You must heard of 
Trans
Living in 
Singapore

PS- bold words are input words given by the user.
Here in this above code, when we are taking an input as "what is your name? : " with the input function then automatically it is looking for a name in the console and when you have give the name it will be stored in the "myName" variable. when we call the "myName" variable with another print function then it will print the answer of input function that is given by you.

What is a variable?
input asks for something, takes it, but then has nowhere to put it. We can change that with a variable which is a value that we can use to name and store data. (Remember, David's box for David's phone?)






Naming variables
You can give a variable any name you want, but you can't use spaces. 
You can use:  
  • underscores_between_words
  • camelCaseToMakeItEasierToRead

Printing a Variable

You can print your variable using print and the name you used for your variable in your input command. Remember the three variables we just created: myName , myFood, myMusic
In your code you can now print 'name' by using print(myName) or 'Food' by using print(myFood).











Tuesday, February 27, 2024

 Writing your first Python program (Hello World!).


Let's start with some simple code to get a simple output (the information the program gives to the user).

print("Hello World!")

output
Hello World!

You just learned your first command: the print statement. It says "Print out whatever's in my brackets". The print statement is how you get your program to put messages in the console.

  • The " " (quotes) are used to tell the command that you're putting text in there (any text you want)
  • A bunch of text (or whatever you put in quotes) is called a string.

Multiple Print Statements

Here is what multiple print statements looks like. 

print("Well we")
print("just use more lines")
print("of code")

output
Well we
just use more lines
of code


Use the triple quote """ if you want to write a big chunk of text with gaps or line breaks. 

print("""Anything that starts
with three quotes, and ends
in three quotes can span
many lines and even contain " symbols
within it without freaking anything out!""")

Output
Anything that starts
with three quotes, and ends
in three quotes can span
many lines and even contain " symbols
within it without freaking anything out!




 Overview of Python: History and Features


History: Python is a high-level, interpreted programming language created by Guido van Rossum and first released in 1991. The language was designed with an emphasis on simplicity and readability, aiming to provide a clear and concise syntax that promotes code readability and maintainability. Python's development was heavily influenced by other programming languages like ABC, Modula-3, and C.

Key milestones in Python's history include:

  • Python 1.0 (1994): The first official release of Python.
  • Python 2.0 (2000): Introduced list comprehensions, garbage collection, and Unicode support.
  • Python 3.0 (2008): A major revision of the language that introduced backward-incompatible changes to improve clarity and consistency.

Python has since seen widespread adoption in various fields, including web development, data analysis, scientific computing, artificial intelligence, and automation.

Features:

1. Readability: Python's syntax is designed to be clear and easy to read, emphasizing the use of indentation and whitespace to define code blocks, rather than relying on curly braces or keywords.

2. Simplicity: Python prioritizes simplicity and ease of use, making it accessible to beginners while still powerful enough for advanced users. Its minimalist syntax reduces the amount of code needed to express concepts compared to other languages.

3. Dynamically Typed: Python is dynamically typed, meaning variable types are inferred at runtime rather than explicitly declared. This feature allows for more flexibility and rapid development but may require additional testing to catch type-related errors.

4. Interpreted: Python is an interpreted language, which means that code is executed line by line by an interpreter rather than being compiled into machine code beforehand. This makes development and debugging faster but can result in slower execution speed compared to compiled languages.

5. High-level: Python provides built-in data structures and abstractions that simplify programming tasks, allowing developers to focus on solving problems rather than managing memory or low-level details.

6. Object-oriented: Python supports object-oriented programming (OOP) principles, including encapsulation, inheritance, and polymorphism. Everything in Python is an object, making it easy to organize and manipulate code into reusable components.

7. Extensive Standard Library: Python comes with a comprehensive standard library that includes modules and functions for performing common tasks such as file I/O, networking, regular expressions, and more. This library reduces the need for external dependencies and facilitates rapid development.

8. Cross-platform: Python is platform-independent, meaning that Python code can run on various operating systems without modification. This portability makes it an ideal choice for developing cross-platform applications.

Overall, Python's combination of simplicity, readability, and versatility has made it one of the most popular programming languages worldwide, used by developers in a wide range of industries and domains.

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