Examples of Python Syntax


Python is easy to learn and it is a good way to learn Python by examples. Here we will introduce some simple examples to help beginners quickly learn Python basic syntax.

1. Encodings

Note: By default, Python 3 uses utf-8 as standard encoding of source code if no other encoding hints are given. You can specify other encodings by adding a line at the beginning of the codes.

Here is an example:

#!/usr/bin/env python
# -*- coding: latin-1 -*-

u = 'abcdé'
print(ord(u[-1]))

In this example, it defines encoding “latin-1” which allows the use of Latin codes in Python source files.

2. Identifiers

In Python, an identifier is a name used to identify a variable, function, class, module or other object. Here are a few important rules about identifiers for beginners to know:

  • The identifier should start with a letter or an underscore. If you use digits to begin an identifier name, it will lead to the syntax error.
  • The rest of the identifier can be letters, numbers, and underlines.
  • Identifiers are case sensitive.

More details about Python identifiers will be introduced in separate articles.

3. Reserved Words

Reserved words are Python keywords. We can not use them as an identifier name. The standard library of Python provides a keyword module and you can print out all keywords of the current Python version:

>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', ' Else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not' , 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

4. Comments

Single-line comments in Python should start with #, as shown below:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# First comment
print ("I am a student!") 

Multi-line comments should be embraced by a triple single quotes (or triple double quotes), as shown below:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

''' Third comment Fourth comment '''

""" Fifth comment Sixth comment """ 
print (“Hello, Python!”)

5. Indentation

The most special feature of Python is the use of indentation to mark code blocks. In contrast, other programming languages often use braces {} to mark code blocks. Let’s take a look at an if-else example to explain how the indentation works for Python:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

if score > 90:
    print('Game over!')
    print('You have won the game, Congrats!')
else:
    print('Game continue!')

print('Note: You can exit the game anytime by pressing escape button')

In this example, the lines print(‘Game over’) and print(‘Game continue’) are two separate code blocks.

In Python, if you want to indicate a block of code, the method is to indent each line of the block by the same amount. Here the two blocks of code are both indented four spaces, which is a typical amount of indentation for Python. The final print(‘Note:…’) is not indented, and thus it does not belong to if-else blocks. It will be printed out no matter which condition (score>90 or not) is met.

6. Statement wrap

In Python usually you need to write a single statement in one line, but if the statement is long, you may use a backslash(\) to implement a multi-line statement. Below is an example:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

def print_long_statement():
         print 'This is a long statement,', \
               'here we make it across multiple lines with backslash.'

7. Number Type

There are four types of numbers in python:

  • int (integer), such as 1.
  • bool (boolean), such as True.
  • float (floating point), such as 1.23, 3E-2.
  • complex (plural), such as 1 + 2j, 1.1 + 2.2j.

8. String Operations

Operation on strings is often needed in Python programming. Here we list a few important notes.

  • Single and double quotes work similarly in Python string operation.
  • Using a triple quotation mark (”’ or “””) can specify a multi-line string.
  • Strings can be joined together with the + operator and repeated with the * operator.
  • Python strings are immutable (i.e. they can’t be modified after creation).
  • Python does not have a data type of Character.
  • Backslashes can be used to escape special characters, and r can be used to stop escaping.

Below are some examples about basic string operations:

#!/usr/bin/python3
# -*- coding: UTF-8 -*-

str = 'Newyork'

# Output string  
print(str) 

# Output all characters from the first to the second last 
print(str[0:-1])

# Output string first character 
print(str[0]) 

# Output characters from the third to the fifth
print(str[2:5]) 

# Output all characters after (also including) the third one
print(str[2:])  

# Output string twice
print(str * 2)  

# Connection string
print(str + 'Hello') 

# Use backslash() to escape special characters
print('hello\n')  

# Add an r in front of the string for no escaping
print(r'hello\n') 

Output:

Newyork
Newyor
N
wyo
wyork
NewyorkNewyork
NewyorkHello
hello

hello\n

In addition, Python has many built-in functions associated with the string data type. These functions allow us easily modify and manipulate strings. In other how-to examples, we will introduce these functions in detail.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments