Wednesday, June 22, 2022

Python - Fun with strings and random numbers

myVar = "hello"
# First character is position 0
# So this will print "h"
print(myVar[0])

print("----")

# This will print 0 through 4
for x in range(5):
    print(x)
print("Now out of for loop")

print("----")

# This will loop through the string myVar
# It will print each letter on a different line
# "hello" = 5 characters
# Positions 0 through 4
for x in range(5):
    print (myVar[x])

print("Now out of for loop")

print("----")

# Lazier way of looping through the word
print("Lazy:")
for x in myVar:
    print(x)
    

print("----")

# Print a random letter of the string
# Need to import the module
import random
# By default the seed will use the system time if we leave it blank
random.seed()

myRandomNumber = random.randrange(0, len(myVar) )
print(myVar[myRandomNumber])

print("----")


# Do it 30 times, each time printing a different random letter
# This is a good way to force errors if I have my upper/lower bounds wrong
for x in range(30):
    myRandomNumber = random.randrange(0, len(myVar) )
    print(myVar[myRandomNumber])