Table of contents
- Python Indentation
- Python Identifiers
- Python Reserved Words
- Python Multi-Line Statements
- Quotations in Python
- Comments in Python
- Using Blank Lines in Python Programs
- Waiting for the User
- Multiple Statements on a Single Line
- Multiple Statement Groups as Suites
- Command Line Arguments in Python
- Advantages of Python 3:
- Disadvantages of Python 3:
- Python Keywords
It’s not compiled and the interpreter will check the code line by line.
So before moving on further.. let’s do the most popular ‘HelloWorld’ tradition and hence compare Python’s Syntax with C, C++, and Java ( I have taken these 3 because they are the most famous and most used languages).
# Python code for "Hello World"
# nothing else to type...see how simple is the syntax.
print("Hello World")
Note: Please note that Python for its scope doesn’t depend on the braces ( { } ), instead it uses indentation for its scope.
Python Indentation
Indentation refers to the spaces at the beginning of a code line.
Whereas in other programming languages, the indentation in code is for readability only, the indentation in Python is very important.
Python uses indentation to indicate a block of code.
if 5 > 3:
print("Five is greater than three!")
Python will give you an error if you skip the indentation:
if 5 > 3:
print("Five is greater than three!")
Let us start with our basics of Python where we will be covering the basics in some small sections. Just go through them and trust me you’ll learn the basics of Python very easily.
Python Identifiers
A Python identifier is a name used to identify a variable, function, class, module or other object. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores and digits (0 to 9).
Python does not allow punctuation characters such as @, $, and % within identifiers.
Python is a case-sensitive programming language. Thus, Manpower and manpower are two different identifiers in Python.
Here are naming conventions for Python identifiers −
Python Class names start with an uppercase letter. All other identifiers start with a lowercase letter.
Starting an identifier with a single leading underscore indicates that the identifier is private.
Starting an identifier with two leading underscores indicates a strongly private identifier.
If the identifier also ends with two trailing underscores, the identifier is a language-defined special name.
Python Reserved Words
The following list shows the Python keywords. These are reserved words and you cannot use them as constants variables or any other identifier names. All the Python keywords contain lowercase letters only.
and | as | assert |
break | class | continue |
def | del | Elif |
else | except | False |
finally | for | from |
global | if | import |
in | is | lambda |
None | nonlocal | not |
or | pass | raise |
return | True | try |
while | with | yield |
Python Multi-Line Statements
Statements in Python typically end with a new line. Python does, however, allow the use of the line continuation character () to denote that the line should continue. For example −
total = item_one + \
item_two + \
item_three
Statements contained within the [], {}, or () brackets do not need to use the line continuation character. For example, the following statement works well in Python −
days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']
Here's a breakdown of what this code does:
It defines a list named
days
.The list contains five elements, each of which is a string representing a day of the week, starting with Monday and ending with Friday.
You can access individual elements in the list using their indices. For example:
print(days[0]) # This will print 'Monday'
print(days[1]) # This will print 'Tuesday'
# and so on...
You can also iterate through the list using a loop to perform operations on each day or access their values one by one.
Quotations in Python
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.
The triple quotes are used to span the string across multiple lines. For example, all the following are legal −
word = 'word'
print (word)
sentence = "This is a sentence."
print (sentence)
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""
print (paragraph)
Comments in Python
A comment is a programmer-readable explanation or annotation in the Python source code. They are added to make the source code easier for humans to understand and are ignored by the Python interpreter
Just like most modern languages, Python supports single-line (or end-of-line) and multi-line (block) comments. Python comments are very much similar to the comments available in PHP, BASH and Perl Programming languages.
A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and up to the end of the physical line are part of the comment and the Python interpreter ignores them.
# First comment
print ("Hello, World!") # Second comment
Output:
Hello, World!
You can type a comment on the same line after a statement or expression −
name = "Rahul" # This is again comment
You can comment on multiple lines as follows −
# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.
The following triple-quoted string is also ignored by the Python interpreter and can be used as a multiline comment:
'''
This is a multiline
comment.
'''
Using Blank Lines in Python Programs
A line containing only whitespace, possibly with a comment, is known as a blank line and Python ignores it.
In an interactive interpreter session, you must enter an empty physical line to terminate a multiline statement.
Waiting for the User
The following line of the program displays the prompt, the statement saying “Press the enter key to exit”, and waits for the user to take action −
#!/usr/bin/python
raw_input("\n\nPress the enter key to exit.")
Here, "\n\n" is used to create two new lines before displaying the actual line. Once the user presses the key, the program ends. This is a nice trick to keep a console window open until the user is done with an application.
Multiple Statements on a Single Line
The semicolon ( ; ) allows multiple statements on a single line given that neither statement starts a new code block. Here is a sample snip using the semicolon −
import sys; x = 'foo'; sys.stdout.write(x + '\n')
Output:
foo
Multiple Statement Groups as Suites
A group of individual statements, which make a single code block are called suites in Python. Compound or complex statements, such as if, while, def, and class require a header line and a suite.
Header lines begin the statement (with the keyword) and terminate with a colon ( : ) and are followed by one or more lines which make up the suite. For example −
if expression :
suite
elif expression :
suite
else :
suite
Command Line Arguments in Python
Many programs can be run to provide you with some basic information about how they should be run. Python enables you to do this with -h −
$ python -h
usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-c cmd : program passed in as string (terminates option list)
-d : debug output from parser (also PYTHONDEBUG=x)
-E : ignore environment variables (such as PYTHONPATH)
-h : print this help message and exit
[ etc. ]
Advantages of Python 3:
Python 3 has a simple syntax that is easy to learn and read, making it a good choice for beginners.
Python 3 is a high-level language that has a large standard library and many third-party libraries available, making it a versatile language that can be used for a wide variety of applications.
Python 3 supports multiple programming paradigms, including object-oriented, functional, and procedural programming.
Python 3 is an interpreted language, meaning that it does not need to be compiled before running, making it easy to write and test code quickly.
Python 3 has good support for data analysis and scientific computing, with libraries such as NumPy and Pandas.
Disadvantages of Python 3:
Python 3 can be slower than compiled languages such as C++ or Java, which may be a concern for applications that require high performance.
Python 3 has a global interpreter lock (GIL), which can limit its ability to take advantage of multiple CPU cores.
Python 3 may not be the best choice for low-level systems programming, as it does not offer the same level of control over hardware as other languages.
Python 3 is not as popular in some fields as other languages, such as R for data analysis or C++ for game development, so it may not always be the best choice for specific applications.
Python Keywords
Keywords in Python are reserved words that can not be used as a variable name, function name, or any other identifier.
List of Keywords in Python:
Keyword | Description | Keyword | Description | Keyword | Description |
and | It is a Logical Operator | False | Represents an expression that will result in not being true. | nonlocal | It is a non-local variable |
as | It is used to create an alias name | finally | It is used with exceptions | not | It is a Logical Operator |
assert | It is used for debugging | for | It is used to create a Loop | or | It is a Logical Operator |
break | Break out a Loop | from | To import specific parts of a module | pass | pass is used when the user doesn’t |
class | It is used to define a class | global | It is used to declare a global variable | raise | raise is used to raise exceptions or errors. |
continue | Skip the next iteration of a loop | if | To create a Conditional Statement | return | return is used to end the execution |
def | It is used to define the Function | import | It is used to import a module | True | Represents an expression that will result in true. |
del | It is used to delete an object | is | It is used to test if two variables are equal | try | Try is used to handle errors |
elif | Conditional statements, same as else-if | in | To check if a value is present in a Tuple, List, etc. | while | While Loop is used to execute a block of statements |
else | It is used in a conditional statement | lambda | Used to create an anonymous function | with | with statement is used in exception handling |
except | try-except is used to handle these errors | None | It represents a null value | yield | yield keyword is used to create a generator function |
Get the List of all Python keywords
We can also get all the keyword names using the below code.
# Python code to demonstrate working of iskeyword()
# importing "keyword" for keyword operations
import keyword
# printing all keywords at once using "kwlist()"
print("The list of keywords is : ")
print(keyword.kwlist)
Output:
The list of keywords is :
[‘False’, ‘None’, ‘True’, ‘and’, ‘as’, ‘assert’, ‘async’, ‘await’, ‘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’]
Let’s discuss each keyword in detail with the help of good examples.
True, False, None Keyword
True: This keyword is used to represent a boolean true. If a statement is true, “True” is printed.
False: This keyword is used to represent a boolean false. If a statement is false, “False” is printed.
None: This is a special constant used to denote a null value or a void. It’s important to remember, 0, any empty container(e.g. empty list) does not compute to None.
It is an object of its datatype – NoneType. It is not possible to create multiple None objects and assign them to variables.
True, False, and None
print(False == 0)
print(True == 1)
print(True + True + True)
print(True + False + False)
print(None == 0)
print(None == [])
Output:
True
True
3
1
False
Fasle
and, or, not, in, is
- and: This a logical operator in Python. “and” Return the first false value. If not found return last. The truth table for “and” is depicted below.
3 and 0 return 0
3 and 10 return 10
10 or 20 or 30 or 10 or 70 returns 10
The above statements might be a bit confusing to a programmer coming from a language like C where the logical operators always return boolean values(0 or 1). The following lines are straight from the Python docs explaining this:
The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.
The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.
Note that neither and nor restrict the value and type they return to False and True, but rather return the last evaluated argument. This is sometimes useful, e.g., if s is a string that should be replaced by a default value if it is empty, the expression s or ‘foo’ yields the desired value. Because not have to create a new value, it returns a boolean value regardless of the type of its argument (for example, not ‘foo’ produces False rather than ”.)
- or: This a logical operator in Python. “or” Return the first True value. if not found return last. The truth table for “or” is depicted below.
3 or 0 returns 3
3 or 10 returns 3
0 or 0 or 3 or 10 or 0 returns 3
not: This logical operator inverts the truth value. The truth table for “not” is depicted below.
in: This keyword is used to check if a container contains a value. This keyword is also used to loop through the container.
is: This keyword is used to test object identity, i.e. to check if both the objects take the same memory location or not.
Example: and, or, not, is and in keyword
- Python
showing logical operation
# or (returns True)
print(True or False)
# showing logical operation
# and (returns False)
print(False and True)
# showing logical operation
# not (returns False)
print(not True)
# using "in" to check
if 's' in 'tests':
print("s is part of the tests")
else:
print("s is not part of the tests")
# using "in" to loop through
for i in 'tests':
print(i, end=" ")
print("\r")
# using is to check object identity
# string is immutable( cannot be changed once allocated)
# hence occupy same memory location
print(' ' is ' ')
# using is to check object identity
# dictionary is mutable( can be changed once allocated)
# hence occupy different memory location
print({} is {})
Output:
True
False
False
s is part of the tests
t e s t s
True
False
Iteration Keywords – for, while, break, continue
for: This keyword is used to control flow and for looping.
while: Has a similar working like “for”, used to control flow and for looping.
break: “break” is used to control the flow of the loop. The statement is used to break out of the loop and passes the control to the statement immediately after the loop.
continue: “Continue” is also used to control the flow of code. The keyword skips the current iteration of the loop but does not end the loop.
Example: For, while, break, continue keyword
# Using for loop
for i in range(10):
print(i, end=" ")
# break the loop as soon it sees 6
if i == 6:
break
print()
# loop from 1 to 10
i = 0
while i < 10:
# If i is equals to 6,
# continue to next iteration
# without printing
if i == 6:
i += 1
continue
else:
# otherwise print the value
# of i
print(i, end=" ")
i += 1
Output:
0 1 2 3 4 5 6
0 1 2 3 4 5 7 8 9
Conditional keywords – if, else, elif
if: It is a control statement for decision-making. Truth expression forces control to go in the “if” statement block.
else: It is a control statement for decision-making. False expression forces control to go in the “else” statement block.
elif: It is a control statement for decision-making. It is short for “else if“
Example: if, else, and elif keyword
# Python program to illustrate if-elif-else ladder
#!/usr/bin/python
i = 20
if (i == 10):
print("i is 10")
elif (i == 20):
print("i is 20")
else:
print("i is not present")
Output:
i is 20
Note: For more information, refer to our Python if else Tutorial.
def
def keyword is used to declare user-defined functions.
Example: def keyword
# def keyword
def fun():
print("Inside Function")
fun()
Output:
Inside Function
Return Keywords – Return, Yield
return: This keyword is used to return from the function.
yield: This keyword is used like a return statement but is used to return a generator.
Example: Return and Yield Keyword
# Return keyword
def fun():
S = 0
for i in range(10):
S += i
return S
print(fun())
# Yield Keyword
def fun():
S = 0
for i in range(10):
S += i
yield S
for i in fun():
print(i)
Output:
45
0
1
3
6
10
15
21
28
36
45
class
class keyword is used to declare user-defined classes.
Example: Class Keyword
# Python3 program to
# demonstrate instantiating
# a class
class Dog:
# A simple class
# attribute
attr1 = "mammal"
attr2 = "dog"
# A sample method
def fun(self):
print("I'm a", self.attr1)
print("I'm a", self.attr2)
# Driver code
# Object instantiation
Rodger = Dog()
# Accessing class attributes
# and method through objects
print(Rodger.attr1)
Rodger.fun()
Output:
mammal
I'm a mammal
I'm a dog
Note: For more information, refer to our Python Classes and Objects Tutorial.
With
with keyword is used to wrap the execution of a block of code within methods defined by the context manager. This keyword is not used much in day-to-day programming.
Example: With Keyword
# using with statement
with open('file_path', 'w') as file:
file.write('hello world !')
as
as the keyword is used to create the alias for the module imported. i.e. giving a new name to the imported module. E.g. import math as my math.
Example: as Keyword
import math as gfg
print(gfg.factorial(5))
Output:
120
pass
pass is the null statement in Python. Nothing happens when this is encountered. This is used to prevent indentation errors and is used as a placeholder.
Example: Pass Keyword
n = 10
for i in range(n):
# pass can be used as placeholder
# when code is to added later
pass
In the code you've provided, you have a for
loop that iterates from 0
to n-1
, where n
is equal to 10
. Inside the loop, you have a pass
statement.
The pass
statement in Python is a null operation or a placeholder. It doesn't do anything when executed and is often used when you need a syntactically valid statement but don't want to perform any specific action at that point in your code. It's typically used as a placeholder for future code that you plan to add later.
In your code, since there is only a pass
statement inside the loop, the loop will simply iterate from 0
to 9
without performing any actions for each iteration. It's a common practice to use pass
in such situations when you're in the process of writing code and want to leave a placeholder for future logic or functionality.
Lambda
The lambda keyword is used to make inline returning functions with no statements allowed internally.
Example: Lambda Keyword
# Lambda keyword
g = lambda x: x*x*x
print(g(7))
Output:
343
Import, From
import: This statement is used to include a particular module in the current program.
from: Generally used with import, from is used to import particular functionality from the module imported.
Example: Import, From Keyword
# import keyword
from math import factorial
import math
print(math.factorial(10))
# from keyword
print(factorial(10))
Output:
3628800
3628800
Exception Handling Keywords – try, except, raise, finally, and assert
try: This keyword is used for exception handling, used to catch the errors in the code using the keyword except. Code in the “try” block is checked, if there is any type of error, except block is executed.
except: As explained above, this works together with “try” to catch exceptions.
finally: No matter what is result of the “try” block is, the block termed “finally” is always executed.
raise: We can raise an exception explicitly with the raise keyword.
assert: This function is used for debugging purposes. Usually used to check the correctness of code. If a statement is evaluated to be true, nothing happens, but when it is false, “AssertionError” is raised. One can also print a message with the error, separated by a comma.
Example: try, except, raise, finally, and assert Keywords
# initializing number
a = 4
b = 0
# No exception Exception raised in try block
try:
k = a//b # raises divide by zero exception.
print(k)
# handles zerodivision exception
except ZeroDivisionError:
print("Can't divide by zero")
finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')
# assert Keyword
# using assert to check for 0
print("The value of a / b is : ")
assert b != 0, "Divide by 0 error"
print(a / b)
# raise keyword
# Raises an user defined exception
# if strings are not equal
temp = "tests"
if temp != "tests":
raise TypeError("Both the strings are different.")
Output:
Can't divide by zero
This is always executed
The value of a/b is :
AssertionError: Divide by 0 error
# raise keyword
# Raises an user defined exception
# if strings are not equal
temp = "tests"
if temp != "tests":
raise TypeError("Both the strings are different.")
Output
TypeError: Both the strings are different.
Note: For more information refer to our tutorial Exception Handling Tutorial in Python.
del
del is used to delete a reference to an object. Any variable or list value can be deleted using del.
Example: del Keyword
my_variable1 = 20
my_variable2 = "Tests"
# check if my_variable1 and my_variable2 exists
print(my_variable1)
print(my_variable2)
# delete both the variables
del my_variable1
del my_variable2
# check if my_variable1 and my_variable2 exists
print(my_variable1)
print(my_variable2)
Output:
20
Tests
NameError: name 'my_variable1' is not defined
Global, Nonlocal
global: This keyword is used to define a variable inside the function to be of a global scope.
non-local: This keyword works similarly to the global, but rather than global, this keyword declares a variable to point to a variable of an outside enclosing function, in case of nested functions.
Example: Global and nonlocal keywords
# global variable
a = 15
b = 10
# function to perform addition
def add():
c = a + b
print(c)
# calling a function
add()
# nonlocal keyword
def fun():
var1 = 10
def gun():
# tell python explicitly that it
# has to access var1 initialized
# in fun on line 2
# using the keyword nonlocal
nonlocal var1
var1 = var1 + 10
print(var1)
gun()
fun()
Output:
25
20
Note: For more information, refer to our Global and local variables tutorial in Python.