DS (1) : Introduction to Python
Related posts:
- DS (2): Python -File Handling
- DS (3) : Advanced Python Libraries
- DS(4) :Python — Data Indexing | Time series| Joins
- Data Visualization Testing
Data Structure, Data Types, Conditional statements
Get Manpreet Buttar’s stories in your inbox
Join Medium for free to get updates from this writer.
Python is a simple, readable, and versatile programming language that’s great for beginners and powerful enough for complex tasks. Its wide range of applications, supportive community, and extensive libraries make it a must-learn language for anyone interested in coding.
Data Types
Python is dynamically typed, meaning you don’t need to specify the data type explicitly when defining variables. The interpreter determines the data type based on the assigned value.
Numeric Types: int to represent integers, e.g., 42, -10, 0 and float to represents floating-point numbers with decimals, e.g., 3.14, -0.5, 2.718.
# Numeric types
num_integer = 42
num_float = 3.14Text Type: str: Represents strings of characters, e.g., “Hello, World!”, ‘Python is awesome!’.
# Text type
text_str = "Hello, Python!"Boolean Type: bool represents boolean values True or False.
# Boolean type
is_true = True
is_false = FalseSequence Types:
- list: Represents ordered, mutable collections of elements, e.g., [1, 2, 3], [‘apple’, ‘banana’, ‘cherry’].
- tuple: Represents ordered, immutable collections of elements, e.g., (1, 2, 3), (‘a’, ‘b’, ‘c’).
# List
my_list = [1, 2, 3, 4]# Tuple
my_tuple = (10, 20, 30)Set Types:
- set: Represents an unordered collection of unique elements, e.g., {1, 2, 3}, {‘apple’, ‘banana’}.
- frozenset: Represents an immutable version of set.
# Set
my_set = {1, 2, 3}Mapping Type: Dictionary is represented in key-value pairs where keys must be unique, e.g., {‘name’: ‘John’, ‘age’: 30}.
# Dictionary
my_dict = {'name': 'John', 'age': 30}TypeCasting
It is the process of changing the data type of a variable from one type to another in a programming language. Here are some of the common typecasting:
int(): Converts a variable to an integer data type.
float_num = 3.14
int_num = int(float_num) # int_num will be 3float(): Converts a variable to a floating-point data type. For example:
int_num = 42
float_num = float(int_num) # float_num will be 42.0str(): Converts a variable to a string data type. For example:
number = 42
str_number = str(number) # str_number will be '42'bool(): Converts a variable to a boolean data type. It will return
Falsefor numeric types with a value of 0 or an empty container, andTruefor non-zero and non-empty values. For example:
x = 0
y = 10
bool_x = bool(x) # bool_x will be False
bool_y = bool(y) # bool_y will be TrueKeep in mind that typecasting should be done carefully, as it may lead to data loss or unexpected behavior if the conversion is not appropriate. Python is dynamically typed, meaning data types are automatically inferred in most cases, so explicit typecasting is often not required unless you need to explicitly convert between types.
Operators
In Python, operators are symbols or special functions that perform operations on one or more operands (variables or values). Python supports various types of operators, which can be broadly categorized into the following groups:
Arithmetic Operators: Used for basic mathematical calculations.
+: Addition-: Subtraction*: Multiplication/: Division (returns a float)//: Floor Division (returns an integer)%: Modulo (remainder of division)**: Exponentiation
Comparison Operators: Used to compare two values or variables.
==: Equal to!=: Not equal to>: Greater than<: Less than>=: Greater than or equal to<=: Less than or equal to
Logical Operators: Used to combine or negate boolean values.
and: Logical AND (True if both operands are True)or: Logical OR (True if at least one operand is True)not: Logical NOT (True if the operand is False, and vice versa)
Assignment Operators: Used to assign values to variables.
=: Assigns the value on the right to the variable on the left+=: Adds the right operand to the left operand and assigns the result to the left operand (e.g.,x += 5is equivalent tox = x + 5)-=: Subtracts the right operand from the left operand and assigns the result to the left operand (e.g.,x -= 3is equivalent tox = x - 3)*=,/=,//=,%=: Similar compound assignment operators for other arithmetic operations
Bitwise Operators: Used to perform operations at the binary level.
&: Bitwise AND|: Bitwise OR^: Bitwise XOR~: Bitwise NOT (inverts the bits)<<: Left shift (shifts bits to the left)>>: Right shift (shifts bits to the right)
Identity Operators: Used to compare the memory location of two objects.
is: Returns True if both variables point to the same objectis not: Returns True if both variables point to different objects
Membership Operators: Used to check if a value exists in a sequence (e.g., string, list, tuple).
in: Returns True if the value is present in the sequencenot in: Returns True if the value is not present in the sequence
These operators play a crucial role in Python programming and allow you to perform various operations, make decisions, and manipulate data efficiently.
Conditional Statements
Conditional statements in Python are used to control the flow of a program based on certain conditions. They allow the program to make decisions and execute specific blocks of code depending on whether a condition is true or false. Python supports two main types of conditional statements: if statement and if-else statement.
if Statement:
if condition:
# Code to be executed if the condition is true
x = 10
if x > 5:
print("x is greater than 5")if-else Statement:
if condition:
# Code to be executed if the condition is true
else:
# Code to be executed if the condition is false
age = 20
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")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
score = 85
if score >= 90:
print("Excellent!")
elif score >= 80:
print("Good job!")
else:
print("Keep practicing.")while Loop:
while condition:
# Code to be executed repeatedly while the condition is true
count = 0
while count < 5:
print(count)
count += 1for Loop:
for item in sequence:
# Code to be executed for each item in the sequence
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)apple
banana
cherryJump statements
- break: The
breakstatement is used to exit the nearest enclosing loop (for loop, while loop) when a certain condition is met. It terminates the loop abruptly and continues with the next statement after the loop. - continue: The
continuestatement is used to skip the current iteration of a loop and move to the next iteration without executing the remaining code in the loop's block. - pass: The
passstatement is used as a placeholder when you want to have a syntactically correct empty block. It does nothing and is commonly used as a temporary placeholder while developing code.
Manipulations
List Manipulation: (ordered collection of data)
# Creating a list
my_list = [1, 2, 3, 4, 5]
# Accessing elements
print(my_list[0]) # Output: 1
# Modifying elements
my_list[2] = 10 # [1, 2, 10, 4, 5]
# Appending and extending
my_list.append(6) # [1, 2, 10, 4, 5, 6]
my_list.extend([7, 8, 9]) # [1, 2, 10, 4, 5, 6, 7, 8, 9]
# Removing elements
my_list.remove(4) # [1, 2, 10, 5, 6, 7, 8, 9]
Del my_list[3] # will remove data at index 3
pop # Will pop last value from list
# Slicing
my_list[1:3] # 2,3 - Will give all values from 1 to 2 index
mylist [::2] # it will give step size of 2, list elements with step size 2
# Search for index
Mylist.index(3) // it will give index for value 3
# Data Insertion
Mylist.insert(4,”python”) //will insert at index 4
# Other
Len(list) # will give num of elements in list
Sorted(list) # will sort the list asc to dec
Sorted(list, reverse = true) # sort desc Tuple Manipulation: (immutable collection of data)
# Creating a tuple
my_tuple = (10, 20, 30)
# Accessing elements
print(my_tuple[1]) # Output: 20Set Manipulation: (unordered, unindexed collection of data)
# Creating a set
my_set = {1, 2, 3, 4, 5}
# Adding and removing elements
my_set.add(6) # {1, 2, 3, 4, 5, 6}
my_set.remove(3) # {1, 2, 4, 5, 6}
my_set.discard(value) #to remove value
# Unlike remove using discard will not throw error if elemet is notpresent
Set2.intersection(set1) # to give common
Set2.union(set1) # give all the data
Set1.update(3,4,5) # Will add new values
Isdisjoint – if both are unique, nothing common
Issubset
Issuperset Dictionary Manipulation: (collection of data in key value pairs)
# Creating a dictionary
my_dict = {"name": "John", "age": 30, "city": "New York"}
# Accessing elements
print(my_dict["name"]) # Output: John
# Modifying and adding elements
my_dict["age"] = 35 # {"name": "John", "age": 35, "city": "New York"}
my_dict["occupation"] = "Engineer" # {"name": "John", "age": 35, "city": "New York", "occupation": "Engineer"}
my_dict[‘M6’]=[11,23] //to add new value pair to dict
my_dict.update({‘M4’: [22,34]})
Del my_dict[key] String Manipulation:
# Concatenating strings
str1 = "Hello"
str2 = "Python"
str3 = str1 + " " + str2 # "Hello Python"
# String slicing
substring = result[0:5] # "Hello"
str3.upper() # will change to upper case
str3.lower() # will change to lowercase
str3.split() # will split string at white space
str3.split(o) # will split string at oHere is an example on 3d list manipulations:
https://github.com/ManpreetKButtar/Basic_Python/blob/main/ListManipulationStudentQuery.ipynb








