Python: Username Generator

The previous exercise used random to choose a random number. In this exercise (also available as a PDF) we choose random words from lists to create custom usernames. This exercise introduces the following concepts:

  • String Manipulation
  • Lists
  • For Loops

Type the code below into a new repl.it or use an Python IDE (code editor) such as PyCharm or IDLE.

import random

list_of_nouns = ['form', 'blinkers', 'dune', 'storm', 'thunder', 'lightning', 'cross', 'knife', 'sword', 'jewel', 'diamond', 'ruby', 'sapphire', 'gem']
list_of_adjectives = ['terra', 'red', 'sharp', 'dull', 'high', 'low', 'silent', 'quiet', 'purple', 'pink', 'black', 'white', 'blue', 'green', 'sporadic', 'bright', 'slender']

for i in range(20):
  random_noun = random.choice(list_of_nouns)
  random_adjective = random.choice(list_of_adjectives)
  print(random_adjective.capitalize()+random_noun.capitalize())

Think About the Code

  • Line 1 imports code to help us choose random numbers
  • Line 3: creates a variable named ‘list_of_nouns’. The Data Type is a list – specifically a list if strings
  • Line 4 :creates a variable named ‘list_of_adjectives’. The Data Type is a list – specifically a list if strings
  • Line 6: We use a for loop to run the next set of code 20 times
  • Line 7: We use the ‘choice’ function that comes from the imported ‘random’ code to pick an item from the list of nouns
  • Line 8: We use the ‘choice’ function that comes from the imported ‘random’ code to pick an item from the list of adjectives
  • Line 9: We print out the randomly chosen adjective and noun but ‘capitalize’ the first letter of each word
  • Notice that the code inside the ‘for’ loop is indented to the right to show that the lines below belong to the ‘for’ loop

What Next

  • You could ‘import tkinter’ to create a GUI version of this program (solution here)
  • Challenge – create a program that allows the user to input a year and the program will check if that year is a leap year

One Response to “Python: Username Generator”

Leave a Reply

  • (will not be published)

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>