Skip to main content

Posts

Showing posts from April, 2023

2D list with while true loop

       Loops, append() and break   Eg:  list_of_question = []  while True:    name = input("what is your name")    age = input("what is your age " )    platfrom = input("which os do u use  ")    row = [name, age, platfrom]    list_of_question.append(row)    exit = input("Exit? y/n ")    if (exit.strip().lower()[0] == "y"):     break print(list_of_question)  Add or Remove?  ask for a name on the list (make sure it is spelled correctly) extract each row, one at a time, from the list check the row to see if it contains the name if the name is in the row, use the .remove() method to remove the whole row, not just the name.  Eg: listOfShame = []  while True:    menu = input("Add or Remove?")   if(menu.strip().lower()[0]=="a"):          name = input("What is your name? ")     age = input("What is your age? ")     pref = input("What is your computer platform? ")          row = [name, age, pref]

LIST IN 2D

 LIST IN 2D  Tables are two-dimensional data structures where we can store data both vertically and horizontally.  Eg: my2DList = [ ["Johnny", 21, "Mac"],              ["Sian", 19, "PC"],              ["Gethin", 17, "PC"] ] print(my2DList[2][2])   Editing a 2D List  We can edit values in a 2D list in the same way as variables and 1D lists. You just need to change the value to the new row and column index numbers Eg:  my2DList = [ ["Johnny", 21, "Mac"],              ["Sian", 19, "PC"],              ["Gethin", 17, "PC"] ] my2DList[1][2] = "Linux" print(my2DList[1])

Dictionaries With Loops

  Dictionaries With Loops  Loops and lists are a perfect pair. Dictionaries and loops are a bit trickier. This is because each dictionary item is made up of two parts - the name of the key and the actual value of that key  Eg:  myDictionary = {"name" : "David the Mildy Terrifying", "health": 186, "strength": 4, "equipped":"l33t haxx0r p0werz"} for name,value in myDictionary.items():   print(f"{name}:{value}")   if (name == "strength"):     if value > 100:       print("Whoa, SO STRONG")     else:       print("Looks like you skipped leg day, arm day, chest day and, well, gym day entirely bro!")

Dictionaries

  Dictionaries  list items are accessed in order by index number. This isn't always the way we want it to work.  Dictionaries are a slightly different type of list that access data by giving each item a key. This creates what we call key:value pairs  Eg:  myUser = {"name": "David", "age": 128} print(myUser["name"]) # This code outputs 'David'. Changing an item Eg: myUser = {"name": "David", "age": 128} myUser["name"] = "The legendary David" print(myUser) # This code outputs 'name:'the legendary David', 'age':'128.

Strings and Loops

 Strings and Loops  Now that we know that strings are basically lists in disguise, we can start to harness the power of loops with them.  Using a for loop   This for loop creates a variable called letter. It is used to store each character in the string as the loop goes through it, starting at the first character. The print statement uses the letter variable and will output the string one character at a time (like a list).  Eg:  myString = "Day 38" for letter in myString:    print(letter) # This code outputs: #D #a #y #3 #8 # this is a comment in the code, the computer will ignore it if statement inside the loop  This code will examine the lower case version of each character. If it's an 'a', the computer will change the font color to yellow before printing. Outside of the loop, the last line sets the font color back to default for the next character in the loop Eg: myString = "Day 38" for letter in myString:   if letter.lower() == "a":     pri

String Slicing

String Slicing  However, sometimes we might want to take part of a string to use it somewhere else. Sometimes, we might want to look at just the first letter of a string or chop it into chunks Eg: myString = "Hello there my friend." print(myString[0]) # This code outputs the 'H' from 'Hello'  The Secret Third Argument  Eg: myString = "Hello there my friend." print(myString[0:6:2]) # This code outputs 'Hlo' (every second character from 'Hello').  myString = "Hello there my friend." print(myString[::-1]) #This code reverses the string, outputting '.dneirf ym ereht olleH'  Split  myString = "Hello there my friend." print(myString.split()) #This code outputs ['Hello', 'there', 'my', 'friend.']

String Manipulation

   String Manipulation Does this code look familiar from the insult generator project? name = input("What's your name? ") if name == "David" or name == "david":   print("Hello Baldy!") else:    print("What a beautiful head of hair!") Right now, if the user writes "DAVID" or "david", the if statement works correctly. However, "DaVID" does not give the correct output. To the computer, " david", "dAviD", and "david" are completely different. To simplify what the user typed in, we can add these functions to the end of the name of the variable: .lower() = all letters are lower case .upper() = all letters are upper case .title() = capital letter for the first letter of every word .capitalize() = capital letter for the first letter of only the first word    

LEN in Python

LEN  len counts how many items is there in a list     EXAMPLE: import os, time listOfEmail = [] def prettyPrint():   os.system("clear")    print("listofEmail")    print()   for index in range(len(listOfEmail)): # len counts how many items in a list     print(f"{index}: {listOfEmail[index]}")    time.sleep(1) while True:   print("SPAMMER Inc.")   menu = input("1. Add email\n2: Remove email\n3. Show emails\n4. Get SPAMMING\n> ")   if menu == "1":     email = input("Email > ")     listOfEmail.append(email)   elif menu =="2":     email = input ("Email > ")     if email in listOfEmail:       listOfEmail.remove(email)   elif menu == "3":     prettyPrint()    time.sleep(1)   os.system("clear")