Writing your first Python script

When it comes to learning to code, Python is one of the easiest coding languages to start with since it resembles standard English. It’s also an interpreted language which means you can write and run your code without compiling it down to binary executable files and so libraries where you have to deal with platform details and compiler scripts.

To write your first beginner Python script you’ll first need to spend some time setting up your Development environment by installing the Python interpreters, downloading an IDE to create and edit Python Files, and then create a project or workspace folder to collect your work.

Afterwords we will write a script to print out the “Hello World” message and then extend this script to take in a name as input, reuse code by making a function and loops, and display the Time using the standard library datetime module.

Install Python3

Important: Python2.7 will no longer be supported after 2019 so any new security holes found will not be updated. Use this version at your own risk.

To get started with Python, simply head over to the python.org website and download either the latest stable 3.7 build or try out the new Python 3.8 version for a few new features and performance updates. Since Python 3.8 is the latest version it may contain security leaks that have not been found yet. If you plan to release enterprise level software or Python based web applications it is better to use 3.7.

After downloading, just install the interpreter from the setup file like you would any other program. The installer will add the “python” executable to your path so in command prompt or a terminal you can run “python” to get an interactive shell or run your scripts using “python myscript.py”

Setup your code editor

To be able to create your script you will need something to type out your code. As a beginner for creating a single python script you may be most comfortable with just using Notepad or GEdit but I’ll list out other available options.

You could also install Notepad++ or Sublime3 text which supports code formatting which color codes variables, operators, comments, and other python Keywords. You can also open entire directories for when you are working on multiple code files which interact with each other.

My preferred code editor for Python is Visual Studio Code. In addition to the above you also get a built in debugging tool for walking through more complex code and tracking variable assignments during runtime, an integrated terminal to be able to run scripts you are working on, auto complete and intellisense for writing code quicker, git integration for tracking changes in your code, plugins, and more.

Another commonly used way of working with Python code is using an integrated development environment such as Jet Brains PyCharm which has a lot of advanced options for navigating, refactoring, and debugging code. There are also other tools such as Jupiter Notebook for data analysis, or using server based linux editors such as Vim or EMacs through SSH to modify code directly on a deployed system.

Create a python sandbox folder

Somewhere on your computer create a workspace folder. This folder will serve as a collection of everything you are working on and a place where you can quickly create new test files and projects. I tend to structure my workspace like below. This allows me to see what projects I have in a single place.

  • ~/python
    • ~/python/project1
      • __init__.py
      • main.py
      • ~/python/project1/submodule1
        • __init__.py
      • ~/python/project1/submodule2
        • __init__.py
    • ~/python/project2
      • __init__.py
      • main.py

Open the folder in your IDE

If you are using Visual Studio Code you can use the shortcut (ctrl+k, ctrl+o) on windows to open an entire folder into your IDE.

Bringing in the entire folder is useful because it allows the IDE be able to read your project folder structure and do auto complete and advanced searching to make you more productive while coding.

You can also open files side by side which makes it faster to work on code in one file that is being used in a second file as an import.

Visual code workspace screen shot

Create a HelloWorld.py file

In your workspace created above create a HelloWorld project folder and a HelloWorld.py file inside that folder with the content below.

print("Hello World")

You can now run this file by hitting F5 and debugging as a python file. This will run the file in the Visual Code terminal and will output “Hello World” in the bottom the IDE window. It will also show the command that was used to run your script with the debugger attached.

Extend your script to use variable, built in functions, and operators

To make this script more realistic instead of just printing “Hello World” to the system out of the computer lets restructure this to assign “Hello ” to a variable and input a name. We will then join these together to display a message to our user.

# This is a comment. It is used to display useful
# information to people who read our code

# Save the string "Hello " to a variable 
# Space is added at the end for when we join our input
hello_text = "Hello "

# Get user input
name = input("Enter your name: ")

# Join our strings using the '+' operator which will
# concatenate two strings together into a new variable
message = hello_text + name

# Display the joined message to our user
print(message)

Running this script results in the screenshot below.

Reusing code by creating functions

In the above code we created our “Hello ” message and formatted the spacing ourselves. While this is OK to do in a small example it would be nice to put our message formatting into a function. This function can be reused in our script to create different kind of messages and format it correctly.

# This is a comment. It is used to display useful
# information to people who read our code

# Get user input
first_name = input("Enter your first name: ")

# This is a function which can be called
# in other parts of our code to format a message
def print_message(prefix, first_name):
    print(prefix + " " + first_name)

# Display the joined message to our user
print_message("Hello", first_name)
print_message("Goodbye", first_name)

And the output for this:

Using a while loop to continually display messages

Now let’s say we want to make our script print out messages for multiple people’s name and keep running until someone inputs the letter ‘Q’. This kind of pattern is good for guess the number type games where we need to keep running the same pieces of code.

# This is a comment. It is used to display useful
# information to people who read our code

def print_message(prefix, first_name):
    print(prefix + " " + first_name)

# Get user input
first_name = input("Enter a name: ")

# Check if the first_name variable is equal to 'Q'
# If so we will skip the next intended lines and go to
# line 21
while first_name != "Q":

    # Display the joined message to our user
    print_message("Hello", first_name)
    print_message("Goodbye", first_name)
    # Get the next name to print message for or check 'quit condition'
    first_name = input("Enter another name or 'Q' to quit: ").title()

print("Quitting greeter")

Import libraries to reuse common features

Let’s add in the ability to also print out the time to our user after we say Hello. Tracking times is very common in programs to be able to save when an account was named, write the time in log files, or to take the differences in time at the start of a function and end of a function to get the latency of how long a piece of code has run.

Because working with times is such a common thing in programming, Python has a module in its standard runtime to make working with times easier. Simply “import” the datetime module at the beginning of your code and you will have access to all the functions that are included in this module. You can also import a specific function using the from 'module' import 'variable' notation.

Without this library we would need to write some kind of code ourselves to retrieve the internal computer time, change this into Months, Days, Years, Hours, Minutes, Seconds and write our own formatter to print this in a way our user will recognize.

Lets import this into our HelloWorld code.

from datetime import datetime

# This is a comment. It is used to display useful
# information to people who read our code

def print_message(prefix, first_name):
    print(prefix + " " + first_name)

# Get user input
first_name = input("Enter a name: ")

# Check if the first_name variable is equal to 'Q'
# If so we will skip the next greeting
while first_name != "Q":

    # Display the joined message to our user
    print_message("Hello", first_name)
    
    # Display the current time using the datetime library
    # and chaining method calls to .now() and .strftime()
    print("The current time is ", datetime.now().strftime("%d/%m/%Y %H:%M:%S"))
    
    print_message("Goodbye", first_name)

    first_name = input("Enter another name or 'Q' to quit: ").title()

print("Quitting greeter")

That’s all there is to writing your first python script, getting user input, using the + operator to join strings, using a method to reuse sections of code, using a loop to get more user input and setting a break condition, and importing a library to print the time which is a common function in Python.

Thank you for visiting!

Please remember if you found this content useful and would like to see more python and software development articles from us, help us conquer the google algorithm in any of the ways below:

If you didn’t find what you expected feel free to use the contact page and let us know ways we can improve or what would help you grow as a developer better! I am honored by every view and it takes a village to really make this great.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s