Getting Started With Python

In this post we look at the basics of Python programming.

The content of this article is a continuation of a series of posts on the Python language. Review the previous post titled Install Python if you need Python and VS Code installed.

Hello World

The usual first step in learning a a new language is to create a “Hello World” example. But before we do that, let’s figure out where you want to save your Python projects. Having your projects appropriately named and organized helps you be a more efficient programmer and a more astute computer user.

Through trial and error, every developer eventually figures out what works best for them. Don’t put everything on your desktop or in your Downloads folder. Be thoughtful and imagine yourself trying to find your work in the future. How will it be easiest to find?

One method is to create a new folder called Python in your Documents folder. Then create another folder called Hello World inside your Python folder. Any additional Python projects can be created as new folders inside the Python folder.

Now open VS Code, click the File menu > Open Folder. Navigate to the Hello World folder you just created and choose Open. VS Code may ask you, “Do you trust the authors of the files in this folder?” Select, “Yes, I trust the authors.”

The folder opens in the Explorer pane of VS Code. Right-click in the Explorer pane and choose New File… Name the file ‘hello-world.py’. VS Code creates the file in the Python directory and opens it automatically in the editor pane.

Add the following line to the file: print('Hello, World!')

Printing Hello World in VS Code

Run the Python file by clicking the triangular play button on the top right of the window or by selecting the Run menu > ‘Run without debugging’. VS Code will open a terminal/console window on the bottom of the screen and output the results of the program.

Interpreted vs. Compiled

Programming languages are generally categorized as compiled or interpreted.

Compilation occurs when the source code is translated into machine code and distributed as a single executable file, such as an .exe file on Windows, or apps you find on the macOS and iOS App Stores. The program that performs the compiling is called a compiler. The users of compiled applications can more easily share and run the programs than with programs written in interpreted languages.

Interpreting happens when the source code is translated each time the program runs. The program doing the translating is called an interpreter. The advantage with interpreted languages is that the source code runs on any system that has an interpreter installed. The code is stored as text files, making the programs easier to change and modify. However, interpreted programs tend to be harder to distribute because the host computer might need additional software installed to run the program correctly.

Python is an interpreted language. The Python interpreter is needed if you wish to write Python programs and run them on your computer.

Historically, interpreted languages have been called scripting languages and the programs built with them were called scripts.

Keywords

All programming languages have words, elements, and symbols that make up its structure and meaning. It’s important to use these items in the right order for the program to run correctly and to have the desired output. A program can be correct in a several different ways:

  • lexically - every language has its own dictionary of words
  • syntactically - the structure of language rules that must be obeyed
  • semantically - the key words and syntax must be composed in a way that makes sense

Programming languages contain reserved keywords that cannot be used as variable, class, or function names. These words are used to define the syntax and structure of the language. Python has 35 reserved keywords as of version 3.10.5.

False      await      else       import     pass
None       break      except     in         raise
True       class      finally    is         return
and        continue   for        lambda     try
as         def        from       nonlocal   while
assert     del        global     not        with
async      elif       if         or         yield

Variables

A variable is a name that references a certain object. They are created when you assign value to them and can be referred to by their name. You can assign variables a value with the equal (=) sign.

A variable’s data type is dynamic and can change over its lifetime. You can check a variable’s type by passing the variable into the type() function.

Use sequential variable names and equal signs to assign multiple variables the same value.

x = 31
name = '31 Flavors'
is_open = True

# prints <class 'int'>
print(type(x)) 

x = 'Thirty One'

# prints <class 'str'>
print(type(x)) 

x = y = z = 5

# prints 15
print(x+y+z)

Naming Conventions

Python has restrictions when it comes to naming variables.

  • Names must start with a letter or underscore character
  • Names cannot start with a number
  • Names can only contain alphanumeric (A-Z , a-z, or 1-9) and underscore characters (_)
  • Names are case sensitive

Though not required, the Python community has a set of best practices for naming variables.

  • Use self-documenting names that make sense
  • Use snake_case instead of camelCase
  • Use uppercase when defining constants

Statements

Statements are what the Python interpreter executes. Statements can be single or multi-line operations. A backslash serves as a line break when you want to extend the statement to the next line.

Multi-line statements can help organize code and make it easier to read and edit. Experienced programmers create collections of data such as lists, tuples, and dictionaries by organizing individual elements on their own line. Line breaks are not needed when defining collections in this way.

Semi-colons are not required to end statements in Python. However, you can use them to separate multiple statements on a single line.

a = 1

nums = 1 + 2 + 3 + \
	   4 + 5 + 6 + \
	   7 + 8 + 9

flavors = ['Vanilla',
		   'Chocolate',
		   'Strawberry',
		   'Butter Pecan']

for i in range(1,11):
	if i % 2 == 0:
		print(i)

x = 1; y = 2; z = 3

Indentation

In other languages like JavaScript and Go, curly brackets are used to create blocks of code that delineate the start and end points of a set of instructions. In Python, spaces serve this function instead. The indentation groups statements into blocks of code that gets executed together.

a = 4
b = 3
if a > b:
	print('a is larger than b')

while a > 0:
	a -= 1
	b += 1
	print(a + b)

The indentation must be consistent throughout your code. If you use four spaces for indentation, you must always use four spaces.

Python will return an error if the code indentation is incorrect. You can use single or multiple spaces for indentation. Using four spaces is considered a best practice.

Comments

Comments can be inserted into your code to add short notes that clarify what the code does or how it should work. Place a hash sign where you want to add the comment and the Python interpreter will ignore everything else on that line that follows.

Multi-line comments can be added with triple-single or triple-double quotes.

# this is a single line comment
print('Hello, World!')

"""
This is a mult-line
comment that spans
three lines
"""
print('Hello again!')

Do not overuse comments. Comments should not duplicate code or be used as an excuse for poorly written code. Write clean code with descriptive naming conventions to reduce confusion and the need for commenting.

Use comments responsibly. Comments can help explain unidiomatic or complex portions of code, provide links to external references, report bug fixes, and mark incomplete code.

Boolean, integers, floating-point numbers

Booleans in Python are represented by the values True and False. Booleans are returned when evaluating expressions and are most commonly seen inside conditional statements and iterative loops.

Booleans evaluate to the numeric values 1 or 0 for True and False values. This allows programmers to use boolean values in mathematical operations.

Use the bool() function to evaluate a variable and return the boolean representation. Most variables return True if they have content. Empty lists, tuples, dictionaries, and the number 0 return False.

print(3 > 4)              # prints False

is_cold = True            # equal to 1
is_tasty = False          # equal to 0

print(is_cold + is_tasty) # prints 1

print(bool(is_cold))      # prints True
print(bool(0))            # prints False

Integers are whole numbers and can be either positive or negative. Very large integers can be difficult to read when they have many digits.

Python allows the use of underscores with numeric literals to improve readability.

a = 3
b = 4
population = 333_076_834

Float, or floating point, numbers contain decimals and are represented in one of two ways. Dot-notation can be represented simply as 3.14. Scientific notation is represented by an upper or lowercase ‘E’ that is used to indicate the power of 10 such as 1.23e8.

Floating point numbers are approximations. Computers can only understand binary numbers comprised of 1s and 0s. However, there is no binary representation for fractions, which is what a floating point is.

Rounding errors occur in the last few bits of data and a loss of precision occurs. Keep this in mind because the result of float operations may not always be what you expect.

pie = 3.14159

a = 1.5e3 # 1500
b = 1.5E4 # 15000

print(.1 + .1 + .1 == .3) # prints False
print(.1 + .1 + .1)       # prints 0.30000000000000004

Strings

Strings are a series of characters surrounded by single, double, or triple quotes. The Python community prefers single quotes when creating and working with string literals. Line breaks, tabs, and spaces are a part of strings that are created with triple quotes.

flavor1 = 'Peach'

flavor2 = "Wombat"

flavor3 = '''Everything

but
     the
	     kitchen
sink
'''

Strings can be indexed and sliced to get individual characters or substrings. You can also loop through a string, get its length, and check if a string contains a substring.

flavor = 'Peppermint'
print(flavor[0])      # prints P
print(flavor[0:6])    # prints Pepper

for letter in flavor:
	print(letter)     # prints each letter of 'Peppermint' on a new line

print(len(flavor))    # prints 10

if 'P' in flavor:
	print('The string contains a "P"')

Apostrophes in strings must be escaped with a backslash if the string is created with single quotes. They do not need to be escaped when using double-quotes.

question = 'What\'s the weirdest ice cream flavor you\'ve tried?'
response = "Mac 'n Cheese."
print(question)
print(response)

The following list contains additional escaped characters and their result. These are good to know.

  • \n creates a new line
  • \t creates a tab
  • \' inserts a single quote in strings created with single quotes
  • \\ creates a backslash
print('Ice cream\nbrings people\ntogether')
print('This ice cream\'s flavor is great!')
print('\\00\t00//')

Summary

In this post we looked the basics of programming as well as the essential syntax and structure of Python. In future lessons we will look at further Python topics in conditionals, operations, and loops.

Check out our Python reading list to view more Python lessons.