Each computer programming language has rules or syntax that show exactly how to format your code. In this lesson, we'll explore some of the basic syntax rules for writing Python code. If you do not follow the syntax rules of the programming language, your code cannot be turned into a program that will run successfully. Instead, you will see one or more error messages that let you know there is a problem with your code.

Understanding Programs
A program (or software or application) runs on a computer to complete a task or provide a service. Python programs are written as a series of statements, or lines of code. Within a program, groups of statements may be called code segments, functions, or procedures.

Most useful programs will have both input data and output data. Input data is information provided by the user (the person running the program). A user might type text into a prompt, click on a button, supply a file with data, or provide other kinds of input. Output data can come in many forms, such as text on a screen, data written to a file, images displayed on the screen, sound played through speakers, etc.

The program will use the input data to guide its behavior and produce the desired output. One program may flexibly respond to different types of input or different situations and produce different output. For example, a program simulating a card game may allow the user to take actions like "draw a card", "play a card", or "steal a card from another player". For each action, there are different inputs.

Draw a card - No other user input is needed as the player simply gets the top card from the deck.
Play a card - The user must additionally specify which card to play out of the current hand.
Steal a card - The user must additionally specify from which other player the card will be stolen.
Depending in the game rules, a player may not be able to take all actions - perhaps stealing a card is only allowed in certain situations. The program should flexibly allow for valid inputs in each situation and produce the expected output for each action.

A program specification is a description of a program's behavior (what the program does when it runs). Some descriptions are very high level ("this program will simulate a card game"). More detailed descriptions can include specifics about the exact behavior of the program (e.g. the rules of a "Go Fish" card game), the types of user inputs and outputs (how a user will play the game), and details on how program code will be written to meet all the requirements.

Code Statements
Each code statement in your program code expresses an action that will be executed when you run the program. How does Python know that you have reached the end of a statement? Once you hit the "Enter" key to move to the next line in your program, Python knows that you are done with that statement. Here is an example statement:

myNumber = 1 + 2
Copy
In many other languages, a special character such as a semi-colon ( ; ) is used to end a statement. But Python knows the statement has ended when you press "Enter" to start a new line.

How can you write a very long statement that doesn't fit easily in a code window? There are two ways to handle this. First, you can put the entire statement on one line. The Python language will allow you to write as long a line as you need. Of course, when viewing this line in a code editor, you will have to scroll the window left to right to see the full statement.

You can also choose to break up a long statement into two or more lines. However, you wouldn't press "Enter" to split up your statement into multiple lines as shown below.

myNumber =
1 + 2
Copy
Python will view this as two lines of code: "myNumber=" and "1 + 2". Neither line makes any sense by itself! If you tried to run this Python program, you would see an error message.

To safely break a long statement across multiple lines, add a backslash ( \ ) character at the end of one line to tell Python the statement is continued on the next line. You can break up a single statement into as many lines as you need if you put the backslash character at the end of each line that has more statement code on the next line. The example below breaks one statement into three lines.

myNumber \
= \
1 + 2
Copy
These three lines are understood by Python as a single statement, "myNumber = 1 + 2".

Using the "print()" Function
A function is a block of code that has been pre-written by you or someone else. Your program can call or run functions to make things happen! Python contains a built-in function called "print()" that will let you display output to the console window. We've already shown simple print() statements like the one below. Click the "Run Code" button to see print() in action!

Try It Now


To use the print() function on your own, simply create a Python statement that starts with the keyword "print", followed by opening and closing parentheses (). Inside the parentheses, you will place a pair of double quotes (""). Write the text you'd like to display to the screen in between those quotes.

Be sure to carefully match each opening parenthesis with a closing parenthesis ( and ). You will also need to use a matched set of double quotes " and " to surround your text. If your print() statement produces an error when you run the program, carefully double-check your code to make sure it meets these syntax rules.

Order of Execution
Python programs are arranged as a series of statements, one after another. By default, the program will run one statement at a time, starting at the top and then moving down to the next in your source file. This type of program execution is called sequential, which means the code statements are run in the order they appear in the code.

What do you think will happen when the following Python program is run? Try it and see the results!

Try It Now


That's right, you will see "I'm First" printed on the screen first, followed by "I'm Second" and then "I'm Third".

When reading and writing computer code, it's important that you focus on one statement at a time, starting at the top. Ask yourself what will happen when just that top statement runs. Then, look at the next statement and again figure out what it will do after the previous statement has finished.

The ability to mentally "trace" your way through program code and understand when and how it will do certain things is an important skill for a programmer!
Python Indentation
Computer programs will often include blocks of code. A "block" of code is a series of statements that will work together to complete a single task. Some programming languages like Java and C# use curly braces { } or other symbols to define a single block of code. These braces clearly tell the program that the statements within the braces belong to a single block.

However, Python code uses indentation to identify statements that belong together as a block. To indent a statement, you would add spaces or other white-space to the beginning of the line, moving the actual statement code to the right. A Python code block starts with the first indented statement and ends with the first un-indented line. The amount of indentation is up to you, but it must be the same throughout that block.

In the example below, both the "umbrella = true" and the "sunShining = false" lines of code belong to the same block. They are both indented to the right by the same amount.

if isRaining == true:
umbrella = true
sunShining = false
Copy
You don't need to worry about indenting any of your code right away. As you begin to write more complex programs and logic, the indentation will become more important, so we will return to this concept later. For now, make sure all your Python statements start on the left side of your source code, without any indentation.

Comments
Sometimes, program code can be hard to read or understand, especially if someone else wrote the code. Programmers will often leave comments in the source code to help themselves and others understand what the code is doing.

Comments contain no code at all, and anything inside a comment is completely ignored when your program runs. To create a comment in Python, start with a single hashtag ( # ). Then, on the remainder of that line, you can write any useful description without worrying about syntax rules. The example below shows two comment lines and a single program statement.

# This is going to be very exciting.
# We're about to find out what happens when you add two numbers together!
myNumber = 1 + 2
Copy
You are encouraged to add comments anywhere a program statement might need more explanation, so a human reader can understand what's happening. Comments can begin on their own line or start after the end (to the right) of a Python statement.

# Calculate the area of a rectangle, given the length and width
length = 2 # set the length
width = 4 # set the width
myArea = length * width # multiply together to calculate area
Copy
With comments, a program becomes more understandable to human readers. You have not yet learned how to work with the data and math statements in the example above. However, the comments make it clear what the program is doing, even if the code looks mysterious.

Python will ignore any line that starts with the hashtag ( # ) character and there are no limits to the number of comments you can make. It is best practice to add clear comments to your program!

1. What can happen if your code does not follow syntax rules?
2. How do you identify the end of a Python statement?
3 How do you break a long statement across two or more lines in the source file?
4. What does the print() statement do? How is it formatted?
5. What is the normal order of execution for statements in a program?
6. How do you use indentation to mark blocks of code?
7. What are comments and why are they important?
8. How do you create a comment in a Python program?

1. If your code does not follow syntax rules, you will see one or more error messages indicating that there is a problem with your code. Your code will not be able to be turned into a program that will run successfully.

2. The end of a Python statement is identified by pressing "Enter" to start a new line. In other programming languages, a special character like a semi-colon is used to end a statement, but in Python, pressing "Enter" indicates the end of a statement.
3. To break a long statement across two or more lines in the source file, you can add a backslash (\) character at the end of one line to tell Python that the statement continues on the next line. Each line with more statement code should have a backslash at the end.
4. The print() statement is used to display output to the console window. It is formatted as "print()" followed by opening and closing parentheses. Inside the parentheses, you can place the text you want to display in double quotes ("").
5. The normal order of execution for statements in a program is sequential. The program will start at the top and run one statement at a time, moving down to the next statement in the source file.
6. Indentation is used in Python to mark blocks of code. To indent a statement, you add spaces or other white-space to the beginning of the line, moving the actual statement code to the right. A block of code starts with the first indented statement and ends with the first un-indented line. The amount of indentation must be the same throughout the block.
7. Comments are used to provide explanations or additional information in the source code. They contain no code and are completely ignored when the program runs. Comments help programmers and others understand what the code is doing. They are important for improving the readability and maintainability of the code.
8. To create a comment in a Python program, you start with a single hashtag (#) and write any useful description or explanation for that line of code. The hashtag tells Python to ignore the rest of the line. Comments can be on their own line or start after the end of a Python statement.