Lesson 1: Basic Syntax

In this lesson we will learn about...

  • Your First Program: "Hello, World!"
  • Identifier Rules and Reserved Words
  • Lines and Indentation
  • Quotation
  • Comments
  • Input and Output

A Word of Warning about Python Versions

  • Two main version of python are still in use: Python 2 and Python 3.
  • We are using Python 3. Make sure you are using the correct tools!

"Hello, World!"

The "Hello, World!" program is the most basic you can run, and is traditionally your first program.

In [1]:
print("Hello, World!")
Hello, World!

Indentation

  • Blocks of code need to be indented
  • The number of tabs/spaces is up to you, but must be consistent
    • Python's Style Guide suggests using 4 spaces per indent
  • No braces are used, unlike many other programming languages
In [2]:
# Correct
if True:
    print("True")
else:
    print("False")
True
In [3]:
# Incorrect
if True:
print("True")
else:
print("False")
  File "<ipython-input-3-71288eeef709>", line 3
    print("True")
        ^
IndentationError: expected an indented block

Quotation

  • Use single ('), double ("), or triple (''' or """) quotes to denote string literals
  • Single and Double quotes span one line
    • In python, these have no syntactic difference
  • Triple quotes can span multiple lines
  • Use a backslash (\) to escape a quotation mark in a string
    • You do not have to escape " inside ', and vice versa
In [4]:
string1 = 'string'
string2 = "string"
sentence = "This is a sentence \"with double quotes\" "
sentence2 = 'This is also a sentence "with double quotes in it"'
multiline = """This is a quote 
that takes multiple lines. Notice 
how the newlines are part of the string too!"""

print(string1)
print(string2)
print(sentence)
print(sentence2)
print(multiline)
string
string
This is a sentence "with double quotes" 
This is also a sentence "with double quotes in it"
This is a quote 
that takes multiple lines. Notice 
how the newlines are part of the string too!

Comments

Comments are pieces of text in a python file that are not interpreted as code.

In [5]:
# This is a comment
a = 2 # This is also a comment

# blank lines also are ignored!

Input and Output

  • Use input() to get input from the keyboard.
  • Use print() to send output to the screen.
In [6]:
text = input("Enter some text: ")
print(text)
Enter some text: This is from the keyboard.
This is from the keyboard.