Python Keywords and Syntax Overview
Python Keywords and Syntax Overview
1 Keywords in Python
Here are the key points related to keywords in Python:
Definition: Keywords in Python are reserved words that cannot be used as ordinary identifiers.
They are used to define the syntax and structure of the Python language.
Immutability: Keywords are immutable. This means their meaning and definition can't be altered.
Case Sensitivity: Keywords are case-sensitive. For example, True is a valid keyword, but true is
not.
Total Number: As of Python 3.9, there are 35 keywords.
List of Keywords: The complete list of Python keywords are 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.
Special Keywords: async and await are used for handling asynchronous processing, and they became
keywords in Python 3.7.
Usage: Each keyword has a specific meaning and usage in Python programming. For instance, def
is used for defining functions, if is used for making conditional statements, for and while are used
for loops, class is used for defining a class, and so on.
Identifying Keywords: You can get the list of all keywords in Python by using the following code:
[65]: # instal package "keyword" to check how many keywords are there
# pip install keyword
# load package
import keyword
1
[66]: # To check current working directory
%pwd
[67]: none = 10
class_number = 10
return_value = 5
if_string = "hello"
else_number = 3.14
2 Identifiers
Here are the key points related to identifiers in Python:
Definition: An identifier is a name given to entities like class, functions, variables, etc. It helps to
differentiate one entity from another.
Syntax: Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or
digits (0 to 9) or an underscore (_).
No digits: They must start with a letter or the underscore character, but not with a digit.
Case-Sensitive: Identifiers in Python are case-sensitive. For example, myVariable and myvariable
are two different identifiers in Python.
No Special Characters: Identifiers cannot have special characters such as !, @, #, $, %, etc.
2
Reserved Words: Python keywords cannot be used as identifiers. Words like for, while, break,
continue, in, elif, else, import, from, pass, return, etc. are reserved words. You can view all
keywords in your current version by typing help(”keywords”) in the Python interpreter.
Unlimited Length: Python does not put any restriction on the length of the identifier. However,
it's recommended to keep it within a reasonable size, to maintain readability and simplicity in the
code.
Private Identifiers: In Python, if the identifier starts with a single underscore, it indicates that it is
a non-public part of the class, module, or function. This is just a convention and Python doesn't
enforce it. If it starts with two underscores, it's a strongly private identifier. If the identifier also
ends with two trailing underscores, the identifier is a language-defined special name.
Non-ASCII Identifiers: Python 3 allows the use of non-ASCII letters in the identifiers. This means
you can use letters like é, ñ, ö, �, etc. in your identifiers if you wish.
[ ]: num1 = 5
_value = 10
text_string = 'Hello, Everyone!'
print(num1, _value, text_string)
[ ]: _1a = 10
_1b = 20
c = _1a + _1b
print(c)
[ ]: my_var = 'lowercase'
MY_VAR = 'UPPERCASE'
print(my_var, MY_VAR)
3 Comments
Here are some key points about comments in Python:
Definition: A comment in Python is a piece of text in your code that is not executed. It's typi-
cally used to explain what the code is doing or leave notes for developers who will be reading or
maintaining the code.
Single-Line Comments: Python uses the hash symbol (#) to denote a comment. Any text following
the # on the same line will be ignored by the Python interpreter.
Multi-Line Comments: Python does not have a specific syntax for multi-line comments. Developers
typically use a single # for each line to create multi-line comments. Alternatively, multi-line strings
using triple quotes (''' or ”””) can also be used as multi-line comments because any string not
assigned to a variable is ignored by Python.
Docstrings or documentation strings: Docstrings are a type of comment used to explain the purpose
of a function or a class. They are created using triple quotes and are placed immediately after the
definition of a function or a class. Docstrings can span multiple lines and are accessible at runtime
using the .__doc__ attribute.
3
[ ]: # This is a comment in Python
x = 5 # This is an inline comment
[ ]: # Docstring Example
def add_numbers(a, b):
"""
This function adds two numbers and returns the result.
Parameters:
a (int): The first number
b (int): The second number
Returns:
int: The sum of the two numbers
"""
return a + b
variable1 = 10
second_variable = 20
third_variable = 30
variable_for = 40
4
4 Indentation
Indentation
Importance: In Python, indentation is not just for readability. It's a part of the syntax and is used
to indicate a block of code.
Space Usage: Python uses indentation to define the scope of loops, functions, classes, etc. The
standard practice is to use four spaces for each level of indentation, but you can use any number
of spaces, as long as the indentation is consistent within a block of code.
Colon: Usually, a colon (:) at the end of the line is followed by an indented block of code. This is
common with structures like if, for, while, def, class, etc.
[ ]: def say_hello():
print("Hello, Eeveryone!")
if True:
print("This is True!") # Error: expected an indented block
for i in range(3):
print(i) # Error: expected an indented block
def hello():
print("Hello, World!") # Error: expected an indented block
while False:
print("This won't print") # Error: expected an indented block
if True:
print("This is True!")
for i in range(3):
print(i)
def hello():
print("Hello, World!")
5
while False:
print("This won't print")
5 Statements
Definition: A statement in Python is a logical instruction that the Python interpreter can read and
execute. In general, a statement performs some action or action.
Types: Python includes several types of statements including assignment statements, conditional
statements, looping statements, etc.
[ ]: # Conditional Statement
x = 2
if x > 0:
print("Positive number")
[ ]: #
for i in range(5):
print(i)
[ ]: # Multi-Line Statements
# Using line continuation character
s = 1 + 2 + 3 + \
4 + 5
# Using parentheses
s = (1 + 2 + 3 +
4 + 5)
6 Variables
Definition: In Python, a variable is a named location used to store data in memory.
Declaration and Assignment: Variables are declared by writing the variable name and assigning it
a value using the equals sign (=). For example:
[ ]: a = 5
st = "hello"
Dynamic Typing: Python is dynamically typed, which means that you don't have to declare the
type of a variable when you create one. You can even change the type of data held by a variable
6
at any time.
[ ]: x = 5 # x is an integer
x = "Hello" # now x is a string
[ ]: x = 10
y = -3
Floats: Floats represent real numbers and are written with a decimal point.
[ ]: x = 10.0
y = -3.14
Strings: Strings in Python are sequences of character data. They are created by enclosing characters
in quotes.
[ ]: s = "Hello, World!"
print(s)
———————————————————————————–
Lists
Definition: A list in Python is an ordered collection (also known as a sequence) of items. Lists are
similar to arrays in other languages, but with additional functionality.
Mutable: Lists are mutable, which means their elements can be changed (added, modified, or
deleted) after they are created.
Creation: A list is created by placing items (elements) inside square brackets [], separated by
commas.
Heterogeneous Elements: A list can contain elements of different types: integers, floats, strings,
and even other lists or tuples.
Indexing and Slicing: Lists support indexing and slicing to access and modify their elements.
Python list indices start at 0.
[ ]: my_list = [1, 2, 3, 4, 5]
print(my_list[0]) # 1
print(my_list[1:3]) # [2, 3]
7
my_list[0] = 10 # change the first element to 10
print(my_list)
———————————————————————————–
Tuples
Definition: A tuple in Python is similar to a list. It’s an ordered collection of items.
Immutable: The major difference from lists is that tuples are immutable, which means their ele-
ments cannot be changed (no addition, modification, or deletion) after they are created.
Creation: A tuple is created by placing items (elements) inside parentheses (), separated by commas.
[ ]: my_tuple = (1, 2, 3, 4, 5)
print(my_tuple)
Heterogeneous Elements: Like lists, a tuple can also contain elements of different types: integers,
floats, strings, and even other tuples or lists.
Indexing and Slicing: Tuples also support indexing and slicing, like lists, but you cannot modify
their elements.
1
(2, 3)
———————————————————————————–
Dictionaries
Definition: A dictionary in Python is an unordered collection of items. Each item stored in a
dictionary has a key and value, making it a key-value pair.
Mutable: Dictionaries are mutable, which means you can change their elements. You can add,
modify, or delete key-value pairs from a dictionary.
Creation: A dictionary is created by placing items (key-value pairs) inside curly braces {}, separated
by commas. Each item is a pair made up of a key and a value, separated by a colon :.
8
[72]: my_dict = {1: "Harshal", "age": 19, (1, 3): [4, 5, 3]}
print(my_dict)
{'name': 'Harshal'}
Accessing Values: You can access a value in a dictionary by providing the corresponding key inside
square brackets [].
Bhavesh
Updating Values: You can update the value for a particular key by using the assignment operator
=.
my_dict["age"] = 20
9
To determine the type of a variable, you can use the type() function:
[78]: x = 10
print(type(x))
<class 'int'>
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[79], line 4
1 # Incorrect use of data types
2
3 # Trying to add a string and an integer
----> 4 result1 = "5" + 3 # Error: must be str, not int
6 # Trying to access a non-existing index of a list
7 my_list = [1, 2, 3]
# Tuples are immutable, create a new one if you need to change a value
10
my_tuple = (1, 4, 3)
53 3 (1, 4, 3) None
# Usually your terminal or console where you are running the program.
11
[ ]: python my_script.py > output.txt
#python my_script.py: Runs the Python script my_script.py.
#>: Redirects the output (stdout) to a specified file.
#output.txt: The file where the output will be saved. If the file doesn’t␣
↪already exist,
[84]: Maths = 90
English = 85
print("Your marks in Maths:", Maths, "and in English:", English)
[85]: Maths = 90
English = 85
12
difference = num1 - num2
product = num1 * num2
9 Operators
Various Operators in Python are:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Arithmetic Operators: Used to perform mathematical operations.
[88]: a = 10
b = 3
13
print(a ** b) # Exponent, Output: 1000
13
7
30
3.3333333333333335
3
1
1000
Assignment Operators: Used to assign values to variables.
a = 10 # Assigns value 10 to a print(a)
a += 5 # Same as a = a + 5, Output: 15 print(a)
a -= 3 # Same as a = a - 3, Output: 12 print(a)
a = 2 # Same as a = a 2, Output: 24 print(a)
a /= 6 # Same as a = a / 6, Output: 4.0 print(a)
Comparison Operators: Used to compare two values.
[89]: a = 10
b = 20
False
True
False
True
False
True
Logical Operators: Used to combine conditional statements.
[90]: a = True
b = False
False
True
False
14
Bitwise Operators: Used to perform bitwise calculations on integers.
AND Operator &: Compares each bit of the first operand with the corresponding bit of the second
operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the result bit is set
to 0.
0
OR Operator |: Compares each bit of the first operand with the corresponding bit of the second
operand. If either bit is 1, the corresponding result bit is set to 1. Otherwise, the result bit is set
to 0.
14
NOT Operator ~: Inverts all the bits of the operand. Every 0 is changed to 1, and every 1 is
changed to 0.
-11
XOR Operator ^: Compares each bit of the first operand with the corresponding bit of the second
operand. If one of the bits is 1 (but not both), the corresponding result bit is set to 1. Otherwise,
the result bit is set to 0.
14
Right Shift Operator »: Shifts the bits of the number to the right by the number of bits specified.
Each shift to the right corresponds to dividing the number by 2.
15
Left Shift Operator «: Shifts the bits of the number to the left by the number of bits specified.
Each shift to the left corresponds to multiplying the number by 2.
40
Remember, bitwise operations are only applicable to integers.
Membership Operators: Used to test whether a value or variable is found in a sequence (string,
list, tuple, set, and dictionary).
True
True
Identity Operators: Used to compare the objects, not if they are equal, but if they are actually the
same object, with the same memory location.
[98]: a = 5
b = 5
16
num1 += num2 # equivalent to num1 = num1 + num2
print("The addition of num1 and num2 is:", num1)
[101]: age = 20
if age >= 18:
print("You are eligible to vote.")
[102]: age = 16
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
[103]: score = 85
if score >= 90:
print("Grade is A")
elif score >= 80:
print("Grade is B")
elif score >= 70:
print("Grade is C")
else:
print("Grade is D")
Grade is B
Program for using “IF” to find 2nd largest number form 3 numbers.
17
[104]: # Program to find the second-largest number from three numbers
num1 = 10
num2 = 20
num3 = 30
18