Python’s basic syntax
Contents
5. Python’s basic syntax#
Author: Tue Nguyen
5.1. Outline#
Math operations
Assignments
Literals
Expressions
Comments
Printing
Statements
Line continuation
Whitespaces
Indentation
Get help
5.2. Overview#
This tutorial aims to provide just some very basic syntax so that you can get started immediately
It’s like when you first learn a new language
You don’t dive into learning grammar right away
Instead, you learn some basic vocabulary and simple sentences
This lecture serves such a purpose
In the next lectures, you will learn Python in a more systematic way
5.3. Math#
You can use Python as a calculator to compute math expressions
Math operations are intuitive. Ex:
+, -, *, /
# Addition
2 + 3
5
# Subtraction
2 - 3
-1
# Multiplication
2 * 3
6
# Division
2 / 3
0.6666666666666666
# Integer division
2 // 3
0
# Modulus (get the remainder)
2 % 3
2
# Exponential (use `**`, not `^`)
2**3
8
# More complicated expressions
# Use parentheses if needed
1000 * (1 + 0.05)**20
2653.2977051444223
5.4. Assignments#
An assignment assigns a value to a variable (will learn in detail later)
We use
=
to make an assignmentAfter an assignment, we can use the variable name to refer to its associated value
# Assign a value 100 to variable x
x = 1000
# Use x as a reference to its associated value
x + 500
1500
5.5. Literals#
A literal is a fixed or constant value
When you see it, it is literally the value it represents
No additional conversion is needed
# Integer literal
1000
1000
# Boolean literal
True
True
# String literal
"This is a string"
'This is a string'
5.6. Expressions#
An expression is anything that can be evaluated as a value
It can be a combination of literals and variables, for example
# Add 2 integers
100 + 200
300
# Concatenate 2 strings
"Hello" + "World"
'HelloWorld'
# Add an integer literal to a integer variable
x + 100
1100
5.8. Printing#
You can use
print()
function to print out values associated with a literal, a variable, or an expressionRoughly speaking, a function (will learn in detail later)
takes some input (inside the parentheses)
does something with the input
and spits out some output
# Print a number literal
print(1.25)
1.25
# Print a number literal using double quotes
print("Hello")
Hello
# Print a number literal using single quotes
print('Nice to meet you')
Nice to meet you
# Print a variable
total = 2 + 3
print(total)
5
# Print an expression
print(2**3 + 4)
12
5.9. Statements#
A statement is a complete instruction that Python can execute
It is like a full-sentence in English, for example
# An assignment statement
total = 2 + 3
# A print statement
print("Good morning")
Good morning
Warning
However,
total =
is not a statementYou will get an error if you try to run it.
Note 1: each statement normally sits on one line
print("Hello")
print("Good morning")
Hello
Good morning
Note 2: you can ends a statement with a semicolon
But it is not required
And it is not recommended as well (redudant + ugly)
# You can end a statement with ;
# NOT recommended
print("Hello");
print("Good morning");
Hello
Good morning
Note 3: you can use semi-colins ;
to write muliple statement on 1 line
But you should NOT do so
It make your code less readable
# Use ; to write multiple statements on 1 line
# NOT recommended
x = 5; y = 6; z = 7
print(x + y + z)
18
# A better alternative
# write each statement on its own line
x = 5
y = 6
z = 7
print(x + y + z)
18
5.10. Line continuation#
On some occasions, you might have to write a complex statement
And keeping everything in one line make it very ugly and hard to read.
If so, you can break it into multiple (shorter) lines in two ways
Method 1: put a backslash
\
at the end of each lineMethod 2: wrap your code in a pair of parentheses
# Method 1: use \
x = 1 + 2 + 3 +\
4 + 5 + 6 +\
7 + 8 + 9
print(x)
45
# Method 2: use ()
x = (1 + 2 + 3 +
4 + 5 + 6 +
7 + 8 + 9)
print(x)
45
5.11. White spaces#
White spaces include spaces, tabs, newlines, and blank lines
Often, whitespaces are ignored by Python’s interpreter
Ex 1: extra spaces don’t count
print(2+3)
print(2 + 3)
print( 2 + 3)
5
5
5
Notes
All three statements print out the same result
However, the second line is considered to follow best practices
More on coding style guide in future lectures
Ex 2: new lines and blank lines don’t count either
# Snippet 1
x = 2 + 3
y = 4 + 5
print(x + y)
14
# Snippet 2
x = 2 + 3
y = 4 + 5
print(x + y)
14
Notes:
Again, snippet 2 is better than snippet 1 in terms of coding style
5.12. Indentation#
Indentation means the spaces at the beginning of each line
You use
Tab
to indentShift + Tab
to dedent
Unlike other languages, indentation does matter in Python
Python uses indentation to indicate a code block
It is similar to the use of curly brackets
{}
in other languages
For now, remember the following
Never indent your code if you dont have a reason
Always indent the new line after a statement that ends with
:
such asAn
if
statementA
for
orwhile
statement
a) Ex 1: try the following code (no error)
age = 30
if age >= 21:
print("Congrats! You can buy vodka")
b) Ex 2: try the following code (error)
age = 30
if age >= 21:
print("Congrats! You can buy vodka")
5.13. Getting help#
You need help when you face things that
You don’t know
You know, but you forget the details
You can get help in 2 ways
Internal documentation of Python using
?
Google (tips: add “stackoverflow” to the search queries)
a) Ex 1: get internal help using ?
# Get help for print
?print
# Get help for abs
?abs
b) Ex 2: get help using Google
Try the following queries
Python compute absolute value stackoverflow
Python sort a list stackoverflow
5.14. Summary#
Math
Basic:
+, -, * /
Modulus:
//, %
Exponential:
**
Use parentheses if needed
Assigment
Syntax:
variable_name = value
After that, use the variable name to refer to the value
Literals
Literals = fixed values
Ex:
1000
(integer literal),True
(Boolean literal),"hello"
(string literal)
Expressions
An expression = anything that can be evaluated as a value
Can be a combination of literals and variables
Comments
Used for human and are ignored by Python
Start a comment with
#
Comment can be on 1 line or multiple lines
Printing
Use
print()
print()
accepts a literal, variable, expression
Statements
A statement = a complete instruction that Python can execute
total = 2 + 3
is a statementtotal =
is NOT a statement
Some best practices
Write each statement on 1 line
Never end a statement with
;
Line continuation
Used to break a long statement into smaller pieces (for readability)
Two ways: use
\
or()
White spaces
White spaces = spaces, tabs, newlines, and blank lines
Often, whitespaces are ignored by Python’s interpreter
You whitespaces wisely to increase readability (more on next lectures)
Indentation
Indetation DOES matters
Keyboard
Tab
to indentShift + Tab
to dedent
For now
Never indent your code if you have no reason
Always indent the new line after
:
ofif
,for
, andwhile
statements
Getting help
Internal help: use
?
Online help: Google with the following template
Python + key words + stackoverflow
5.7. Comments#
Comments are used to document your code
Why? To help other people can understand what you are doing (if your code is not so obvious)
Other people also include future you because it is not uncommon that you will forget what you have done after a few weeks (or even days)
Comments are for human-only and are ignored by the interpreter
In Python, a comment starts with
#
# This is a single-line comment