M1 Variables Data Types I O Statements Casting and Operators
M1 Variables Data Types I O Statements Casting and Operators
1. Python
Python is a high-level, interpreted programming language known for its simplicity and readability. It was
created by Guido van Rossum and first released in 1991. Python emphasizes code readability and a clean syntax,
which makes it ideal for beginners as well as experienced programmers.
• Syntax: Many programming languages have different syntax rules and conventions. For example,
languages like C and Java use curly braces ({}) to denote code blocks, while Python uses indentation.
• Readability: Python emphasizes readability and simplicity, making it easier to write and understand code
compared to some other languages.
• Dynamic Typing: Python is dynamically typed, meaning you don't need to declare variable types explicitly.
Other languages like C++ and Java are statically typed, requiring variable types to be explicitly declared.
• Interpreted vs. Compiled: Python is an interpreted language, executing code line by line. Compiled
languages like C and C++ translate the entire code into machine language before execution.
• Development Speed: Python is known for its rapid development capabilities due to its concise syntax and
built-in data structures.
• Versatility: Python is a versatile language used in various domains such as web development, data
analysis, machine learning, and automation.
• Community and Libraries: Python has a large and active community, with a vast ecosystem of libraries
and frameworks that make it suitable for a wide range of tasks.
https://orion021.github.io/krishnan_t/ 1 | 😁 👻 ✌️ 😎
Python - Variables, Data Types, I/O Statements, Casting and Operators
• Python was created by Guido van Rossum and first released in 1991.
• Guido van Rossum aimed to create a language that was easy to read and write, with a focus on code
readability and simplicity.
• Python's name was inspired by the British comedy group Monty Python.
• The language went through several iterations, with Python 2.x being the predominant version for many
years. Python 3.x was introduced in 2008 with various improvements and changes, leading to some
backward compatibility issues.
• Python has since become one of the most popular programming languages globally, known for its
simplicity, versatility, and readability.
2.1. Keywords:
Keywords in Python are reserved words that have special meaning and are part of the language syntax.
They cannot be used as identifiers (variable names, function names, etc.) because they are reserved for specific
purposes within the language.
Python has a set of built-in keywords that serve various purposes, such as defining control flow,
declaring functions and classes, and performing operations.
2.2. Identifiers:
Identifiers in Python are names used to identify variables, functions, classes, modules, or other objects
in a program. An identifier can consist of letters (both uppercase and lowercase), digits, and underscores, but it
must start with a letter (either uppercase or lowercase) or an underscore. Python is case-sensitive, meaning
myVar and MyVar are treated as different identifiers.
• They can contain letters (both uppercase and lowercase), digits, and underscores.
https://orion021.github.io/krishnan_t/ 2 | 😁 👻 ✌️ 😎
Python - Variables, Data Types, I/O Statements, Casting and Operators
2.3. Comments:
Comments in Python are non-executable statements that are used to annotate code, provide
explanations, or temporarily disable certain parts of code. They are intended for human readers and are ignored
by the Python interpreter during program execution.
Types of Comments:
• Single-line Comments: Begin with the # character and extend until the end of the line.
• Multi-line Comments: Enclosed within triple quotes (""" or ''') and can span multiple lines.
Purpose of Comments:
• Temporary Disabling: Temporarily deactivate certain code segments for debugging or testing purposes.
Example:-
"""
This is a multi-line comment.
It provides additional explanation about the program.
In this case, it explains the purpose of each section of code.
"""
https://orion021.github.io/krishnan_t/ 3 | 😁 👻 ✌️ 😎
Python - Variables, Data Types, I/O Statements, Casting and Operators
Arithmetic operators are used to perform mathematical operations between variables or values.
• Floor Division (//) : The division that results in the quotient rounded down to the nearest integer.
• Exponentiation (**) : Raises the left operand to the power of the right operand.
Example:-
a = 10
b = 3
addition = a + b
subtraction = a - b
multiplication = a * b
division = a / b
floor_division = a // b
modulus = a % b
exponentiation = a ** b
print("Addition:", addition)
print("Subtraction:", subtraction)
print("Multiplication:", multiplication)
print("Division:", division)
print("Floor Division:", floor_division)
print("Modulus:", modulus)
print("Exponentiation:", exponentiation)
Output:-
Addition: 13
Subtraction: 7
Multiplication: 30
Division: 3.3333333333333335
Floor Division: 3
Modulus: 1
Exponentiation: 1000
https://orion021.github.io/krishnan_t/ 4 | 😁 👻 ✌️ 😎
Python - Variables, Data Types, I/O Statements, Casting and Operators
• Not equal to (!=) : Returns True if the operands are not equal.
• Greater than (>) : Returns True if the first operand is greater than the second.
• Less than (<) : Returns True if the first operand is less than the second.
• Greater than or equal to (>=) : Returns True if the first operand is greater than or equal to the
second.
• Less than or equal to (<=) : Returns True if the first operand is less than or equal to the second.
Example:-
x = 10
y = 5
print("Equal to:", x == y)
print("Not equal to:", x != y)
print("Greater than:", x > y)
print("Less than:", x < y)
print("Greater than or equal to:", x >= y)
print("Less than or equal to:", x <= y)
Output:-
Example:-
p = True
q = False
print("Logical AND:", p and q)
print("Logical OR:", p or q)
print("Logical NOT:", not p)
Output:-
https://orion021.github.io/krishnan_t/ 5 | 😁 👻 ✌️ 😎
Python - Variables, Data Types, I/O Statements, Casting and Operators
• Assignment (=) : Assigns the value on the right to the variable on the left.
• Add and assign (+=) : Adds the value on the right to the variable on the left and assigns the
result to the variable.
• Subtract and assign (-=) : Subtracts the value on the right from the variable on the left and assigns
the result to the variable.
• Multiply and assign (*=) : Multiplies the variable on the left by the value on the right and assigns
the result to the variable.
• Divide and assign (/=) : Divides the variable on the left by the value on the right and assigns the
result to the variable.
• Modulus and assign (%=) : Computes the modulus of the variable on the left by the value on the
right and assigns the result to the variable.
• Exponent and assign (**=) : Raises the variable on the left to the power of the value on the right and
assigns the result to the variable.
• Floor divide and assign (//=) : Computes the floor division of the variable on the left by the
value on the right and assigns the result to the variable.
Example:-
x = 5
x += 3
print("Add and assign:", x)
x -= 2
print("Subtract and assign:", x)
x *= 2
print("Multiply and assign:", x)
x /= 4
print("Divide and assign:", x)
x %= 3
print("Modulus and assign:", x)
x **= 2
print("Exponent and assign:", x)
x //= 2
print("Floor divide and assign:", x)
Output:-
https://orion021.github.io/krishnan_t/ 6 | 😁 👻 ✌️ 😎
Python - Variables, Data Types, I/O Statements, Casting and Operators
Identity operators are used to compare the memory locations of two objects.
• is not : Returns True if both variables are not the same object.
Example:-
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print("is:", a is b)
print("is not:", a is not b)
print("is:", a is c)
Output:-
is: False
is not: True
is: True
• In : Returns True if a sequence with the specified value is present in the object.
• not in : Returns True if a sequence with the specified value is not present in the object.
Example:-
my_list = [1, 2, 3, 4, 5]
print("in:", 3 in my_list)
print("not in:", 6 not in my_list)
Output:-
in: True
not in: True
https://orion021.github.io/krishnan_t/ 7 | 😁 👻 ✌️ 😎
Python - Variables, Data Types, I/O Statements, Casting and Operators
add the Binary weights where you have 1's Places --> 128+32+8+2 = 170
• Left Shift (<<): Shifts the bits to the left by a specified number of positions.
• Right Shift (>>): Shifts the bits to the right by a specified number of positions.
https://orion021.github.io/krishnan_t/ 8 | 😁 👻 ✌️ 😎
Python - Variables, Data Types, I/O Statements, Casting and Operators
Example:-
a = 170
b = 240
result_and = a & b
print("Bitwise AND:", result_and)
result_or = a | b
print("Bitwise OR:", result_or)
result_xor = a ^ b
print("Bitwise XOR:", result_xor)
result_not_a = ~a
result_not_b = ~b
print("Bitwise NOT of a:", result_not_a)
print("Bitwise NOT of b:", result_not_b)
shift_left_a = a << 3
print("Left Shift of a:", shift_left_a)
shift_right_b = b >> 3
print("Right Shift of b:", shift_right_b)
Output:-
3.7.1.Detailed explanation:-
In bitwise AND, each bit in the result is In bitwise XOR, each bit in the result is
set to 1 if and only if both corresponding bits in set to 1 if the corresponding bits in the operands
the operands are 1. are different.
In bitwise OR, each bit in the result is set In bitwise NOT, each bit in the result is
to 1 if either of the corresponding bits in the flipped (0 becomes 1 and 1 becomes 0) and take
operands is 1. 2’s complement add – (negation) as prefix.
https://orion021.github.io/krishnan_t/ 9 | 😁 👻 ✌️ 😎
Python - Variables, Data Types, I/O Statements, Casting and Operators
In left shift, each bit in the number is In right shift, each bit in the number is
shifted to the left by the specified number of shifted to the right by the specified number of
positions. Zeros are filled in from the right. positions. Zeros are filled in from the left.
Operator Precedence
Operator precedence determines the order in which operators are evaluated in an expression. In
Python, as in many programming languages, operators have different levels of precedence. Operators with
higher precedence are evaluated before operators with lower precedence.
For example, in the expression 2 + 3 * 4, multiplication (*) has a higher precedence than addition (+), so
3 * 4 is evaluated first, resulting in 12, and then 2 + 12 is evaluated, resulting in 14.
1. Parentheses ()
2. Exponentiation **
5. Addition +, subtraction -
8. Bitwise XOR ^
9. Bitwise OR |
10. Comparison operators ==, !=, <, <=, >, >=, is, is not, in, not in
Operators with the same precedence are evaluated from left to right. For example, + and - have the
same precedence, so 2 + 3 - 4 is evaluated as (2 + 3) - 4.
Understanding operator precedence is important for writing expressions that behave as expected and
avoiding errors caused by incorrect evaluation order.
https://orion021.github.io/krishnan_t/ 10 | 😁 👻 ✌️ 😎
Python - Variables, Data Types, I/O Statements, Casting and Operators
These are the basic data types provided by Python, and the functions mentioned above are used to create
instances of these types. Examples of built-in types include integers, floats, strings, lists, tuples, dictionaries,
sets, booleans, complex numbers, and ranges.
1. Numeric Types:
z1 = 3 + 4j # 3 + 4i
z2 = complex(2, -5) # 2 - 5i
print(z1, z2)
2. Sequence Types:
numbers = [1, 2, 3]
letters = ['a', 'b', 'c']
print("list examples:", numbers, letters)
https://orion021.github.io/krishnan_t/ 11 | 😁 👻 ✌️ 😎
Python - Variables, Data Types, I/O Statements, Casting and Operators
coordinates = (1, 2, 3)
vowels = ('a', 'e', 'i', 'o', 'u')
print("tuple examples:", coordinates, vowels)
3. Mapping Type:
4. Set Types:
number_set = {1, 2, 3}
letter_set = {'a', 'b', 'c'}
print("set examples:", number_set, letter_set)
is_true = True
is_false = False
print("bool examples:", is_true, is_false)
null_value = None
print("None examples:", null_value)
https://orion021.github.io/krishnan_t/ 12 | 😁 👻 ✌️ 😎
Python - Variables, Data Types, I/O Statements, Casting and Operators
Typecasting, is the process of converting one data type into another. In Python, you can perform type
conversion using built-in functions or constructors. Here are some common type conversion functions:
# Integer to float
int_num = 5
float_num = float(int_num)
print(float_num) # Output: 5.0
# Float to integer
float_num = 3.14
int_num = int(float_num)
print(int_num) # Output: 3
# Integer to string
int_num = 42
str_num = str(int_num)
print(str_num) # Output: '42'
# String to integer
str_num = '123'
int_num = int(str_num)
print(int_num) # Output: 123
# List to tuple
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
print(my_tuple) # Output: (1, 2, 3)
# Tuple to list
my_tuple = (4, 5, 6)
my_list = list(my_tuple)
print(my_list) # Output: [4, 5, 6]
# String to list
my_string = "hello"
my_list = list(my_string)
print(my_list) # Output: ['h', 'e', 'l', 'l', 'o']
# List to set
my_list = [1, 2, 3, 3, 4, 5]
my_set = set(my_list)
print(my_set) # Output: {1, 2, 3, 4, 5}
https://orion021.github.io/krishnan_t/ 13 | 😁 👻 ✌️ 😎
Python - Variables, Data Types, I/O Statements, Casting and Operators
• To get input of different types (like integer or float), you can use type casting.
• You can print fixed strings or use variables to dynamically include values.
• % formatting allows you to specify a format string with placeholders for variables.
• Introduced in Python 3.6, f-strings provide a more concise and readable way to format
strings.
name = "Doraemon"
age = 3
print(f"My name is {name} and I am {age} years old.")
https://orion021.github.io/krishnan_t/ 14 | 😁 👻 ✌️ 😎
Python - Variables, Data Types, I/O Statements, Casting and Operators
6. Lists
A list in Python is an ordered collection of items that can contain elements of different data types. Here
are some characteristics:
• Ordered: Elements in a list maintain their order, which means you can access elements by their
index.
• Mutable: Lists are mutable, meaning you can modify, add, or remove elements after the list is
created.
• Heterogeneous: Lists can contain elements of different data types, including integers, strings, floats,
and even other lists.
• Dynamic: Lists can grow or shrink in size dynamically as elements are added or removed.
# List of integers
int_list = [1, 2, 3, 4, 5]
# List of strings
str_list = ['apple', 'banana', 'orange']
# List of lists
nested_list = [[1, 2, 3], ['a', 'b', 'c'], [True, False]]
# Empty list
empty_list = []
You can access elements in a list using square brackets [] with the index of the element you want to access.
Python uses zero-based indexing.
Example:
https://orion021.github.io/krishnan_t/ 15 | 😁 👻 ✌️ 😎
Python - Variables, Data Types, I/O Statements, Casting and Operators
1. append(element):
2. clear():
my_list = [1, 2, 3]
my_list.clear()
print(my_list) # Output: []
3. copy():
my_list = [1, 2, 3]
new_list = my_list.copy()
print(new_list) # Output: [1, 2, 3]
4. count(element):
my_list = [1, 2, 3, 2]
count = my_list.count(2)
print(count) # Output: 2
5. extend(iterable):
• Description: Extends the list by appending elements from the specified iterable.
my_list = [1, 2, 3]
my_list.extend([4, 5, 6])
print(my_list) # Output: [1, 2, 3, 4, 5, 6]
6. index(element):
• Description: Returns the index of the first occurrence of the specified element in the list.
my_list = [1, 2, 3, 2]
index = my_list.index(2)
print(index) # Output: 1
https://orion021.github.io/krishnan_t/ 16 | 😁 👻 ✌️ 😎
Python - Variables, Data Types, I/O Statements, Casting and Operators
7. insert(index, element):
my_list = [1, 2, 3]
my_list.insert(1, 1.5)
print(my_list) # Output: [1, 1.5, 2, 3]
8. pop(index):
9. remove(element):
• Description: Removes the first occurrence of the specified element from the list.
my_list = [1, 2, 3, 2]
my_list.remove(2)
print(my_list) # Output: [1, 3, 2]
10. reverse():
my_list = [1, 2, 3]
my_list.reverse()
print(my_list) # Output: [3, 2, 1]
• Description: Sorts the elements of the list in place, optionally accepting a key function to customize
sorting.
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5]
my_list.sort()
print(my_list) # Output: [1, 1, 2, 3, 4, 5, 5, 6, 9]
# Custom functions
def myFunc(t):
return len(t)
https://orion021.github.io/krishnan_t/ 17 | 😁 👻 ✌️ 😎
Python - Variables, Data Types, I/O Statements, Casting and Operators
7. Tuple’s
A tuple in Python is an ordered collection of elements, similar to a list, but with the key difference that
tuples are immutable, meaning they cannot be modified after creation. Tuples are defined using parentheses ()
and can contain elements of different data types. Here are the key characteristics of tuples:
3. Heterogeneous: Tuples can contain elements of different data types, including integers, floats, strings,
and other tuples.
5. Iterative: Tuples support iteration, allowing you to loop through the elements using a for loop or other
iterable methods.
6. Hashable: Tuples are hashable, meaning they can be used as keys in dictionaries and elements in sets.
my_tuple = (1, 2, 3, 4, 5)
print(first_element) # Output: 1
print(second_element) # Output: 2
print(third_element) # Output: 3
1. count(value):
• Returns the index of the first occurrence of a specified value within a specified range of
indices.
# Define a tuple
my_tuple = (1, 2, 3, 4, 2, 5, 2)
https://orion021.github.io/krishnan_t/ 18 | 😁 👻 ✌️ 😎
Python - Variables, Data Types, I/O Statements, Casting and Operators
8. Dictionary
5. Keys Immutable: Keys must be of an immutable data type, such as strings, integers, or tuples.
6. Values Any Type: Values in a dictionary can be of any data type, including other dictionaries.
7. Access by Key: Values in a dictionary are accessed using their corresponding keys rather than
indices.
8. Dynamic Size: Dictionaries can grow or shrink in size as needed to accommodate more elements or
remove existing ones.
# Define a dictionary
my_dict = {"name": "John", "age": 30, "city": "New York"}
# Accessing elements
print(my_dict["name"]) # Output: John
print(my_dict.get("age")) # Output: 30
8.3.Dictionary methods
1. clear():
3. fromkeys(keys, value=None):
• Returns a new dictionary with keys from an iterable and values set to a specified value
(default None).
https://orion021.github.io/krishnan_t/ 19 | 😁 👻 ✌️ 😎
Python - Variables, Data Types, I/O Statements, Casting and Operators
4. get(key, default=None):
• Returns the value for a specified key. If the key is not found, returns the default value
(default None).
5. items():
6. keys():
• Returns a view object that displays a list of all keys in the dictionary.
7. pop(key, default):
• Removes and returns the value associated with the specified key. If the key is not found,
returns the default value (default None).
8. popitem():
• Removes and returns an arbitrary (key, value) pair from the dictionary.
9. setdefault(key, default=None):
• Returns the value for a specified key. If the key is not found, inserts the key with the
specified default value (default None) and returns the default value.
my_dict = {'a': 1, 'b': 2}
value = my_dict.setdefault('c', 0)
print("Setdefault value:", value) # Output: Setdefault value: 0
https://orion021.github.io/krishnan_t/ 20 | 😁 👻 ✌️ 😎
Python - Variables, Data Types, I/O Statements, Casting and Operators
10. update(key:value):
• Updates the dictionary with the key-value pairs from another dictionary or iterable.
11. values():
• Returns a view object that displays a list of all values in the dictionary.
https://orion021.github.io/krishnan_t/ 21 | 😁 👻 ✌️ 😎
Python - Variables, Data Types, I/O Statements, Casting and Operators
10. Sets
• They are defined using curly braces {} and can contain various data types.
• Sets do not allow duplicate elements. If you try to add a duplicate element, it will be ignored.
• Sets are mutable, meaning you can add or remove elements from them.
• Sets are commonly used for membership testing, removing duplicates from a sequence, and
mathematical operations like union, intersection, etc.
• Example:
my_set = {1, 2, 3, 4, 5}
print(my_set)
• Since sets are unordered, you cannot access elements using indices like you do with lists or tuples.
• However, you can iterate over the elements of a set using a loop, or check for membership of a specific
element.
• Program:
my_set = {1, 2, 3, 4, 5}
# Check membership
if 3 in my_set:
print("3 is present in the set")
my_set = {1, 2, 3}
my_set.add(4)
print(my_set) # Output: {1, 2, 3, 4}
• remove(): Removes the specified element from the set. Raises an error if the element is not present.
my_set = {1, 2, 3}
my_set.remove(2)
print(my_set) # Output: {1, 3}
• discard(): Removes the specified element from the set if it is present. Unlike remove(), it does not raise
an error if the element is not found.
my_set = {1, 2, 3}
my_set.discard(2)
print(my_set) # Output: {1, 3}
• clear(): Removes all elements from the set.
https://orion021.github.io/krishnan_t/ 22 | 😁 👻 ✌️ 😎
Python - Variables, Data Types, I/O Statements, Casting and Operators
my_set = {1, 2, 3}
my_set.clear()
print(my_set) # Output: set()
• union(): Returns a new set containing all the distinct elements from both sets.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
print(union_set) # Output: {1, 2, 3, 4, 5}
• intersection(): Returns a new set containing the common elements between two sets.
set1 = {1, 2, 3, 7}
set2 = {3, 4, 5, 7}
intersection_set = set1.intersection(set2)
print(intersection_set) # Output: {3, 7}
• difference(): Returns a new set containing the elements that are present in the first set but not in the
second set.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
difference_set = set1.difference(set2)
print(difference_set) # Output: {1, 2}
• pop(): Removes and returns an arbitrary element from the set. If the set is empty, raises a KeyError.
my_set = {1, 2, 3}
popped_element = my_set.pop()
print(popped_element) # Output: 1
print(my_set) # Output: {2, 3}
• update(): Updates the set with the union of itself and others.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
set1.update(set2)
print(set1) # Output: {1, 2, 3, 4, 5}
• issubset(): Returns True if all elements of the set are present in the specified set, otherwise returns
False.
set1 = {1, 2}
set2 = {1, 2, 3, 4, 5}
print(set1.issubset(set2)) # Output: True
• issuperset(): Returns True if all elements of the specified set are present in the set, otherwise returns
False.
set1 = {1, 2, 3, 4, 5}
set2 = {1, 2}
print(set1.issuperset(set2)) # Output: True
https://orion021.github.io/krishnan_t/ 23 | 😁 👻 ✌️ 😎
Python - Variables, Data Types, I/O Statements, Casting and Operators
• intersection_update(): Updates the set with the intersection of itself and another set.
• symmetric_difference(): Returns a new set containing elements that are in exactly one of the sets.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
sym_diff_set = set1.symmetric_difference(set2)
print(sym_diff_set) # Output: {1, 2, 4, 5}
Augmented assignment operators are shorthand operators in Python that combine assignment with another
operation, such as arithmetic or bitwise operations. They provide a concise way to perform an operation and update
the value of a variable in a single step.
The operator that are applicable for list is += and *=. But -=, /=, //=, **== are not supported.
For List:
my_list = [1, 2, 3]
my_list += [4,5,6]
print(my_list) # Output: [1, 2, 3, 5]
my_list = [1, 2, 3]
my_list *= 3
print(my_list) # Output: [1, 2, 3, 1, 2, 3, 1, 2, 3]
For Tuples:
my_list = (1, 2, 3)
my_list += (4,5,6)
print(my_list) # Output: (1, 2, 3, 4, 5, 6)
my_list = (1, 2, 3)
my_list *= 3
print(my_list) # Output: (1, 2, 3, 1, 2, 3, 1, 2, 3)
Even if, Tuples are immutable, meaning their contents cannot be changed after creation. So, while the
augmented assignment operators for tuples (+= and *=) create new tuples as a result of the operation, they
effectively produce new tuple objects rather than modifying the existing ones.
https://orion021.github.io/krishnan_t/ 24 | 😁 👻 ✌️ 😎
Python - Variables, Data Types, I/O Statements, Casting and Operators
Dictionaries in programming are like real-world dictionaries in that they provide a way to store and retrieve
information. In Python, for example, a dictionary is a collection of key-value pairs where each key is unique and
associated with a value. This structure can be used to model real-world things in various ways as follows:
Program:
employee = {
"id": 101,
"details": {
"name": "Disha",
"position": "Manager",
"department": "Sales",
"salary": 60000,
"email": "[email protected]",
"phone": "12345-67890",
"hire_date": "2023-05-15"
}
}
print("Employee Information:")
print("ID:", employee["id"])
print("Name:", employee["details"]["name"])
print("Position:", employee["details"]["position"])
print("Department:", employee["details"]["department"])
print("Salary:", employee["details"]["salary"])
print("Email:", employee["details"]["email"])
print("Phone:", employee["details"]["phone"])
print("Hire Date:", employee["details"]["hire_date"])
Output:
Employee Information:
ID: 101
Name: Disha
Position: Manager
Department: Sales
Salary: 60000
Email: [email protected]
Phone: 12345-67890
Hire Date: 2023-05-15
https://orion021.github.io/krishnan_t/ 25 | 😁 👻 ✌️ 😎
Python - Variables, Data Types, I/O Statements, Casting and Operators
Program
student = {
"id": "S001",
"info": {
"name": "Ujwal",
"grade": 9,
"subjects": ["Math", "Science", "English"],
"address": "123 Main St",
"parent_contact": "12345-67890",
"birthdate": "2010-03-21"
}
}
print("Student Information:")
print("ID:", student["id"])
print("Name:", student["info"]["name"])
print("Grade:", student["info"]["grade"])
print("Subjects:", student["info"]["subjects"])
print("Address:", student["info"]["address"])
print("Parent Contact:", student["info"]["parent_contact"])
print("Birthdate:", student["info"]["birthdate"])
Output:
Student Information:
ID: S001
Name: Ujwal
Grade: 9
Subjects: ['Math', 'Science', 'English']
Address: 123 Main St
Parent Contact: 12345-67890
Birthdate: 2010-03-21
https://orion021.github.io/krishnan_t/ 26 | 😁 👻 ✌️ 😎
Python - Variables, Data Types, I/O Statements, Casting and Operators
Program:
zoho_corporation = {
"founding_year": 1996,
"founders": ["Sridhar Vembu", "Tony Thomas"],
"headquarters": "Chennai, Tamil Nadu, India",
"products": ["CRM software",
"Email hosting",
"Project management tools",
"Office suite",
"Invoicing software"],
"offices_and_data_centers": ["India",
"China",
"Japan",
"Europe",
"United States",]}
Output:
https://orion021.github.io/krishnan_t/ 27 | 😁 👻 ✌️ 😎
Python - Variables, Data Types, I/O Statements, Casting and Operators
Pretty printing is the process of formatting complex data structures, such as dictionaries or lists, in a
visually appealing and easy-to-read manner. It helps improve the readability of the output by adding appropriate
spacing, indentation, and line breaks.
Program:
import pprint
zoho_corporation = {
"founding_year": 1996,
"founders": ["Sridhar Vembu", "Tony Thomas"],
"headquarters": "Chennai, Tamil Nadu, India",
"products": ["CRM software",
"Email hosting",
"Project management tools",
"Office suite",
"Invoicing software"],
"offices_and_data_centers": ["India",
"China",
"Japan",
"Europe"
"United States",]}
pprint.pprint(zoho_corporation)
Output:
https://orion021.github.io/krishnan_t/ 28 | 😁 👻 ✌️ 😎