Skip to main content

Posts

Showing posts from January, 2023

OS LIBRARY , TIME LIBRARY

  What is the os library? It allows us to "talk" to the console. One of the most powerful things we can do with this library is allow it to clear the console EXAMPLE: import os print("Welcome") print("to") print("Replit") os.system("clear") username = input("Username: ")  Time Library We can import a second library by placing a  ,  after the name of the first library. EXAMPLE: import os, time print("Welcome") print("to") print("Replit") time.sleep(10) os.system("clear") username = input("Username: ")  NOTE:  from replit import audio import os, time def play():   source = audio.play_file('audio.wav')   source.paused = False # unpause the playback   while True:     stop_playback = int(input("Press 2 anytime to stop playback and go back to the menu : ")) # giving the user the option to stop playback     if stop_playback == 2:       source.paused = True # let'

Return Command

  Return Command The  return  command sends some information back to the part of the code that called it. This means the function call is replaced with whatever was returned  EXAMPLE : def area_square(side1, side2):   area = side1 * side2  return area area = area_square(4, 12) print(area)

Parameters , Call the Subroutine , Adding More Arguments

  Parameters In a subroutine, the  ()  are for the argument (FYI argument is another word for parameter). These are the pieces of information we pass to the code. These can be variable names that are made up for the first time within the argument  () . EXAMPLE : def whichCake(ingredient):   if ingredient == "chocolate":     print("Mmm, chocolate cake is amazing")   elif ingredient == "broccoli":     print("You what mate?!")   else:      print("Yeah, that's great I suppose...") How do we call the subroutine? We call it in the same way as before. However, instead of leaving the  ()  blank, we send the code a message.   EXAMPLE : def whichCake("chocolate"):   if ingredient == "chocolate":     print("Mmm, chocolate cake is amazing")   elif ingredient == "broccoli":     print("You what mate?!")   else:      print("Yeah, that's great I suppose...")  Adding More Arguments We c

Subroutine

  Subroutine A  subroutine  tells the computer that a piece of code exists and to go run that code again and again ... EXAMPLE : def rollDice():   import random   dice = random.randint(1, 6)   print("You rolled", dice)  Call the Subroutine   We need to 'call' the code by adding one more line to our code with the name of the subroutine and the empty  () :  EXAMPLE : def rollDice():   import random   dice = random.randint(1, 6)   print("You rolled", dice) rollDice()

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.  EXAMPLE : import random myNumber = random.randint(1,100) print(myNumber) How random works In the code below, I have created a variable, 'myNumber'. I am making it equal to a random number given to me 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.

What can range really do?

  What can range  really  do? 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?)   EXAMPLE :  for i in range(1, 8):   print("Day", i)   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.  EXAMPLE :   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. EXAMPLE : for i in range(10, -1, -1):   print(i)

FOR LOOP , RANGE

  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.  EXAMPLE :  for counter in range(10):   print(counter) RANGE  The  range  function creates a list of numbers in the range you create. If you only give it one number, it will start at  0  and move to a state where the final number is  one less  than the number in the brackets. In this case, the final number would be  9 .  EXAMPLE :  total = 0 for number in range(100) :   total += number   print(total)

CONTINUE COMMAND AND EXIT LINE

  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. 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") NOTE :  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.  EXIT  COMMAND LINE  The previous code continues to loop even after the user has won. Let's fix that with the  exit()  command EXAMPLE: print("Let's play chutes and ladders. Pick ladder or chute.") while True:   print("Do you want to go up the ladder or do

WHAT IS WHILE TRUE LOOP AND TO STOP THE LOOP

  while True Loop EXAMPLE  (THIS WILL NOT STOP) :  while True:   print("This program is running") print("Aww, I was having a good time 😭")  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.  EXAMPLE :   while True:   print("This program is running")   goAgain = input("Go again?: ")   if goAgain == "no":     break print("Aww, I was having a good time 😭")

ALL ABOUT WHILE LOOP

 WHILE LOOP  A  while  loop allows your code to repeat itself based on a condition you set.   EXAMPLE : counter = 0 while counter < 10:   print(counter)   counter +=1 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.  This is just saying "count to 10 by 1 each time." to make the loop end. Don't forget, if your  condition  is a  >  then you might need to  -= . This will subtract from the variable instead of adding to it.   EXAMPLE : counter = 0 while counter < 10:   print(counter)    counter += 1

THE IMPORTANT PROJECT ON MATH CODE

  days_this_year = int(input("How many days are in this year?")) days_in_year = 365 days_in_leapyear = 366 hours_in_day = 24 minutes_in_hour = 60 seconds_in_minute = 60 result = days_in_year * hours_in_day * minutes_in_hour * seconds_in_minute leapyear_result = days_in_leapyear * hours_in_day * minutes_in_hour * seconds_in_minute if days_this_year == 366:   print("Number of seconds in a leap year are", leapyear_result) else:   print("Number of seconds in a year are", result)

A little bit of math

  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)  THIS IN ROUND  # 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)  THIS IN ROUND FIGURE   EXAMPLE : answer = round(answer, 2)

WHAT IS Casting , INT , FLOAT

  WHAT IS Casting  If  statements support more than  == . They support inequality symbols as well. Remember those <, >, and = signs you used in math way back when? Well they are back again, but this time they look a bit different    EXAMPLE : myScore = input("Your score: ") if myScore > 100000:   print("Winner!") else:   print("Try again ") WHAT IS INT  To change "your score" to a number, we need to add  int  in front of the  input  and place the enitre input in  () .  EXAMPLE :  myScore = int(input("Your score: ")) if myScore > 100000:   print("Winner!") else:   print("Try again 😭")  WHAT IS 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.  EXAMPLE :    myPi = float(input("What is Pi to 3dp? ")) if myPi == 3.142 :   print("Exactly!") else:   print("Try again 😭") 

WHAT IS Nesting

 WHAT IS Nesting  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.  EXAMPLE:

WHAT IS ELIF

  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. EXAMPLE :  print("SECURE LOGIN") username = input("Username > ") password = input("Password> ") if username == "mark" and password == "password":  print("Welcome Mark!") elif username == "suzanne":  print("Hey there Suzanne!") else:  print("Go away!") E

IF AND ELSE STATEMENT

  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.  EXAMPLE :  myName = input("What's your name?: ") if myName == "David":  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    EXAMPLE :  myName = input("What's your name?: ") if myName == "David":  print("Welcome Dude!")  print("You're just the baldest dude I've ever seen") else:  print("Who on earth are you?!")

PRINT IN COLOR

  HOW TO PRINT IN COLOR  HOW TO PRINT IN OTHER COLOR  Color Value Default 0 Black 30 Red 31 Green 32 Yellow 33 Blue 34 Purple 35 Cyan 36 White 37

Concatenate

  Concatenate  All it really means is  combine  text (remember, text is called a string) and variables together into single sentences EXAMPLE:  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!")