Python Notes Start From Keywords
Python Notes Start From Keywords
Python Keywords
We cannot use a keyword as a variable name, function name or any other identifier. They are
used to define the syntax and structure of the Python language.
In Python, keywords are case sensitive.
Built – in Functions:
Python has several functions readily available for use once you install python on your PC. These
functions are called built-in functions.
There are numerous ways to identify these keywords. Some of them are:
1. Syntax Highlighting in IDEs:
Most of the good python friendly IDEs usually highlight keywords while writing codes. Hence
easily identifiable. E.g. Spyder, PyCharm, Vim, Visual Studio Code, etc.
Python comes installed with its interpreter, the interactive Read-Eval-Print Loop (REPL)
environment. Here you can obtain the keywords with the following command:
>>> help("keywords")
Here is a list of the Python keywords. Enter any keyword to get more help.
3. Python Libraries:
You can use libraries like kwlist, to get a list of keywords supported by the current version of
python you are running the code on.
4. iskeyword() function:
This function is part of the keyword package and is used to check if a term is a python keyword
or not.
>>> keyword.iskeyword("finally")
True
>>> keyword.iskeyword("hi")
False
These python keywords are used to denote values. These values are single values that can be
used multiple times and about the same object or variable. These keywords are the only
keywords that begin with a capital letter. Let's see the different types of value keywords
possessed by python:
Python Usage
Keyword
True Used for assigning the value to a variable or represents the result of a
boolean expression evaluating to true
False Used for assigning the value to a variable or represents the result of a
boolean expression evaluating to false
None Represents null, nil, none, undef, or undefined values in python
Example:
>>> 1 == 1
True
True
>>> 3 > 7
False
False
>>> None == 0
False
>>> x = None
>>> y = None
>>> x == y
True
2. Operator Keywords
Many operators are used as symbols in other languages; on the contrary, python uses keywords
for defining these operators. Their function is similar to their literal meaning, making coding in
python lucid to understand. Let’s take a look at these keywords:
Python Keyword Math Operator
and AND, Intersection(^)
or OR, Union(v)
not NOT, Negation (¬)
in CONTAINS, (∈)
is Checking Identity
Example:
True>>> True and False
False
>>> True or False
True
>>> not False
True
>>> a = 'scaler academy'
>>> 'scaler' in a
True
>>> True is True
True
3. Control Flow Keywords
These keywords help us perform conditional logic and execute code given certain conditions.
They are commonly used in forming a pipeline on how the code should perform based on
decision-making conditions and hence are essential in python. Let's see how these control flow
keywords work:
Example:
# My Calculator
a = int( input() )
b = int(input())
print ('enter operation: +, -, *, /')
opt = input()
if opt == '+':
print (a+b)
elif opt == '-':
print (a-b)
elif opt == '*':
print (a*b)
elif opt == '/':
print (a/b)
else:
print ('invalid input')
Output:
>3
>5
>enter operation: +, -, *, /
>+
>8
4. Iteration Keywords
In python programming, these keywords indicate the type of looping initiated. Synonymous with
python’s ease of usage, the function of these keywords are literally the same as what we type.
Let's see the various types of iteration keywords:
Example:
# Display numbers 5 to 10
#################################
n=5
# while loop example
while n < 11:
print(n)
n+=1
Output:
>5
>6
>7
>8
>9
>10
>5
>6
>7
>8
>9
>10
5. Structural Keywords
We use various keywords in python to define the structure of certain pieces of code. These
keywords are very often used to make code modular and understandable. Let’s take a look at
these functions and their uses:
A parameter is the variable listed inside the parentheses in the function definition
6. Return Keywords
These keywords help us give out results of functions. They are essential keywords that help us
determine with what value must exist the function. Let’s take a look at its functionalities.
7. Import Keywords
There are many useful packages and libraries in python that can be installed and used to form
your code that is not available in the installed version of python. These libraries can be used in
the codebase using the following keywords:
The following keywords are used to raise and catch exceptions in python. Let’s take a look at
these keywords and their functions:
These keywords are used to do manipulations on python variables. Let's take a look at their
functionality and syntax.
Output
a@ = 0
Output
Python is a case-sensitive language. This means, Variable and variable are not the same.
Always give the identifiers a name that makes sense. While c = 10 is a valid name, writing count
= 10 would make more sense, and it would be easier to figure out what it represents when you
look at your code after a long gap.
Multiple words can be separated using an underscore, like this_is_a_long_variable.
Python Statement, Indentation and Comments
Python Statement
Instructions that a Python interpreter can execute are called statements. For example, a = 1 is an
assignment statement. if statement, for statement, while statement, etc. are other kinds of
statements which will be discussed later.
Multi-line statement
In Python, the end of a statement is marked by a newline character. But we can make a statement
extend over multiple lines with the line continuation character (\). For example:
a=1+2+3+\
4+5+6+\
7+8+9
a = (1 + 2 + 3 +
4+5+6+
7 + 8 + 9)
Here, the surrounding parentheses ( ) do the line continuation implicitly. Same is the case
with [ ] and { }. For example:
colors = ['red',
'blue',
'green']
We can also put multiple statements in a single line using semicolons, as follows:
a = 1; b = 2; c = 3
Python Indentation
Most of the programming languages like C, C++, and Java use braces { } to define a block of
code. Python, however, uses indentation.
A code block (body of a function, loop, etc.) starts with indentation and ends with the first un-
indented line. The amount of indentation is up to you, but it must be consistent throughout that
block.
Generally, four whitespaces are used for indentation and are preferred over tabs. Here is an
example.
for i in range(1,11):
print(i)
if i == 5:
break
Run Code
The enforcement of indentation in Python makes the code look neat and clean. This results in
Python programs that look similar and consistent.
Indentation can be ignored in line continuation, but it's always a good idea to indent. It makes the
code more readable. For example:
if True:
print('Hello')
a=5
and
if True: print('Hello'); a = 5
both are valid and do the same thing, but the former style is clearer.
You might forget the key details of the program you just wrote in a month's time. So taking the
time to explain these concepts in the form of comments is always fruitful.
#This is a comment
#print out Hello
print('Hello')
Run Code
Multi-line comments
We can have comments that extend up to multiple lines. One way is to use the hash(#) symbol at
the beginning of each line. For example:
Another way of doing this is to use triple quotes, either ''' or """.
These triple quotes are generally used for multi-line strings. But they can be used as a multi-line
comment as well. Unless they are not docstrings, they do not generate any extra code.
"""This is also a
perfect example of
multi-line comments"""
Docstrings in Python
def double(num):
"""Function to double the value"""
return 2*num
Docstrings appear right after the definition of a function, class, or a module. This separates
docstrings from multiline comments using triple quotes.
The docstrings are associated with the object as their __doc__ attribute.
So, we can access the docstrings of the above function with the following lines of code:
def double(num):
"""Function to double the value"""
return 2*num
print(double.__doc__)
Run Code
Output
Python Variables
A variable is a named location used to store data in the memory. It is helpful to think of variables
as a container that holds data that can be changed later in the program. For example,
number = 10
Here, we have created a variable named number. We have assigned the value 10 to the variable.
You can think of variables as a bag to store books in it and that book can be replaced at any time.
number = 10
number = 1.1
Initially, the value of number was 10. Later, it was changed to 1.1.
Note: In Python, we don’t actually assign value to the variables. Instead, Python gives the
reference of the object(value) to the variable.
As you can see from the above example, you can use the assignment operator = to assign a value
to a variable.
Example 1: Declaring and assigning value to a variable
website = "apple.com"
print(website)
Run Code
Output
apple.com
In the above program, we assigned a value apple.com to the variable website. Then, we printed
out the value assigned to website i.e. apple.com
Note: Python is a type-inferred language, so you don't have to explicitly define the variable type.
It automatically knows that apple.com is a string and declares the website variable as a string.
Example 2: Changing the value of a variable
website = "apple.com"
print(website)
print(website)
Run Code
Output
apple.com
programiz.com
In the above program, we have assigned apple.com to the website variable initially. Then, the
value is changed to programiz.com.
a, b, c = 5, 3.2, "Hello"
print (a)
print (b)
print (c)
Run Code
If we want to assign the same value to multiple variables at once, we can do this as:
x = y = z = "same"
print (x)
print (y)
print (z)
Run Code
The second program assigns the same string to all the three variables x, y and z.
Constants
A constant is a type of variable whose value cannot be changed. It is helpful to think of constants
as containers that hold information which cannot be changed later.
You can think of constants as a bag to store some books which cannot be replaced once placed
inside the bag.
In Python, constants are usually declared and assigned in a module. Here, the module is a new
file containing variables, functions, etc which is imported to the main file. Inside the module,
constants are written in all capital letters and underscores separating the words.
Create a constant.py:
PI = 3.14
GRAVITY = 9.8
Create a main.py:
import constant
print(constant.PI)
print(constant.GRAVITY)
Output
3.14
9.8
In the above program, we create a constant.py module file. Then, we assign the constant value
to PI and GRAVITY. After that, we create a main.py file and import the constant module.
Finally, we print the constant value.
Note: In reality, we don't use constants in Python. Naming them in all capital letters is a
convention to separate them from variables, however, it does not actually prevent reassignment
2. snake_case
3. MACRO_CASE
4. camelCase
CapWords
5. Create a name that makes sense. For example, vowel makes more sense than v.
6. If you want to create a variable name having two words, use underscore to separate them. For
example:
7. my_name
current_salary
10. G
11. MASS
12. SPEED_OF_LIGHT
TEMP
Literals in Python
Literals in Python is defined as the raw data assigned to variables or constants while
programming. We mainly have five types of literals which includes string literals, numeric
literals, boolean literals, literal collections and a special literal None.
Introduction to Literals in Python
Be it a friend, family member or a cousin you’re really close to, we all need a constant in life.
Well, the same applies to programming languages like Python!
“A constant can be defined as an entity that has a fixed value or an entity whose value does not
vary.”
Well, we luckily have the concept of constants in Python as well! They are known as literals in
Python.
Python literals are quantities/ notations whose value does not change during the execution of a
program.
In this article, we will be deep-diving into what are literals in Python and the types of literal in
Python.
Literals in Python are nothing but a succinct way of representing the data types. In simpler
words, it is the way to represent a fixed value in our source code. They can either be numbers,
text, boolean or any other form of data.
Python literals are of several types, and their usage is also pretty varied. So let’s check them out
one by one.
String Literals
Numeric Literals
Boolean Literals
Literal Collections
Special Literals
And these five types again have certain subtypes, which we will discuss in-depth and see their
implementation in Python.
1. String Literals in Python
Creating a string literal in Python is really easy- enclose the text or the group of characters in
single, double or triple quotes. Using triple quotes also allows us to write multi-line strings.
Hence, we can say that there are two types of string literals in Python-
Single-line String
String literals that are enclosed within single quotes (‘’) are known as single-line strings.
#string literals
#single line literal
single_quotes_string='Scaler Academy'
double_quotes_string="Hello World"
print(single_quotes_string)
print(double_quotes_string)
We have successfully created a string using single quotes and double quotes in the above code
snippet. The output of it is-
Scaler Academy
Hello World
Multi-line String
A collection of characters or a string that goes on for multiple lines is a multi-line string.
We can enable multi-line strings in Python by adding a backslash at the end of every line.
#string literals
#multi line literal
str="Welcome\
to\
Scaler\
Academy"
print(str)
The output of this will be-
WelcometoScalerAcademy
Triple quotes at the beginning and end of the string literally will allow us to create a multi-line
string in Python easily!
#string literals
#multi line literal
str="""Welcome
to
Scaler
Academy"""
print(str)
Welcome
to
Scaler
Academy
Numerical literals in Python are those literals that contain digits only and are immutable.
They are of four types-
Integer
The numerical literals that are zero, positive or negative natural numbers and contain no decimal
points are integers.
Decimal- It contains digits from 0 to 9. The base for decimal values is 10.
Binary- It contains only two digits- 0 and 1. The base for binary values is 2 and prefixed
with “0b”.
Octal- It contains the digits from 0 to 7. The base for octal values is 8. In Python, such
values are prefixed with “0o”.
Hexadecimal- It contains digits from 0 to 9 and alphabets from A to F.
# integer literal
#positive whole numbers
x = 2586
#negative whole numbers
y = -9856
# binary literal
a = 0b10101
# decimal literal
b = 505
# octal literal
c = 0o350
# hexadecimal literal
d = 0x12b
print (x,y)
print(a, b, c, d)
2586 -9856
21 505 232 299
Float
The floating-point literals are also known as real literals. Unlike integers, these contain decimal
points.
Float literals are primarily of two types-
A. Fractional- Fractional literals contain both whole numbers and decimal points.
Example
print(78.256)
Output
78.256
B. Exponential- Exponential literals in Python are represented in the powers of 10. The power
of 10 is represented by e or E. An exponential literal has two parts- the mantissa and the
exponent.
Note:
Example
print(2.537E5)
Output
253700.0
Complex
Complex literals are represented by A+Bj. Over here, A is the real part. And the entire B part,
along with j, is the imaginary or complex part. j here represents the square root of -1, which is
nothing but the iota or i we use in Mathematics.
# complex literal
a=7 + 8j
b=5j
print(a)
print(b)
The output of the code snippet will be-
(7+8j)
5j
Long
Long literals were nothing but integers with unlimited length. From Python 2.2 and onwards, the
integers that used to overflow were automatically converted into long ints. Since Python 3.0, the
long literal has been dropped. What was the long data type in Python 2 is now the standard int
type in Python 3.
Long literals used to be represented with a suffix- l or L. The usage of L was strongly
recommended as l looked a lot like the digit 1.
Example
Note– The code snippet was executed using Python 1.8. Output
Success #stdin
Boolean literals in Python are pretty straight-forward and have only two values-
#boolean literals
x = (1 == 1)
y = (7 == False)
print("x is", x)
print("y is", y)
x is True
y is False
We can see that we used boolean literals for comparison and based on the conditions, we
received the outputs True and False, respectively.
Python literals have one special literal known as None. This literal in Python is used to signify
that a particular field is not created.
Python will print None as output when we print the variable with no value assigned to it. None is
also used for end of lists in Python.
Example
#special literals
val=None
print(val)
Output
None
If we wish to work with more than one value, then we can go for literal collections in Python.
Literal collections in Python are of four types-
List Literals
Lists are a collection of data declared using the square brackets([]), and commas separate the
elements of the list (,). This data can be of different types. Another important thing to know
about lists is that they are mutable.
# list literals
numbers = [10, 20, 30, 40, 50]
names = ['John', 'Jake', 'Jason', 25]
print(numbers)
print(names)
Output
The literals that are declared using round brackets and can hold any data type are tuples.
Commas separate the elements of tuples. However, unlike lists, tuples are immutable.
# tuple literals
even_numbers = (2, 4, 6, 8)
vowels=('a','e','i','o','u')
print(even_numbers)
print(vowels)
Output
(2, 4, 6, 8)
('a', 'e', 'i', 'o', 'u')
Dictionary Literals
Dictionary is a collection of data that stores value in a key-value format. These are enclosed in
curly brackets and separated by commas. Dictionaries are mutable and can also contain different
types of data.
Check out the below code snippet that shows how a dictionary works-
# dictionary literals
my_dict = {'a': 'apple', 'b': 'bat', 'c': 'car'}
print(my_dict)
Output
Set Literals
Set literals are a collection of unordered data that cannot be modified. It is enclosed within curly
brackets and separated by commas.
#set literals
vowels = {'a', 'e', 'i', 'o', 'u'}
print(vowels)
Output