Intro to Python Program

In this article, we will give a quick overview of what a Python Program looks like and also touch on the “Anatomy” of a Program.

The Anatomy of a Program

  • Main
  • Function
  • Statement
  • Variable
  • Value

A program is like a machine, for example, a TV. You can build it, run it, and fix it if broken. To draw an analogy from a program to a machine, Main is like the core engine; Functions are like modules or plugins; Statements are like blocks, when connected together, can perform tasks. A Statement can have Values or Variables (value placeholders).

Remember Scratch? This is an example of a Statement, with a Value.

print("hello")

And this is an example of a Scratch Program

A Python Program

# This program prints Hello World
print("Hello, world")

You can have a program that prints two lines

# This program prints Hello World
print("Hello, world")
print("Goodbye, world")

This is an example program with a function “say”, and also two statements that call the function “say”.

def say(saying):
    print("I said:" + saying)

say("hello")
say("world")

A Python program can be built with multiple files or multiple “modules”, which we will cover in a later article. Below is a preview of an example Python program that randomly selects a key from a Python “dictionary”, asks a question based on the “key”, and checks user input with the key’s value.

import random

def random_key():
    # find all the keys, 'keys' now in a SET data structure
    keys = words.keys()
    # convert 'keys' to LIST
    keys = list(keys)
    # randomly select a key from 'keys'
    random_key = random.choice(keys)
    return random_key

words = {
    "red" : "rojo",
    "blue" : "azul",
    "water" : "aqua",
    "sky" : "cielo",  
    "love" : "amor",  
}

random_answer = random_key()
random_question = words[random_answer]

user_answer = input("Word for " + random_question + ": ")
user_answer = user_answer.strip()
if (user_answer == random_answer):
    print("correct")
else:
    print ("incorrect")