Sep. 27, 2019

Python Syntax Basics

Before you start writing your first Python program, you’ve got to learn the basics. We will walk you through Python syntax basics that will help as a building block for your Python career.

Throughout the article, we are going to use Python 3 to cover the topic.

To get started, let's first write a very basic Python program.

Writing your First Python Program

There are two ways in which you can write and execute a basic Python program:

  1. In Interactive mode - where you write a program and execute it
  2. Using Script mode - where you execute and already saved Python program(.py file)

Let's see those in action.

Writing “Hello, World!” on Interpreter

To enter the interactive Python mode enter the following command on your Terminal.

$ python

And, now you should be in the interactive mode.

But, if you are using an IDE you don’t need to type the command above to get into interactive programming mode.

Here is Basic Python syntax for executing a Hello World Program.

When you write this program and press enter, your IDE should display "Hello, Word!"

print("Hello World”)

Anything that you write within “ “ of print(“ ”) gets printed on your IDE.

In our case, the output that you should see on your screen would be Hello, World!

Running Your First Python Program in Scripting Mode

When you wrote your Hello World program earlier, let's assume that you saved it in a Python file. When you save your first program, look for a .py extension file.

Assuming that you saved it as Hello_Python.py, here's how you would execute this code in a scripting mode.

First of all, the file you saved has to be made executable. We ideally do that by the command:

$ chmod +x test.py

Now that your file is executable, let's run the program in scripting mode.

$ python Hello_Python.py

Once you execute this command, you will see "Hello, World!" was printed on your Terminal.

"Hello, World”

And, there you have learned your first Python Syntax.

Python Keywords and Identifiers

There are a total of 31 keywords and 5 major identifiers that you should know in Python.

Keywords and identifiers are something you will easily get used to as you work on your Python skills.

What are Identifiers in Python

A Python identifier usually is a variable, a function, a class, a module or it can be any other object. You give a name to an entity in Python, it is called an identifier. A valid identifier starts with a letter(A-Z, a-z both apply) or an underscore(_) which can be followed by zero, letters, underscores or numbers(0-9).

Types of Identifiers in Python:

  1. Variables
  2. Functions
  3. Modules
  4. Class
  5. Other Objects

Let’s go over and check what Keywords are available in Python

Python Syntax Basics - Keywords

To see all 3 Python Keywords, open your IDE and type the following:

>>> import keyword

>>> keyword.kwlist

You should see something like this as the output

['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']

These keywords may often change as new Python versions are released. A couple things in mind:

  1. These are fixed and cannot be used as identifiers
  2. They are case sensitive

These Keywords are also often referenced as Reserved words.

Python Statement

The next thing you should know before we move ahead with Python Syntax basics is Lines and Indentation.

Indentation is help organize code blocks in Python. And, it is rigidly enforced and makes your code visually scannable.

The space that goes with indentation varies under each situation. Observe the code below:

person = ["Dave", "Ben", "Emily"]

for x in person:

if x == "Ben":

print(x)

else:

print("not Ben")

Notice how the "for" statement has one space(indentation), and how "if" has two. That establishes a hierarchy of what's happening within the code.

Try reading the snippet below where we replaced code with the text:

List of Persons

    Go through the list of Persons:

See if Ben is there:

    If yes, print Ben's name

else:

    print that it's not Ben

When you end a line in Python with a semicolon(;), you end a statement in Python.

Also, you can effectively use to write multiple statements in a single line too. Look at the Python Syntax example below:

person="John Doe";age=12;location="unknown"

Python Syntax Basics - Comments

There are two different ways to write comments in Python:

  1. Single line comments using “#”
  2. Multi line comments using """ “””

When you enter anything within triple quotes you can actually write multi line comments without having to add “#” in front of each line of comment. A good example of this would be the “Hello, World!” program at the start.

When you execute a code, it doesn’t print comments that you add in the code.

Python Basic Syntax - Command Line Arguments

With Hello_python.py and interactive script, we actually used a command line argument.

And, that's the best way to introduce command line arguments to you. They are an important part of Python syntax basics that you should know.

For example, let's say if you wish to get more information about how a specific program should be run.

[-c cmd | -m mod | file | -] [arg] ...

Options and arguments (and corresponding environment variables):

-B     : don't write .py[co] files on import; also PYTHONDONTWRITEBYTECODE=x

-c cmd : program passed in as string (terminates option list)

-d     : debug output from parser; also PYTHONDEBUG=x

-E     : ignore PYTHON* environment variables (such as PYTHONPATH)

-h     : print this help message and exit (also --help)

-i     : inspect interactively after running script; forces a prompt even

if stdin does not appear to be a terminal; also PYTHONINSPECT=x

-m mod : run library module as a script (terminates option list)

-O     : optimize generated bytecode slightly; also PYTHONOPTIMIZE=x

-OO    : remove doc-strings in addition to the -O optimizations

-R     : use a pseudo-random salt to make hash() values of various types be

unpredictable between separate invocations of the interpreter, as

a defense against denial-of-service attacks

-Q arg : division options: -Qold (default), -Qwarn, -Qwarnall, -Qnew

-s     : don't add user site directory to sys.path; also PYTHONNOUSERSITE

-S     : don't imply 'import site' on initialization

-t     : issue warnings about inconsistent tab usage (-tt: issue errors)

-u     : unbuffered binary stdout and stderr; also PYTHONUNBUFFERED=x

see man page for details on internal buffering relating to '-u'

-v     : verbose (trace import statements); also PYTHONVERBOSE=x

can be supplied multiple times to increase verbosity

-V     : print the Python version number and exit (also --version)

-W arg : warning control; arg is action:message:category:module:lineno

also PYTHONWARNINGS=arg

-x     : skip first line of source, allowing use of non-Unix forms of #!cmd

-3     : warn about Python 3.x incompatibilities that 2to3 cannot trivially fix

file   : program read from script file

-      : program read from stdin (default; interactive mode if a tty)

arg ...: arguments passed to program in sys.argv[1:]

How To Create A Virtual Environment

Virtual environments are going to be one of those things that you'll create for each new project.

You can still work on new Python projects without creating virtual environments. But, doing so would mean that you will end up with a situation where:

  1. You'll change/modify dependencies (e.g. upgrading your default Python version from 2.7 to 3.x)
  2. Your other Python projects may not execute properly

To create a virtual environment, go to your Terminal and type the following:

$ virtualenv newevironment

The name of the virtual environment we just created it newenvironment.

To launch this newly created environment, type the following command:

source newenvironment

Python Basic Syntax - Installing A Library and Packages

The best way to install Python libraries and packages is by using PyPI.

To install a package, simply type the following command:

pip install "package"

Here "package" should be replaced by the library you wish to install.

In case if you wish to install a specific version of a package, change the previous command:

pip install "package==2.801"

However, if you are unsure of the package version availability, but want to install a stable or a more reliable package - here's your command:

pip install "package>=2.8"

There are other ways to install Python packages too, you can go to source distributions and download these packages directly.

Taking User Input

There are two basic Python syntax types that can request a user input:

  1. raw_input
  2. input

Both will prompt a user to enter an input.

raw_input():

This method is no longer valid Python 3 and the new input is input().

input()

To request a user input see the example below

user_input_request = input("Enter your name: ")

Once you enter this, your IDE will ask you to enter you your name.

Recommended Python Training – DataCamp

For Python training, our top recommendation is DataCamp.

Datacamp provides online interactive courses that combine interactive coding challenges with videos from top instructors in the field.

Datacamp has beginner to advanced Python training that programmers of all levels benefit from.

 



Read more about:
Disclosure of Material Connection: Some of the links in the post above are “affiliate links.” This means if you click on the link and purchase the item, I will receive an affiliate commission. Regardless, PythonForBeginners.com only recommend products or services that we try personally and believe will add value to our readers.