Basic building blocks of Python

1. Identifiers and Keywords

IDENTIFIERS

An identifier is a name given to entities like class, functions, methods, variables, etc. It helps to differentiate one entity from another.

Rules for writing identifiers

  1. Identifiers can be a combination of:

    1. Lowercase (a to z)

    2. Uppercase (A to Z)

    3. Digits (0 to 9)

    4. An underscore_

      Examples: myClass, var_1, print_this_to_screen.

  2. An identifier cannot start with a digit:

    Example: 1variable is invalid, but variable1 is a valid

  3. Keywords cannot be used as identifiers

  4. We cannot use special symbols like !, @, #, $, % etc. in our identifier

  5. An identifier can be of any length.

In [1]:
myClass=1
1variable=10
  File "<ipython-input-1-ba1c4b0834e0>", line 2
    1variable=10
     ^
SyntaxError: invalid syntax
In [2]:
True=10
  File "<ipython-input-2-f9c1faaf4ad0>", line 1
    True=10
    ^
SyntaxError: cannot assign to True
In [3]:
variable$=10
  File "<ipython-input-3-b9e535e96a7b>", line 1
    variable$=10
            ^
SyntaxError: invalid syntax
### Things to Remember 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, but writing count = 10 would make more sense, and it would be easier to figure out what it represents anyone look at the code. Multiple words can be used as an identifier with the help of an underscore, like this_is_a_long_variable.
In [4]:
variable=10
Variable=100
print(variable)
print(Variable)
10
100

KEYWORDS

Python Keywords: Keywords are the reserved words in Python.

  1. 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.
  2. There are 35 keywords in Python 3.7. This number can vary slightly over the course of time.
  3. In Python, keywords are case sensitive.
  4. All the keywords except True, False and None are in lowercase and they must be written as they are. The list of all the keywords is given below.
True False None import class
if else elif for while
try except finally raise return
break continue pass def lambda
from with is in not
as and or del yield
await asert async global nonlocal

2. Integral Types

Python interprets a sequence of decimal digits without any prefix to be a decimal number.

Prefix Interpretation Base
0b (zero + lowercase letter 'b') Binary 2
0B (zero + lowercase letter 'B') Binary 2
0o (zero + lowercase letter 'o') Octal 8
0O (zero + lowercase letter 'O') Octal 8
0x (zero + lowercase letter 'x') Hexadecimal 16
0X (zero + lowercase letter 'X') Hexadecimal 16

3. Floating point types

The float type in Python designates a floating-point number. Float values are specified with a decimal point.

Optionally, the character e or E followed by a positive or negative integer may be appended to specify scientific notation:

4. Complex Numbers

Complex numbers are specified as: real part + (imaginary part) j

Example: 2+3j

5. Strings

Strings are sequences of character data.

  1. ‘within single quotes’
  2. “within double quotes”

A string in Python can contain as many characters as we wish. The only limit is our machine’s memory resources. A string can also be empty:

Use the escape \ sequence if you want to include a quote character as part of the string itself.

In [5]:
print('It\'s my life')  
It's my life
In [6]:
print("The \"Honey Cake\" is delicious") 
The "Honey Cake" is delicious
The following codes will generate __SyntaxError: invalid syntax__ because the second quote symbol (after the letter 't', after the word 'The') will be considered as the closing quote for the first quote symbol.
In [7]:
print('It's my life')
  File "<ipython-input-7-1a27a8aa3045>", line 1
    print('It's my life')
              ^
SyntaxError: invalid syntax
In [8]:
print("The "Honey Cake" is delicious") 
  File "<ipython-input-8-bab003f9ebc8>", line 1
    print("The "Honey Cake" is delicious")
                ^
SyntaxError: invalid syntax
#### Using an escape '\\' sequence to type a sentance in multiple lines which will be considered as a single line
In [9]:
print('a \
is an \
alphabet')
a is an alphabet
#### Using an escape sequence '\n' to go the next line
In [10]:
print('First Line\nSecond Line\nThird Line')
First Line
Second Line
Third Line
In [11]:
print('hello')
print("Hello")
hello
Hello
In [12]:
a=10
b=20
print(a)
print(b)
10
20
In [13]:
a,b=b,a
print(a)
print(b)
20
10
In [14]:
sum=a+b
print(sum)
30
In [15]:
a = 20
b = 10
c = 15
d = 5
In [16]:
e = (a + b) * c / d       #( 30 * 15 ) / 5 = 90
print ("Value of (a + b) * c / d is ",  e)

e = ((a + b) * c) / d     # (30 * 15 ) / 5=90
print ("Value of ((a + b) * c) / d is ",  e)

e = (a + b) * (c / d);    # ________=__
print("Value of (a + b) * (c / d) is ",  e)

e = a + (b * c) / d;      #  ______=__
print ("Value of a + (b * c) / d is ",  e)
Value of (a + b) * c / d is  90.0
Value of ((a + b) * c) / d is  90.0
Value of (a + b) * (c / d) is  90.0
Value of a + (b * c) / d is  50.0

6. Decision Making

if, if else, if-elif-else, Nested if statements are used whenever we want to make a decision based on some conditions. The syntax for decision making is, the line ends with : either after else or after the condition is mentioned in the if block. The segment of code which needs to be executed as part of the decision is written with indentation.

if statements

If the condition given in if block are true then, first only the code written with indentation are executed and then the remaining code will execute. If the condition is false then the code written in if block is skipped and remaining code will be executed.

__Syntax:__ if condition : statement 1 statement 2
In [17]:
a=20
if(a>10):
    print('Inside if block')
    print('a is bigger than 10')
print('After if statement')
Inside if block
a is bigger than 10
After if statement

if else statements

if...else statements are used when we want to make any one decision out of two based on some condition. If the condition is true the code in the if block will be executed. If the condition is false then else block will be executed. Once, any one of the code block (either if or else) is executed, the remaining code wil be executed.

__Syntax:__ if condition : statement 1 statement 2 else : statement 3 statement 4
In [18]:
a = 20
b = 33
if b > a:
    print('Inside if block')
    print("b is greater than a")
else:
    print('Inside else block')
    print("b is not greater than a")

print('Outside if else block')
Inside if block
b is greater than a
Outside if else block
In [19]:
a = 20
b = 33
if a > b :
    print('Inside if block')
    print("b is greater than a")
else:
    print('Inside else block')
    print("a is not greater than b")

print('Outside if else block')
Inside else block
a is not greater than b
Outside if else block

if elif else statements

if else statements are used when we need to check two conditions but if there are multiple conditions which needs to be checked then we use if elif statements. Here, else block is optional. else block will be executed if none of the if conditions are true.

__Syntax:__ if condition 1 : statement 1 statement 2 elif condition 2 : statement 3 statement 4 elif condition 3 : statement 5 statement 6 .... .... .... else : statement 3 statement 4
In [20]:
percentage=55
if percentage > 70:
    print("Distinction")
elif ( percentage > 60 and percentage < 70 ) :
    print("First class")
elif ( percentage > 50 and percentage < 60 ) :
    print("Second class")
elif ( percentage > 35 and percentage < 50 ) :
    print("Pass class")
else:
    print("Fail")

print('Outside if elif statements')
Second class
Outside if elif statements
In [21]:
a = 200
b = 200
if b > a:
    print("b is greater than a")
elif a == b:
    print("a and b are equal")
else:
    print("a is greater than b")
a and b are equal

nested if

Python supports nested structures. Which means we can have if statement inside another if statement.

__Syntax :__ if condition 1 : statement 1 statement 2 if condition 2 : statement 3 else: statement 4 else: statement 5
In [22]:
x =40
if x > 10:
    print('inside outer if statement')
    print("Above ten,")
    if x > 20:
        print("and also above 20!")
        print('Inside if block of inner if statement')
    else:
        print("but not above 20.")
        print('Inside else block of inner if statement')
else:
    print('a is less than 10')
    
print('outside if statement')  
inside outer if statement
Above ten,
and also above 20!
Inside if block of inner if statement
outside if statement
In [23]:
x =5
if x > 10:
    print('inside outer if statement')
    print("Above ten,")
    if x > 20:
        print("and also above 20!")
        print('Inside if block of inner if statement')
    else:
        print("but not above 20.")
        print('Inside else block of inner if statement')
else:
    print('a is less than 10')
    
print('outside if statement')   
a is less than 10
outside if statement

7. Loops in python

If there is any need to execute a set of instructions several times as long as certain condition is true, we use looping structures such as for loops, while loops, and nested loops.

for loops

It has the ability to iterate over the items of any sequence, such as a list or a string.

for iterating_var in sequence: statements(s)
In [24]:
for i in 'Hello World':
    print(i)
H
e
l
l
o
 
W
o
r
l
d
In [25]:
for i in (10,20,30,40,50):
    print(i)
10
20
30
40
50
In [26]:
for n in range(0,10):
    print(n)
0
1
2
3
4
5
6
7
8
9
In [27]:
language=['C','C++','Java','Python']

for index in language:
    print(index)
C
C++
Java
Python
In [28]:
language=['C','C++','Java','Python']

for index in range(len(language)):
    print(language[index])
C
C++
Java
Python
In [29]:
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]

for x in adj:
    for y in fruits:
        print(x, y)
red apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherry

while loop

While loop is executed as long as the condition is true.

__Syntax :__ while condition : statement 1 statement 2 ...........
In [30]:
n=1
while n<10:
    print(n)
    n=n+1
1
2
3
4
5
6
7
8
9

range( )

range ( ) is a built-in function of Python. It is used when a user needs to perform an action for a specific number of times

__Syntax__ range(start, stop, step) Here start and step are optional. 0 will be considered as start value and 1 as the step value in case if they are not provided by the programmer.
In [31]:
numbers = range(5)
for n in numbers:
    print(n)
0
1
2
3
4
In [32]:
numbers = range(2,5)
for n in numbers:
    print(n)
2
3
4
In [33]:
numbers = range(1,5,2)
for n in numbers:
    print(n)
1
3

8. Control Statements

break

break is used to control the sequence of the loop. If we want to terminate a loop and skip to the next code after the loop then we use break statement. And if we want to continue in the loop in such case we use continue statement

pass statement are null statements which are ignored by the compilers. Usually we use pass statements as placeholder.

In [34]:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
    if x == "banana":
        break
    print(x)
apple
In [35]:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
    if x == "banana":
        continue
    print(x)
apple
cherry
In [36]:
for x in [0, 1, 2]:
    pass

else block in for loop

In [37]:
for x in range(6):
    print(x)
else:
    print("Finally finished!")
0
1
2
3
4
5
Finally finished!
In [38]:
#### Note: The else block will NOT be executed if the loop is stopped by a break statement.
for x in range(6):
    if x == 3: 
        break
    print(x)
else:
    print("Finally finished!")
0
1
2
In [39]:
x = 'print(55)'
eval(x)
55