Quick Revision of Basic Python (Part-1)

Jinendrasingh
7 min readMay 4, 2023

--

I have been learning Python for the past 7 months through continuous classes. However, I found myself struggling to retain what I had learned from previous classes whenever I attended a new one. As a solution, I decided to write short notes that cover the basics of Python and other topics that I have covered so far. My main goal is to use these notes for revision, especially during interviews for data science positions. I am focusing on learning Python specifically for data science, and I hope that these notes will be useful in achieving that goal. Let’s Start: Day 1 (Intro to Python)

Python

Python is a high-level, interpreted programming language that emphasizes code readability, simplicity, and ease of use.

It supports multiple programming paradigms including procedural, object-oriented, and functional programming.

Python is used for a wide range of applications, including web development, data analysis, artificial intelligence, machine learning, and scientific computing.

Procedural programming is a programming paradigm that involves writing a list of instructions or procedures for the computer to execute in a specific order.

Functional programming is a programming paradigm that focuses on using functions to create software.

Object-oriented programming is a programming paradigm that involves modeling real-world objects as software objects.

Data Types in Python

# Integer
print(8)
print(1e309)

# Decimal/Float
print(8.55)
print(1.7e309)

# Boolean
print(True)
print(False)

# Text/String
print('Hello World')

# complex
print(5+6j)

# List-> C-> Array
print([1,2,3,4,5])

# Tuple
print((1,2,3,4,5))

# Sets
print({1,2,3,4,5})

# Dictionary
print({'name':'Nitish','gender':'Male','weight':70})

# type
type([1,2,3])

Variables

A variable is a name that represents a value stored in the computer’s memory. Variables in Python are dynamically typed, which means that the type of data they can hold can change during the execution of a program. For example, a variable that holds an integer value can be reassigned to hold a string value later on in the program.

# Dynamic Typing (Data type automatically detect)
a = 5
# Static Typing (Data type need to define)
int a = 5

# Dynamic Binding (A single veriable can hold different datatype in a program)
# Means it can be change within the program
a = 5
print(a)
a = 'nitish'
print(a)

# Static Binding (A single veriable can only hold sinfle datatype in a program)
int a = 5

#Assignment
a,b,c = 1,2,3
print(a,b,c)
output-> 1 2 3

a=b=c= 5
print(a,b,c)
output-> 5 5 5

Comments

# this is a comment
# second line
a = 4
b = 6 # like this
# second comment
print(a+b)

Keywords & Identifiers

Keywords are reserved words in Python that have special meanings and cannot be used as variable names or identifiers.

Identifiers, on the other hand, are names given to variables, functions, classes, and other objects in Python.

User Input

input("Email")

Output
Enter Emailnitish@gmail.com
'nitish@gmail.com'

# take input from users and store them in a variable
fnum = int(input('enter first number'))
snum = int(input('enter second number'))
#print(type(fnum),type(snum))
# add the 2 variables
result = fnum + snum
# print the result
print(result)
print(type(fnum))

Output
enter first number56
enter second number67
123
<class 'int'>

Type Conversion

Type conversion, also known as type casting, is the process of converting a value from one data type to another in a programming language.

# Implicit 
print(5+5.6)
print(type(5),type(5.6))

output:
10.6
<class 'int'> <class 'float'>

# Explicit
# str -> int
int('4')
output: 4

# int to str
str(5)
output: '5'

# float
float(4)
output: 4.0

Literals

In programming, a literal is a value that is written directly into the code of a program, rather than being computed or generated at runtime.

a = 0b1010 #Binary Literals
b = 100 #Decimal Literal
c = 0o310 #Octal Literal
d = 0x12c #Hexadecimal Literal

#Float Literal
float_1 = 10.5
float_2 = 1.5e2 # 1.5 * 10^2
float_3 = 1.5e-3 # 1.5 * 10^-3

#Complex Literal
x = 3.14j

print(a, b, c, d)
print(float_1, float_2,float_3)
print(x, x.imag, x.real)

Output:
10 100 200 300
10.5 150.0 0.0015
3.14j 3.14 0.0

# binary
x = 3.14j
print(x.imag) #imag will print imagnary value
Output:
3.14

string = 'This is Python'
strings = "This is Python"
char = "C"
multiline_str = """This is a multiline string with more than one line code."""
unicode = u"\U0001f600\U0001F606\U0001F923"
raw_str = r"raw \n string"

print(string)
print(strings)
print(char)
print(multiline_str)
print(unicode)
print(raw_str)

Output:
This is Python
This is Python
C
This is a multiline string with more than one line code.
😀😆🤣
raw \n string


a = True + 4 #True = 1
b = False + 10 #False = 0

print("a:", a)
print("b:", b)

Output:
a: 5
b: 10

Operators

Operators in Python are symbols or keywords that represent operations that can be performed on values or variables. Python supports a variety of operators, including:

# Arithmetric Operators
print(5+6) --> 11
print(5-6) --> -1
print(5*6) --> 30
print(5/2) --> 2
print(5//2) --> 1
print(5%2) --> 1
print(5**2) --> 25

# Relational Operators
print(4>5) --> False
print(4<5) --> True
print(4>=4) --> True
print(4<=4) --> True
print(4==4) --> True
print(4!=4) --> False

# Logical Operators
print(1 and 0) --> 0
print(1 or 0) --> 1
print(not 1) --> False

# Bitwise Operators

# bitwise and
print(2 & 3) --> 2
# bitwise or
print(2 | 3) --> 3

# bitwise xor
print(2 ^ 3) --> 1
print(~3) --> -4
print(4 >> 2) --> 1
print(5 << 2) --> 20

# Assignment Operators
a = 2
a %= 2
print(a) --> 4

# Membership Operators
# in/not in
print('D' not in 'Delhi') --> False
print(1 in [2,3,4,5,6]) --> False

Example on Operators

# Program - Find the sum of a 3 digit number entered by the user

number = int(input("Enter the 3 digit number"))

# 345%10 -> 5
a = number%10
number = number//10

# 34%10 -> 4
b = number%10
number = number//10

# 3 % 10 -> 3
c = number%10
number = number//10

print(a+b+c) --> 12

If-else in Python

In Python, if-else is a control statement that allows you to execute different blocks of code based on a condition. The basic syntax of the if-else the statement is:

#Basic if-else statement

if condition:
# code to be executed if condition is True
else:
# code to be executed if condition is False


#if-elif-else statement
if condition1:
# code to be executed if condition1 is True
elif condition2:
# code to be executed if condition2 is True
else:
# code to be executed if all conditions are False


#Nested if-else statement
if condition1:
# code to be executed if condition1 is True
if condition2:
# code to be executed if condition1 and condition2 are True
else:
# code to be executed if condition1 is True and condition2 is False
else:
# code to be executed if condition1 is False


#Ternary operator
value_if_true if condition else value_if_false

Example
x = 5
y = 10
max_value = x if x > y else y --> 10

Basic Module in Python

In Python, a module is a file that contains a collection of related functions, classes, and variables that can be used in other Python programs.

Some inbuilt Modules are given below:

#math
import math
math.sqrt(196) --> 14.0

#keyword
import keyword
print(keyword.kwlist)

# random
import random
print(random.randint(1,100))

# datetime
import datetime
print(datetime.datetime.now())

help('modules') #To check all the inbuilt module

Loops

In Python, loops are used to execute a set of instructions repeatedly. There are two types of loops in Python: for loop and while loop.

For loop

A for loop is used to iterate over a sequence (e.g. a list, tuple, or string) and execute a block of code for each item in the sequence.

#Syntex
for item in sequence:
# code block

----------------------------------------------------

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)

Output -->
apple
banana
cherry

While loop

A while loop is used to execute a block of code repeatedly as long as a certain condition is true.

#Syntex
while condition:
# code block
---------------------------------------------

i = 1
while i <= 5:
print(i)
i += 1

Output:
1
2
3
4
5

Example:-

"""Program - The current population of a town is 10000. 
The population of the town is increasing at the rate of 10% per year.
You have to write a program to find out the population at the
end of each of the last 10 years."""

Curr_Pop = 10000

for i in range(10,0,-1):
print(i, Curr_Pop)
Curr_Pop = 1.1

"""Problem - 1/1! + 2/2! + 3/3! + ... Find Sequence Sum """

n = int(input("Enter the value of n"))

fact = 1
result = 0

for i in range(1+n):
fact = fact * i
result = result + i/fact

print(result)

"""Pettern Problem 1"""
for i in range(5):
for j in range(i):
print('*', end='')
print('')

*
**
***
****

"""Pettern Problem 2"""
for i in range(1, 5):
for j in range(1, i+1):
print(j, end='')
for k in range(i-1,0,-1):
print(k, end='')
print('')

1
121
12321
1234321

Loop Control Statement

In Python, there are three types of loop control statements: break, continue, and pass.

Break: The break statement is used to terminate a loop prematurely.

for i in range(1, 6):
if i == 3:
break
print(i)

output:
1
2

Continue: The continue statement is used to skip the current iteration of a loop and move on to the next one.

for i in range(1, 6):
if i == 3:
continue
print(i)

output:
1
2
4
5

Pass: The pass statement is used as a placeholder when you need to write a block of code that does nothing.

for i in range(1, 6):
pass

In this example, the loop simply executes five times without doing anything.

--

--

Jinendrasingh
Jinendrasingh

Written by Jinendrasingh

An Aspiring Data Analyst and Computer Science grad. Sharing insights and tips on data analysis through my blog. Join me on my journey!

No responses yet