Wednesday, March 27, 2024

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.

I've Lost My Keys!
Let's set up a looped dictionary.
Using a for loop, like we would with a list, will output the values, but not the keys. Not ideal.

myDictionary = {"name" : "Ian", "health": 219, "strength": 199, "equipped": "Axe"}

for i in myDictionary:
  print(myDictionary[i])

This loop uses the values() method, which can be run on a data type. We still only get the value, and not the key.

myDictionary = {"name" : "Ian", "health": 219, "strength": 199, "equipped": "Axe"}

for value in myDictionary.values():
  print(value)

I've Got The Key...I've Got The Secret

There is a better way!
Here's a loop that will output both key and value.
The .items() function returns the key name and value. Note that I've supplied the loop with two arguments: 'name' and 'value').
This example will just output the names and values using an fString.

myDictionary = {"name" : "Ian", "health": 219, "strength": 199, "equipped": "Axe"}

for name,value in myDictionary.items():
  print(f"{name}:{value}")

A Bit Iffy
Let's go one step further and use some if statements inside the loop.
This example makes a comment about the strength key.

myDictionary = {"name" : "Ian", "health": 219, "strength": 199, "equipped": "Axe"}

for name,value in myDictionary.items():
  print(f"{name}:{value}")

  if (name == "strength"):
    print("Whoa, SO STRONG!")

This example uses nested if statements to react to the key name and the value stored within it.

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: # This nested if wasn't indented properly
  print("Whoa, SO STRONG")
else:
  print("Looks like you skipped leg day, arm day, chest day and, well, gym day entirely bro!")


Coding Challenge

Create a dictionary that stores the following information about a website: name, URL, description and a star rating (out of 5).
Use a loop to output the names of the keys, ask the user to type in the details and store the input in the dictionary.
Finally, output the whole dictionary (keys and values).

website = {"name": None, "url": None, "desc": None, "rating": None}

for name in website.keys():
  website[name] = input(f"{name}: ")

print()
for name, value in website.items():
  print(f"{name}: {value}")


Coding Challenge

Create a dictionary to store the details of your, ahem, MokéBeast.
Ask the user to input the following details: name, type (earth, fire, air, water or spirit), special move, starting HP and starting MP. For now we're just taking in one set of values for one beast.
Output the beast's details.
Check the beast's type and change the color of the text accordingly. Fire is red, water is blue, air is white. You decide on the others.

mokedex = {"Beast Name": None, "Type": None, "Special Move": None, "HP": None, "MP": None}

print("MokéBeast")
print()

for name, value in mokedex.items():
  mokedex[name] = input(f"{name}:\t").strip().title()

if mokedex["Type"]=="Earth":
  print("\033[32m", end="")
elif mokedex["Type"]=="Air":
  print("\033[37m", end="")
elif mokedex["Type"]=="Fire":
  print("\033[31m", end="")
elif mokedex["Type"]=="Water":
  print("\033[34m", end="")
else:
  print("\033[33m", end="")

for name, value in mokedex.items():
  print(f"{name:<15}: {value}")

Tuesday, March 26, 2024

Dictionaries

 

Dictionaries
As you might have guessed, we love lists. However, 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.

Now we can access each item through its key, instead of having to remember what index it is at in the list.

Creating a dictionary - brace!
Curly, curly braces...
To create a dictionary we start just like a list, except with curly braces {}. This dictionary will store data about a user.
The data is inserted in key value pairs like this. Each pair is separated by a comma:


The first key:value pair below has "name" as the key and "David" as the value. Try it out:

myUser = {"name": "David", "age": 128}

Printing the keys
To output (print) from a dictionary, we can use the key instead of the index. Note that we still use square brackets for accessing items (ex: ["name"]).

Let's print "name".

myUser = {"name": "David", "age": 128}
print(myUser["name"])

# This code outputs 'David'.

Changing an item
You can use the = syntax to change key values.

myUser = {"name": "David", "age": 128}

myUser["name"] = "The legendary David"
print(myUser)

# This code outputs 'name:'the legendary David', 'age':'128.

Note that we have to put the keys in single quotation marks '' inside the fString when using this technique.
This is because we've already used double quotes to start and end the fString. So, using "" for the dictionary value would get Python all confuzzled.


myUser = {"name": "David", "age": 128}

print(f"Your name is {myUser['name']} and your age is {myUser['age']}")

# This code outputs 'Your name is David and your age is 128'.

Syntax error?

Why are you getting a syntax error on the print statement line?
The print statement uses square brackets. Curly braces {} are only used to call the value.

Wrong 
myUser = {"name": "David", "age": 128}

print(myUser{"name"})

Correct 
myUser = {"name": "David", "age": 128}

print(myUser["name"])

Undefined?

The key, name, in the dictionary should be inside quotes.

Wrong
myUser = {name: "David", "age": 128}

print(myUser["name"])


Correct 
myUser = {"name": "David", "age": 128}

print(myUser["name"])

Spare Key?
A dictionary can't have two keys with the same name. It always overrides the previous one. Therefore, the 129 overrides the age, 128.

Wrong
myUser = {name:"David", "age": 128, "age" = 129}

print(myUser)

Correct 
myUser = {"name":"David", "age": 128}

myUser["age"] = 129

print(myUser)


Coding Challenge 
Ask the user to input their name, date of birth, telephone number, email and physical address.
Store it all in a dictionary.
Print it out in a nice way once its stored.

x = input("Input your name >")
y = input("Input your date of birth >")
z = input("Input your telephone number >")
a = input("Input your email >")
b = input("Input your address >")


myUser = {"name":x, "DOB": y , "phone": z, "email": a, "address": b}

print(f"Hi {myUser['name']}. Our dictionary says that you were born on {myUser['DOB']}, we can call you on {myUser['phone']}, email {myUser['email']}, or write to {myUser['address']}.")

print(myUser)

Thursday, March 21, 2024

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.

Let's look a bit further into string slicing.

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

myString = "Day 21"
for letter in myString:
print(letter)

output 
D
a
y
 
2
1

This means that we can do certain things to certain characters inside the loop.

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 colour to yellow before printing.

Outside of the loop, the last line sets the font colour back to default for the next character in the loop.

myString = "Day 38"
for letter in myString:
if letter.lower() == "a":
print('\033[33m', end='') #yellow
print(letter)
print('\033[0m', end='')

Using a list to specify search items:-
If the letters are in my list called vowels, they will print out in yellow.
I changed the print statement on the last line back to the default color with the ending system.

vowels = ["a","e","i","o","u"]
myString = "Will my vowels now be yellow?"
for letter in myString:  
  if letter.lower() in vowels:
    print('\033[33m', end='') #yellow    
  print(letter, end="")
  print('\033[0m', end='') #back to default

Coding challenge :
Ask the user to input any sentence (string).
Now we'll rainbow-ize (nope, me neither) it.
As soon as the string contains an 'r', every letter from that point on should be red.
When the computer encounters a 'b', 'g', 'p' or 'y', from there the output should be blue for 'b', green for 'g'...you get the idea.
Loop through the string and output it (so the color continues through the loop).
The output should change color every time it encounters a new r,g,b,p or y.

Extra points for resetting the output color back to default every time there's a space.

It would be like this........

#import os, time
def colorChange(color):
  if color=="r":
    return ("\033[31m")
  elif color=="w":
    return ("\033[0m")
  elif color=="b":
    return ("\033[34m")
  elif color=="":
    return ("\033[33m")
  elif color == "g":
    return ("\033[32m")
  elif color == "p":
    return ("\033[35m")

while True:
  #os.system("clear")
  listofWords= input("Tell me what do want: ").split()
  print(listofWords)
  i=0
  for i in listofWords:
    if i[0]=="r":
      print(colorChange('r'),i,end="" )
    elif i[0] == "w":
      print(colorChange('w'),i,end="")
    elif i[0] == "b":
      print(colorChange('b'),i,end="")
    elif i[0] == "g":
      print(colorChange('g'),i,end="")
  print()
  print(colorChange('w'))


More better way :- 

import os

def colorChange(color):
    colors = {
        'r': '\033[91m',  # Red
        'w': '\033[0m',   # White (reset)
        'b': '\033[94m',  # Blue
        'g': '\033[92m'   # Green
    }
    return colors.get(color, '\033[0m')  # Default to white if color not found

while True:
    os.system("clear")  # Clear the console (uncomment this line if you want to clear the console before each input)
    listofWords = input("Tell me what you want: ").split()
    print(listofWords)
    
    for word in listofWords:
        if word[0] == "r":
            print(colorChange('r') + word, end=" ")
        elif word[0] == "w":
            print(colorChange('w') + word, end=" ")
        elif word[0] == "b":
            print(colorChange('b') + word, end=" ")
        elif word[0] == "g":
            print(colorChange('g') + word, end=" ")
        else:
            print(word, end=" ")  # Print the word without color change if it doesn't start with a recognized letter

    print()
    print(colorChange('w'))  # Reset color to white after printing the words

Picking from a list randomly

Random.choice() picks a random item from a list.

listOfWords = ["british", "suave", "integrity", "accent", "evil", "genius", "Downton"]
wordChosen = random.choice(listOfWords)

Coding Challenges
Prompt the user to type in a letter.
Check if the letter is in the word.
If it does, output the word with all blanks apart from the letter(s) they've already guessed.
Keep a running list of the letters they've used.
Count how many times they've picked a letter that isn't in the word - more than 6 and they lose.
Output a 'win' message if they reveal all the letters.



import random, os, time
listOfWords = ["apple", "orange", "grapes", "pear"]
letterPicked = []
lives = 6
word = random.choice(listOfWords)
while True:
time.sleep(5)
os.system("clear")
letter = input("Choose a letter: ").lower()
if letter in letterPicked:
print("You've tried that before")
continue
letterPicked.append(letter)
if letter in word:
print("You found a letter")
else:
print("Nope, not in there")
lives -= 1
allLetters = True
print()
for i in word:
if i in letterPicked:
print(i, end="")
else:
print("_", end="")
allLetters = False
print()
if allLetters:
print(f"You won with {lives} left!")
break


if lives<=0:
print(f"You ran out of lives! The answer was {word}")
break
else:
print(f"Only {lives} left")

String Manipulation

 

String Manipulation
Let's do some string manipulation to make if statements even easier.

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

lower

The computer is converting everything to lowercase before it compares my if statements.
You need to type your if statement in lower case when you use .lower. The if statement needs to be written in upper case when you use .upper, etc.

name = input("What's your name? ")
if name.lower() == "david": 
  print("Hello Baldy!")
else: 
  print("What a beautiful head of hair!")

What if we put a space first?
Adding .strip() removes any spaces on either side of the word.

name = input("What's your name? ")
if name.lower().strip() == "david": 
  print("Hello Baldy!")
else: 
  print("What a beautiful head of hair!")

No Duplicates
This is a simple program that creates a list with a simple subroutine. In the while True loop, the user is adding something to the list. (This is nowhere near as complicated as what you have done).

myList = []

def printList():
  print()
  for i in myList:
    print(i)
  print()

while True:
  addItem = input("Item > ").strip().capitalize()
  if addItem not in myList:
    myList.append(addItem)
  printList()

Note: Whatever you do after the . will happen to the string. If you use .lower, then the string will print in lower case.

Coding Challenge :- 
Create a list of people's names. Ask for first and last name (surname) separately.
Strip any extra spaces.
Store names in a capitalized version.
Create a new string using an fString that combines the tidied up version of the first name and tidied up version of the last name.
Add those new versions to a list.
Do not allow duplicates.
Each time you add a new name, you should print out the full list.

import os,time
yourName=[]

def prettyPrint():
  os.system('clear')
  print("Chart of All People")
  print()
  for i in yourName:
    print(i)
    time.sleep(1)

while True:
  os.system('clear')
  firstName=input("First Name please:").strip().capitalize()
  lastName=input("Last Name please:").strip().capitalize()
  name =f"{firstName} {lastName}"
  if name in yourName:
    print("already in the list")
  elif name not in yourName:
    yourName.append(name)
  prettyPrint()

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.

To do this, we use string slicing.

A string isn't just one big lump of text. In fact it's a list of individual characters. 

By giving our program an index, we can specify which part of the string to chop out. 

Slicing

To slice a single character from a string, you use the index of that character in square brackets [] just like you'd use with a list!

myString = "Hello there my friend."
print(myString[0])

# This code outputs the 'H' from 'Hello'


To slice more than one character, you use two indices (yes that is the plural form of 'index'): the start character and one after your desired end character.

myString = "Hello there my friend."
print(myString[6:11])
# This code outputs 'there'.

Leaving the first index blank defaults to 'start from index 0'.
myString = "Hello there my friend."
print(myString[:11])
# This code outputs 'Hello there'.

Leaving the last index blank defaults to 'go to the end'.
myString = "Hello there my friend."
print(myString[12:])
# This code outputs 'my friend.'.

The Secret Third Argument

Adding a third argument to the square brackets [] specifies the gap left between characters.



Try to print every other character in the word 'hello':
myString = "Hello there my friend."
print(myString[0:6:2])

# This code outputs 'Hlo' (every second character from 'Hello').

Can you print every third character in the whole string?

myString = "Hello there my friend."
print(myString[::3])

# This code outputs 'Hltrmfe!' (every third character from the whole string).

Using a negative number in the third argument can be super useful. It starts the slice from the end of the string instead of the beginning.

myString = "Hello there my friend."
print(myString[::-1])

#This code reverses the string, outputting '.dneirf ym ereht olleH'

Split

split lets us split a string into a list of individual words by separating it at the space characters.

myString = "Hello there my friend."
print(myString.split())

#This code outputs ['Hello', 'there', 'my', 'friend.']

It stops printing too early

Why is it printing 'Hell' instead of 'Hello'?

myString = "Hello there my friend."
print(myString[0:4])

The second argument should always be one more than the index of the final character.

myString = "Hello there my friend."
print(myString[0:5])

It won't stop printing the same character

myString = "Hello there my friend."
print(myString[0:4:0])---- wrong code

The 0 in the third argument means 'move on 0 characters in the string each time'. You've told it to print the same character again and again and again....

The third argument should be at least 1.

CODING CHALLENGE
Ask the user to input their first & last names.
Slice the first 3 letters of the first name.
Slice the first 3 letters of the last name (surname).
Join them together. Ideally change the case so that it looks good - think fStrings or .upper()/.lower(). This is the user's Star Wars first name.
Now ask the user for their mother's maiden name and the city where they were born. (Maiden name is the last name they had before they got married. If you are not sure, make up a last name.)
Combine the first two letters of the maiden name with the last 3 letters of the city to make the user's Star Wars last name. Remember, fStrings and .upper()/.lower().
Finally, print them both as part of a sentence.

 Extra points for getting all the inputs with just one input command and the split function.

import os,time
starWars=[]


while True:
  os.system('clear')
  print("🌟Star Wars Name Generator🌟")
  print()
  print()
  input_all= input("Input your first name., Input your last name,Input your Mother's name,Input your city name with a space in each word:").slipt().upper()
  input1= input("Input your first name:").strip().upper()
  input2= input("Input your last name:").strip().upper()
  #output1= f"star wars first name is {input1[0:3]} {input2[0:3]}"   
  #print(output1)
  input3= input("Input your Mother's name:").strip().upper()
  input4= input("Input your city name:").strip().upper()
  #output2= f"star wars second name is {input3[0:2]}{input4[0:3:-1]}"
  #data = f"{input1[0:3]}{input2[0:3]}  {input3[0:2]}{input4[-3:]}"
  #print(f"{input1[0:3]}{input2[0:3]}  {input3[0:2]}{input4[-3:]}")
  
  #starWars.append(f"{input_all[0][0:3]}{input_all[1][0:3]}  {input_all[2][0:2]}{input_all[3][-3:]}")
  starWars.append(f"{input1[0:3]}{input2[0:3]}  {input3[0:2]}{input4[-3:]}")
  print(input_all)
  print(starWars)
  time.sleep(2)


More better version :-  


print("STAR WARS NAME GENERATOR")

all = input("Enter your first name, last name, Mum's maiden name and the city you were born in").split()

first = all[0].strip()
last = all[1].strip()
maiden = all[2].strip()
city = all[3].strip()

name = f"{first[:3].title()}{last[:3].lower()} {maiden[:2].title()}{city[-3:].lower()}"

print(f"Your Star Wars name is {name}")

Wednesday, March 20, 2024

Pretty print Functions

 

Pretty print Functions
Let's build a pretty print subroutine! 
When we have a list of data, being able to print out that data in pretty ways is something we need to be able to do. So "pretty printing" is actually a thing.

import os, time
listOfEmail = []

def prettyPrint():
  os.system("clear") # start by clearing the screen
  print("listofEmail") # print the title of my program
  print() # print a blank line
  for email in listOfEmail: # use for loop to access list
    print(email)
  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)
    prettyPrint()  
  time.sleep(1)
  os.system("clear")

Creating a Numbered List

We can also ensure our list prints as a numbered list. Let's make this happen by making these few changes below to our subroutine. This code snippet only shows the subroutine so we can focus on the changes there:

import os, time
listOfEmail = []


def prettyPrint():
os.system("clear")
print("listofEmail")
print()
counter = 1
for email in listOfEmail:
print(f"{counter}: {email}")
counter += 1
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": # we added this elif
prettyPrint() # called our subroutine here
time.sleep(1)
os.system("clear")


len counts how many items are in a list. In this case, it is starting at 0 and then keeps going until it reaches the end of our data inside our list. We can now eliminate the counter variable because we are counting with index.

We do need to access email in a different way now. We are going to use the actual list name itself and then [index] to access the index.


Coding Challenge :
 Print out the first 10 email addresses with a custom email sent to each of those people.
Print one email at a time, pause, and then clear the screen before the next email is printed.

import os, time
listOfEmail = []

def prettyPrint():
  os.system("clear")
  print("listOfEmail")
  print()
  counter = 1
  for email in listOfEmail:
    print(f"{counter}: {email}")
    counter+=1
  time.sleep(1)

def spam(max):
  for i in range(0,max):
    print(f"""Email {i+1}

Dear {listOfEmail[i]}
It has come to our attention that you're missing out on the amazing Replit 100 days of code. We insist you do it right away. If you don't we will pass on your email address to every spammer we've ever encountered and also sign you up to the My Little Pony newsletter, because that's neat. We might just do that anyway.

Love and hugs,

Ian Spammington III""")
    time.sleep(1)
    os.system("clear")
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()
  elif menu =="4":
    spam(10)
  time.sleep(1)
  os.system("clear")

Coding Challenge : 
Build a really cool to do list manager. 
We are going to upgrade the last to do list manager we created: Create a menu where the user can view, add, or remove an item.
The user should be able to edit the text of an item on the list too.
Don't allow the user to add duplicates.
Double check with the user they want to remove an item from the list before it is actually removed. (Is this the item they really want to remove?)
Give the user the option to completely erase the to do list. 

import os, time
toDoList = []

def printList():
  print()
  for items in toDoList:
    print(items)
  print()

while True:
  menu = input("ToDo List Manager\nDo you want to view, add, edit, remove or delete the todo list?\n")
  if menu=="view":
    printList()
  elif menu=="add":
    item = input("What do you want to add?\n").title()
    toDoList.append(item)
  elif menu=="remove":
    item = input("What do you want to remove?\n").title()
    check = input("Are you sure you want to remove this?\n")
    if check[0]=="y":
      if item in toDoList:
        toDoList.remove(item)
  elif menu=="edit":
    item = input("What do you want to edit?\n").title()
    new = input("What do you want to change it to?\n").title()
    for i in range(0,len(toDoList)):
      if toDoList[i]==item:
        toDoList[i]=new
  elif menu=="delete":
    toDoList = []
  time.sleep(1)
  os.system('clear')

Tuesday, March 19, 2024

Dynamic Lists

 

Dynamic Lists

Dynamic lists are ways of using a blank list and adding or removing items to it as we go.

Blank lists

Behind the scenes, the computer is going to recognize this code as a blank list.

myAgenda = []

Append a list.
append will let us add whatever is in () to the list.


Let's use a while True loop to add items to the list. We will store this in a variable called item. Add this code to the end of the code above:

while True:
  item = input("What's next on the Agenda?: ")
  myAgenda.append(item)
  printList()

Printing our new list
Why can't we see what we just added to the list? We need to print the list each time to see what has changed. Let's use a subroutine (why not!):

myAgenda = []

def printList():
  print() #this is just to add an extra space between items
  for item in myAgenda:
    print(item)
  print() #this is just to add an extra space between items

while True:
  item = input("What's next on the Agenda?: ")
  myAgenda.append(item)
  printList()

Removing Items from a List
Notice how using .remove will remove what is inside the ( ).

myAgenda = []

def printList():
  print() 
  for item in myAgenda:
    print(item)
  print() 

while True:
  menu = input("add or remove?: ")
  if menu == "add":
    item = input("What's next on the Agenda?: ")
    myAgenda.append(item)
  elif menu == "remove":
    item = input("What do you want to remove?: ")
    myAgenda.remove(item)
   else:
     print(f"{item} was not in the list")
  printList()

the append function. We have two objects backwards. The list name comes first and then what's being added to the list goes inside ().


Coding Challenge : 
Create your own to do list manager. (This can be super useful!)Ask the user whether they want to view, add, or edit their to do list.
If they want to view it, print it out in a nice way (Hint: subroutine).
If they choose to add an item to the to do list, allow them to type in the item and then add it to the bottom of the list.
If they want to edit the to do list, ask them which item they completed, and remove it from the list.
Don't worry about duplicates!
The first item you put in the list should be the first item you remove.

import os, time
myTodoList=[]
def viewList():
    print() 
    for item in myTodoList:
      print(item)
    print() 

while True:
    os.system("clear")
    menu = input("TodoList Manager\n\nview , add or edit the todo list?: ")
    if menu == "view":
      viewList()
      time.sleep(2)

    elif menu == "add":
      item = input("What do you want to add in the list?\n ")
      myTodoList.append(item)
      time.sleep(2)
    elif menu == "edit":
      item = input("which item you want to remove from the list?\n ")
      if item in myTodoList:
        myTodoList.remove(item)
        time.sleep(2)
      else:
        print(f"{item} was not in the list")
    #viewList()
    time.sleep(2)

Lists

 

Lists
In Computer Science, we learn about a data structure called arrays. Arrays are a place to store more than one thing with the same variable name.

However, Python uses lists instead. Lists are literally lists of items. Any piece of data from any data type can go into a list. We can extract, remove, or change lists.

You may be asking: "What is the point of a list?"

Sometimes, you don't always know how much data you need to store. We can use a loop to move through data in a list without having to first manually tell the computer how many things are in that list.

Starting at 0
As far as Python is concerned, this is a list. Notice we start counting the first item at 0 (instead of 1).


Example: In this list, "lots" is index 0, "of" is index 1, etc.

We can directly add to the list with the variable name, [ ] with the index number of the row.


Printing Lists
We can print out data in the same way.

Let's make a list of our class schedule.

timetable = ["Computer Science", "Math", "English", "Art", "Sport"]
print(timetable)

That looks awful with all the [ ],"" printing too! If I want to print out index 1 in my timetable, I need to tell the computer!



timetable = ["Computer Science", "Math", "English", "Art", "Sport"]
print(timetable[1])

Changing Lists
We can also change lists and the index.
We built our list with timetable =, but we want to change index 4, "sport". We can do this by calling it with [ ].

timetable = ["Computer Science", "Math", "English", "Art", "Sport"]
print(timetable[0])
print(timetable[1])
print(timetable[2])
print(timetable[3])
print(timetable[4])

Add this to to the code above:
timetable[4]= "Watch TV"
Why is it not printing correctly? I have created the timetable, printed it out, and changed index 4 of the timetable.
However, I need to print the changed version. Let's print our new index:

timetable = ["Computer Science", "Math", "English", "Art", "Sport"]
timetable[4]= "Watch TV"
print(timetable[0])
print(timetable[1])
print(timetable[2])
print(timetable[3])
print(timetable[4])

Lists and Loops
Why would I want to write all of those lines of code?
Introducing lists' best friend...loops

We can replace a lot of those lines of code we just wrote with just two lines of code. Change your code to look like this:

timetable = ["Computer Science", "Math", "English", "Art", "Watch TV"]
for lesson in timetable:
  print(lesson)

Remember, for loops work by creating the variable right after the word for and setting it equal to each value in a list (so far we have only used numbers with the range function).


Coding Challenge ;
Create a list that stores greetings in different languages. .
Import random library. Generate a random number between 0 and maximum number of items in your list.
At random, when the user clicks run, print one of the greetings.

while True:
  ask = input("want to play(y/n): ")
  if ask == "y":
    import random
    u= ["gh","hu","iuy","gyu","hui"]
    randi = random.randint(0,3)
    print(u[randi])
  else :
    break

Monday, March 18, 2024

f-strings

 

f-strings
f-strings (format strings) are the best way to combine variables and text together. Everything up until now has been...well...awkward.

Let's look at how we have combined variables and text in the past...concatenating.
name = "Katie"
age = "28"
pronouns = "she/her"

print("This is", name, "using", pronouns, "pronouns and is age", age)

Let's now use an f-string for this same code. What changes did I make to this code?

 Change 1: Using {} as a placeholder for the variable.
 Change 2: Adding .format(variable names, commas)

name = "Katie"
age = "28"
pronouns = "she/her"

print("This is {}, using {} pronouns, and is {} years old.".format(name, pronouns, age))

Local Variables

We can set local variables within the f-string itself. Now it doesn't matter the order of the variables.
 Looking at this code again, I can set my variables inside the text itself. 

Change 1: Replace {}with variable names. 
Change 2: Replace each variable inside {} with what has been defined in format.( = )

name = "Katie"
age = "28"
pronouns = "she/her"
print("This is {name}, using {pronouns} pronouns, and is {age} years old. Hello, {name}. How are you? Have you been having a great {age} years so far".format(name=name, pronouns=pronouns, age=age))

  • f-strings work with different variable types too: int, float, and string.
name = "Katie"
age = "28"
pronouns = "she/her"

response = "This is {name}, using {pronouns} pronouns, and is {age} years old. Hello, {name}. How are you? Have you been having a great {age} years so far".format(name=name, pronouns=pronouns, age=age)

print(response)

The Power of f...
Instead of all that faffing about...try this instead.

Use the letter f before any string with {} for variable names (and forget that .format business).



Look at this same code and see the difference using this technique

name = "Katie"
age = "28"
pronouns = "she/her"
response = f"This is {name}, using {pronouns} pronouns, and is {age} years old. Hello, {name}. How are you? Have you been having a great {age} years so far"
print(response)

Alignment of arguments in print function

left = <  ,   right = >  ,   center = ^

for i in range(1, 31):
print(f"Day {i} of 30")

Let's fix it by adding a left alignment of 2 characters long.

for i in range(1, 31):
print(f"Day {i: <2} of 30")

Coding challenge :
Create a program that uses a loop that asks the user what they have thought of each of the 30 days of challenges so far.
For each day, prompt the user to answer a question and restate it in a full sentence that is center aligned underneath the heading.


print("30 Days Down - What did you think?")
print()
for i in range(1, 31):
thought = input(f"Day {i}:\n")
print()
myText = f"You thought Day {i} was"
print(f"{myText:^35}")
print(f"{thought:^35}")
print()

Thursday, March 14, 2024

Argunents using in Print function

 Some Argunents using in Print function 

End inside print function : You can already create print statements like a boss, but there are a few things you can do to make them easier.Let's add a few secret second arguments to the print statement and see what happens.

By default, at the end of every print statement, the computer clicks 'enter'.

How a range of numbers shows each number on a new line...
for i in range(0, 100):
  print(i)

Here output as 0,1,2,3,....99 will be printed in a vertical manner .

Add a space
Let's tweak that code and see if we can get it to print with a space between each number instead of a new line. What do you notice?
for i in range(0, 100):
  print(i, end=" ")

Here output as 0,1,2,3,....99 will be printed in a horizontal manner with a space in between numbers.

Add a space and comma 
What if we want to add a comma and a space? Let's try it by adding , to our argument.
for i in range(0, 100):
  print(i, end=", ")

Here output as 0,1,2,3,....99

Add a new line, tab, or vertical tab
What happens if you add these different options in your second argument? Play around with these options below and see what they do:

#new line
for i in range(0, 100):
  print(i, end="\n")

#tab indent
for i in range(0, 100):
  print(i, end="\t")

#vertical tab
for i in range(0, 100):
  print(i, end="\v")


We can turn the colors on and off different bits of the code by using end. Remove the previous code from your main.py file and try this out.
print("If you put")
print("\033[33m", end="") #yellow
print("nothing as the")
print("\033[35m", end="") #purple
print("end character")
print("\033[32m", end="") #green
print("then you don't")
print("\033[0m", end="") #default
print("get odd gaps")

Let's concatenate that same print statement:

print("If you put", "\033[33m", "nothing as the", "\033[35m", "end character", "\033[32m", "then you don't", "\033[0m", "get odd gaps", end="")

Now you may notice that we are getting weird double spaces in between the different sections. Let's fix that!
sep Arguments 



Take this same code and change end to sep (short for separator) and add a space at the end of each string. What happens

print("If you put ", "\033[33m", "nothing as the ", "\033[35m", "end character ", "\033[32m", "then you don't ", "\033[0m", "get odd gaps ", sep="")

That GIANT white cursor
we could turn that off! It is just a sneaky print command.
import os, time
print('\033[?25l', end="")
for i in range(1, 101):
  print(i)
  time.sleep(0.2)
  os.system("clear")

Coding Challenge :
Write a subroutine that writes text in color. All it will do is print out the text in that color and turn the color back to normal when it's finished.
Control end and sep so there are not random symbols or spaces.

def newPrint(color,word):
  if color == "Red":
    print("\033[0;31m",word,sep="",end="")
  elif color == "pink":
    print("\033[0;34m",word,sep="",end="")
  elif color == "cyan":
    print("\033[0;36m",word,sep="",end="")
#return (color, word)

print("super Subroutine")
print("with my ",end="")
newPrint("Red","new Programme ")
newPrint("pink","I can just call red")

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