mercredi 6 novembre 2019

Is there a way to continue printing a random element from a Python 3 dictionary without repeating?

I am currently learning Python 3, as well as trying to pickup on command line along the way. I figured I could practice both by writing a Python program to aid in memorizing commands for the command line.

The code I wrote almost did what I wanted it to (shown below).

Essentially, when I run the file in my command line, I want it to print a random key from the dictionary, then allow me to type in what I think it means, then show me the correct answer upon hitting enter.

The problem is that it just keeps printing the same key every time unless I close the program and run it again. I've tried functions, nesting functions, for loops, while loops, nesting loops, etc and I just can't seem to get it to print a different key.

I would love some feedback on this!

import random
import time

command_dict = {
    'pwd' : 'print working directory',
    'hostname': 'my computer\'s network name',
    'mkdir' : 'make directory',
    'cd' : 'change directory',
    'ls' : 'list directory',
    'rmdir' : 'remove directory',
    'pushd' : 'push directory',
    'popd' : 'pop directory',
    'cp' : 'copy a file or directory',
    'mv' : 'move file or directory',
    'less' : 'page through a file',
    'cat' : 'print the whole file',
    'xargs' : 'execute arguments',
    'find' : 'find files',
    'grep' : 'find things inside files',
    'man' : 'read a manual page',
    'apropos' : 'find which man page is appropriate',
    'env' : 'look at your environment',
    'echo' : 'print some arguments',
    'export' : 'export/set a new environment variable',
    'exit' : 'exit the shell',
    'sudo' : 'become super user root - !Danger!'
}

random_key = random.sample(list(command_dict), 1)[0]
answer_value = command_dict.get(random_key)

while True:

    print(random_key)
    input("> ")
    print("ANSWER: ", answer_value)
    time.sleep(2)
    print("\n------------")

here is my command line




Aucun commentaire:

Enregistrer un commentaire