Repository navigation
Syntax
Let us execute the programs in different modes of programming.
Interactive Mode:
Type "python" in terminal.
$ python
Python 3.3.2 (default, Dec 10 2013, 11:35:01)
[GCC 4.6.3] on Linux
Type "help", "copyright", "credits", or "license" for more information.
Example:
print ("Hello, World!")Result:
Hello, World!
Script Mode:
Create a .py script and write your code in it. Then run it using your IDE's interpreter.
There are some reserved words and you cannot use them as constants or variables or any other identifier names. All the Python keywords contain lowercase letters only.
Python does not use braces({}) to indicate blocks of code for class and function definitions or flow control. Blocks of code are denoted by line indentation, which is rigidly enforced.
Example:
if True:
print ("True")
else:
print ("False")Statements in Python typically end with a new line. Python, however, allows the use of the line continuation character () to denote that the line should continue.
Example:
total = item_one + \
item_two + \
item_threeThe statements contained within the [], {}, or () brackets do not need to use the line continuation character.
Example:
days = ['Monday', 'Tuesday',
'Wednesday', 'Thursday', 'Friday']Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long as the same type of quote starts and ends the string.
Example:
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""A hash sign (#) that is not inside a string literal is the beginning of a comment. All characters after the #, up to the end of the physical line, are part of the comment and the Python interpreter ignores them.
Example:
#!/usr/bin/python3
# First comment
print ("Hello, Python!") # second commentYou can comment multiple lines as follows:
'''
This is a multiline
comment.
'''A line containing only whitespace, possibly with a comment, is known as a blank line and Python totally ignores it.
In an interactive interpreter session, you must enter an empty physical line to terminate a multiline statement.
The semicolon ( ; ) allows multiple statements on a single line given that no statement starts a new code block.
Example:
import sys; x = 'foo'; sys.stdout.write(x + '\n')