DEV Community

Rajasekaran Palraj
Rajasekaran Palraj

Posted on

Data Analytics Week 2 Notes

Python

Programming Language Types

  • Low-level Language

    • OS development
    • Embedded system
    • Device drivers
  • High-level Language

Ways of high-level Language Execution

  • Compiler
    • C, C++, java
  • Interpreter
    • Execute line by line Python, perl, metlab

Programming Language Components

  • Data types
  • Variables
  • Operators
  • Control Structurs
  • Libraries

Python Features

  • Simple and Readable
  • Run seamlessly on all operating Systems
  • Data Science, Automation and AI
  • Libray support
  • Used by big companies like google , Netflix, Nasa

Data Types:

*1. Numeric Data Types *

  • Integers - This value is represented by int class. It contains positive or negative whole numbers (without fractions or decimals). In Python, there is no limit to how long an integer value can be.
  • Float - This value is represented by the float class. It is a real number with a floating-point representation. It is specified by a decimal point. Optionally, the character e or E followed by a positive or negative integer may be appended to specify scientific notation.
  • Complex Numbers - A complex number is represented by a complex class. It is specified as (real part) + (imaginary part)j . For example - 2+3j

2. Sequence Data Types

  • String - arrays of bytes representing Unicode characters
  • List - ordered collection of data with similar or different data type (Mutable)
  • Tuple - ordered collection of data with similar or different data type (ImMutable)

3. Boolean Data Type
Python Data type with one of the two built-in values

  • True
  • False

4. Set Data Type
It is an unordered collection of data types that is iterable, mutable, and has no duplicate elements.

*5. Dictionary Data *
A dictionary in Python is a collection of data values, used to store data values like a map, unlike other Python Data Types that hold only a single value as an element, a Dictionary holds a key: value pair. Key-value is provided in the dictionary to make it more optimized.

Operators

Operators Type
+, -, *, /, % Arithmetic operator
<, <=, >, >=, ==, != Relational operator
AND, OR, NOT Logical operator
&, , <<, >>, ~, ^
=, +=, -=, *=, %= Assignment operator

Flow Control Statements:

  • Conditional Statements (if, elif, else, Match case)
  • Looping Statements (for, while)
  • Loop Control Statements (break, continue, pass)
  • Exception Handling

Conditional statements
IF
`age = 20

if age >= 18:
print("Eligible to vote.")`

ELIF and Else
`age = 25

if age <= 12:
print("Child.")
elif age <= 19:
print("Teenager.")
elif age <= 35:
print("Young adult.")
else:
print("Adult.")`

Nested IF

`age = 70
is_member = True

if age >= 60:
if is_member:
print("30% senior discount!")
else:
print("20% senior discount.")
else:
print("Not eligible for a senior discount.")`

Ternary Conditional Statement in Python
A ternary conditional statement is a compact way to write an if-else condition in a single line. It’s sometimes called a "conditional expression."

`# Assign a value based on a condition
age = 20
s = "Adult" if age >= 18 else "Minor"

print(s)`

Match-Case Statement in Python
match-case statement is Python's version of a switch-case found in other languages. It allows us to match a variable's value against a set of patterns.

`number = 2

match number:
case 1:
print("One")
case 2 | 3:
print("Two or Three")
case _:
print("Other number")`

For Loop

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

for i in range(5):
print(i)

While Loop
The while loop is used to repeatedly execute a block of code as long as a specified condition is true.

count = 0
while count < 5:
print(count)
count += 1

Nested Loops
Loops can be nested within one another to perform more complex iterations. For example, a for loop can be nested inside another for loop to create a two-dimensional iteration.

Python For Loop with String
This code uses a for loop to iterate over a string and print each character on a new line. The loop assigns each character to the variable i and continues until all characters in the string have been processed.

s = "Rajasekaran"
for i in s:
print(i)

Using range() with For Loop
The range() function is commonly used with for loops to generate a sequence of numbers. It can take one, two, or three arguments:

range(stop): Generates numbers from 0 to stop-1.
range(start, stop): Generates numbers from start to stop-1.
range(start, stop, step): Generates numbers from start to stop-1, incrementing by step.

for i in range(0, 10, 2):
print(i)

Output

0
2
4
6
8

List

a list is a built-in dynamic sized array (automatically grows and shrinks). We can store all types of items (including another list) in a list. A list may contain mixed type of items, this is possible because a list mainly stores references at contiguous locations and actual items maybe stored at different locations.

  • List can contain duplicate items.
  • List in Python are Mutable. Hence, we can modify, replace or delete the items.
  • List are ordered. It maintain the order of elements based on how they are added.
  • Accessing items in List can be done directly using their position (index), starting from 0

`# Creating a Python list with different data types
a = [10, 20, "GfG", 40, True]
print(a)

Accessing elements using indexing

print(a[0]) # 10
print(a[1]) # 20
print(a[2]) # "GfG"
print(a[3]) # 40
print(a[4]) # True

Checking types of elements

print(type(a[2])) # str
print(type(a[4])) # bool`

Create List:
`# List of integers
a = [1, 2, 3, 4, 5]

List of strings

b = ['apple', 'banana', 'cherry']

Mixed data types

c = [1, 'hello', 3.14, True]

print(a)
print(b)
print(c)`

Adding Elements into List
We can add elements to a list using the following methods:

append(): Adds an element at the end of the list.
extend(): Adds multiple elements to the end of the list.
insert(): Adds an element at a specific position.

# Initialize an empty list
a = []

# Adding 10 to end of list
a.append(10)  
print("After append(10):", a)  

# Inserting 5 at index 0
a.insert(0, 5)
print("After insert(0, 5):", a) 

# Adding multiple elements  [15, 20, 25] at the end
a.extend([15, 20, 25])  
print("After extend([15, 20, 25]):", a)
Enter fullscreen mode Exit fullscreen mode

Updating Elements into List
We can change the value of an element by accessing it using its index.

`a = [10, 20, 30, 40, 50]

Change the second element

a[1] = 25
print(a)`

Removing Elements from List
We can remove elements from a list using:

remove(): Removes the first occurrence of an element.
pop(): Removes the element at a specific index or the last element if no index is specified.
del statement: Deletes an element at a specified index.

`a = [10, 20, 30, 40, 50]

Removes the first occurrence of 30

a.remove(30)

print("After remove(30):", a)

Removes the element at index 1 (20)

popped_val = a.pop(1)

print("Popped element:", popped_val)
print("After pop(1):", a)

Deletes the first element (10)

del a[0]

print("After del a[0]:", a)`

Iterating Over Lists
We can iterate the Lists easily by using a for loop or other iteration methods. Iterating over lists is useful when we want to do some operation on each item or access specific items based on certain conditions. Let's take an example to iterate over the list using for loop.

`a = ['apple', 'banana', 'cherry']

Iterating over the list

for item in a:
print(item)`

Nested Lists in Python
A nested list is a list within another list, which is useful for representing matrices or tables. We can access nested elements by chaining indexes.

`matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]

Access element at row 2, column 3

print(matrix[1][2])`

output

6

List Slicing
Python list slicing is fundamental concept that let us easily access specific elements in a list

`a = [1, 2, 3, 4, 5, 6, 7, 8, 9]

Get elements from index 1 to 4 (excluded)

print(a[1:4])`

output

[2, 3, 4]

Python List Slicing Syntax
list_name[start : end : step]

Parameters:

start (optional): Index to begin the slice (inclusive). Defaults to 0 if omitted.
end (optional): Index to end the slice (exclusive). Defaults to the length of list if omitted.
step (optional): Step size, specifying the interval between elements. Defaults to 1 if omitted

`a = [1, 2, 3, 4, 5, 6, 7, 8, 9]

Get all elements in the list

print(a[::])
print(a[:])`

Dictionaries

Python dictionary is a data structure that stores the value in key: value pairs. Values in a dictionary can be of any data type and can be duplicated, whereas keys can't be repeated and must be immutable.

d = {1: 'Raj', 2: 'Ram', 3: 'Rani'}

Adding and Updating Dictionary Items
We can add new key-value pairs or update existing keys by using assignment.

`d = {1: 'Raj', 2: 'Ram', 3: 'Rani'}

Adding a new key-value pair

d["age"] = 32

Updating an existing value

d[1] = "Sekar"

print(d)`

Output

{1: 'Sekar', 2: 'Ram', 3: 'Rani', 'age': 32}

Removing Dictionary Items
We can remove items from dictionary using the following methods:

del: Removes an item by key.
pop(): Removes an item by key and returns its value.
clear(): Empties the dictionary.
popitem(): Removes and returns the last key-value pair.

d = {1: 'Raj', 2: 'Ram', 3: 'Sekar', 'age':22}

# Using del to remove an item
del d["age"]
print(d)

# Using pop() to remove an item and return the value
val = d.pop(1)
print(val)

# Using popitem to removes and returns
# the last key-value pair.
key, val = d.popitem()
print(f"Key: {key}, Value: {val}")

# Clear all items from the dictionary
d.clear()
print(d)
Enter fullscreen mode Exit fullscreen mode

Nested Dictionaries

Example of Nested Dictionary:

Nested Dictionaries

d = {1: 'Raj', 2: 'Sekaran',
3: {'A': '1', 'B': 'To', 'C': '3'}}

print(d)Nested Dictionaries

Top comments (0)