Python - Syntax

Python

Share
python logo

In this tutorial we will learn about Python syntax.

Comment

We create single line comments in Python using the hash # symbol.

In the following example we are creating a single line comment.

# hello world this is a single line comment...

For multiline comments we use delimiter """ at the start and end of the comment.

In the following example we are creating a multiline comment.

"""
Hello World
This is a multiple line
comment...
"""

Semicolon ;

If you are familiar with other programming languages like C and Java then you know that we have to end the line with the semicolon ; character.

In Python we don't have to end the line with semicolon. You can put a semicolon if you want but it is not required.

Case Sensitive

Python is case-sensitive language. This means a variable named score is completely different from a variable named SCORE.

Indentations

We use indentations in other programming languages to make the code more readable.

In Python, indentations holds a special meaning. It defines a block of code.

For example, we will write the following to create a if-statement in PHP.

// set value of x
$x = 1;

// now check
if ($x == 1) {
  echo "x is 1";
} else {
  echo "x is not 1";
}

In Python we don't have to use the curly-brackets { } but instead we use indentation to make the if and else block.

# set value of x
x = 1

# now check
if x == 1:
  print("x is 1")
else:
  print("x is not 1")

Indentation in Python indicates a block of code. So, each line in a block must be indented the same amount.

Following code will give error as third line in the if-block is not properly indented.

x = 1
if x == 1:
  print("x is 1")
  print("x is an integer")
    print("This line will give us error")	# this line is not correctly indented

If we run the above code we will get a similar error output.

File "/Users/yusufshakeel/PycharmProjects/HelloWorld/Syntax.py", line 5
    print("This line will give us error")	# this line is not correctly indented
    ^
IndentationError: unexpected indent

Quotation

In Python we can use single quote ', double quotes " and triple quotes ''' to denote string literal.

In the following example we are assigning string value to a variable using single quote.

msg = 'Hello World'

In the following example we are assigning string value to a variable using double quotes.

msg = "Hello World"

In the following example we are assigning multiline string value to a variable using triple quotes.

msg = '''Hello World
This is a multiline
string value'''

We can also mix the quotes. In the following example we are using double quotes inside single quotes.

msg = 'This is the "Hello World" message.'

The above code will give us the following output.

This is the "Hello World" message.
Share