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

No comments:

Post a Comment

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