0% found this document useful (0 votes)
15 views15 pages

Python Data Types and Control Statements

This will be helpful for 5 sem students of gtu this pdf is for python for data science

Uploaded by

Fake Id
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views15 pages

Python Data Types and Control Statements

This will be helpful for 5 sem students of gtu this pdf is for python for data science

Uploaded by

Fake Id
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python for Data Science (3150713)

Chepter – 1 Overview of Python and Data Structures

Q-1. List Advantages and Disadvantages of Python.


Advantages of Python:
• Easy to Learn: Python has a simple syntax and is relatively easy to learn, making it a
great language for beginners.
• Versatile: Python can be used for web development, data analysis, artificial intelligence,
machine learning, automation and more.
• Large Community: Python has a vast and active community, ensuring there are plenty
of resources available.
• Cross-Platform: Python can run on multiple operating systems, including Windows,
macOS, and Linux.
• Extensive Libraries: Python has numerous libraries and frameworks (e.g., NumPy,
pandas, Flask, Django) that simplify development.
• Rapid Development: Python's syntax and nature enable rapid prototyping and
development.
• Open-Source: Python is open-source, which means it's free to use and distribute.
• Data Analysis: Python is widely used in data science and analytics due to libraries like
pandas, NumPy, and Matplotlib.

Disadvantages of Python:
• Slow Performance: Python is an interpreted language, which can result in slower
execution times.
• Limited Multithreading: Python's Global Interpreter Lock (GIL) restricts true
multithreading.
• Memory-Intensive: Python's dynamic typing and memory management can lead to
memory-intensive applications.
• Less Suitable for Mobile Development: Python is not typically used for mobile app
development.
• Limited Support for Parallel Processing: Python's GIL can make parallel processing
challenging.
• Dependent on Third-Party Libraries: Python's extensive use of libraries can lead to
dependency issues.
• Security Concerns: Python's dynamic typing and flexibility can introduce security risks.
• Limited Error Handling: Python's syntax and nature can make error handling more
difficult.
• Not Ideal for Real-Time Systems: Python's slow performance and GIL make it less
suitable for real-time systems.
• Compatibility Issues: Python's versions (e.g., Python 2.x vs. 3.x) can cause
compatibility problems.
Python for Data Science (3150713)

Q-2. Explain Data Types of Python with suitable example.

1. Numeric Data Types


• Integers (int): Whole numbers, either positive, negative, or zero.
Example: x = 10
• Floating Point Numbers (float): Decimal numbers.
Example: x = 10.5
• Complex Numbers (complex): Numbers with real and imaginary parts.
Example: x = 3 + 5j

2. Sequence Data Types


• Strings (str): Ordered collections of characters.

Example: name = "John"

• Lists (list): Ordered collections of items, mutable.


Example: fruits = ["apple", "banana", "cherry"]
• Tuples (tuple): Ordered collections of items, immutable.

Example: colors = ("red", "green", "blue")


Python for Data Science (3150713)

3. Mapping Data Type


• Dictionaries (dict): Unordered collections of key-value pairs.

Example: person = {"name": "John", "age": 30}


4. Set Data Types
• Sets (set): Unordered collections of unique items.
Example: numbers = {1, 2, 3, 4, 5}
• Frozensets (frozenset): Immutable sets.
Example: frozen_numbers = frozenset([1, 2, 3, 4, 5])
5. Boolean Data Type
• Boolean (bool): True or False values.
Example: is_admin = True

Q-3. Explain List in Python with suitable example.


• Lists are mutable, meaning you can modify their contents (add, remove, or change
items) after they are created.
• List is a mutable ordered Sequence of objects, duplicate values are allowed inside list.
• List will be represented by sequare brackets [ ].
• Python does not have array, List can be used similary to array.
• Each element can be accessed by an index.
Example:-
my_list = [‘Prime’, ‘college’, ‘Navsari’]

List Characteristics
Lists are:
• Ordered - They maintain the order of elements.
• Mutable - Items can be changed after creation.
• Allow duplicates - They can contain duplicate values.
Python for Data Science (3150713)

Q-4. Explain Set in Python with suitable example.


• A set is an unordered collection of unique elements in Python.
• set will be represented by curly brackets { }.
• Sets are used to store multiple items in a single variable.
• They automatically eliminate duplicate entries.
• A set is a collection which is unordered, unchangeable*, and unindexed.
• Since sets are unordered, they do not support indexing, slicing, or other sequence-like
behaviors.
• set has many in-built methods such as add(), Clear(), Copy(), POP(), remove() etc..

Example:-
my_set = {1,1,1,2,2,2,5,3,6}
print(my_set)
OutPut:-
{1, 2, 3, 5, 6}

Q-5. Explain Tuple in Python with suitable example.


• Tuples are used to store multiple items in a single variable.
• Tuple is one of 4 built-in data types in Python used to store collections of data, the other
3 are List, Set, and Dictionary, all with different qualities and usage.
• A tuple is a collection which is ordered and unchangeable.
• Tuples are written with round brackets ().

Example:-
tuple = ("apple", "banana", "cherry")
print(tuple)
OutPut:-
('apple', 'banana', 'cherry')

Q-6. Explain Dictionary Python with suitable example.


• A Python dictionary is a data structure that stores the value in key: value pairs.
• Here, The data is stored in key: value pairs in dictionaries, which makes it easier to find
values.
• A dictionary can also be created by the built-in function dict().
• An empty dictionary can be created by just placing curly braces{}.
Python for Data Science (3150713)

Example:-
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
OutPut:-
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

Q-7. Explain expression evaluation in Python with suitable example.


Types of Expressions
1. Arithmetic Expressions
2. Comparison Expressions
3. Logical Expressions
4. Assignment Expressions
5. Conditional Expressions

Arithmetic Expressions
Arithmetic expressions evaluate to a numerical value.
Example:
Addition x=5 print(x + y) Output:
y=3 8
Subtraction x=5 print(x - y) Output:
y=3 2
Multiplication x=5 print(x * y) Output:
y=3 15
Division x=5 print(x / y) Output:
y=3 1.6666666666666667
Modulus x=5 print(x % y) Output:
y=3 2
Exponentiation x=5 print(x ** y) Output:
y=3 125
Python for Data Science (3150713)

Comparison Expressions
Comparison expressions evaluate to a boolean value (True or False).
Example:
Equal x=5 print(x == y) Output:
y=3 False
Not Equal x=5 print(x != y) Output:
y=3 True
Greater Than x=5 print(x > y) Output:
y=3 True
Less Than x=5 print(x < y) Output:
y=3 False
Greater Than or x=5 print(x >= y) Output:
Equal y=3 True
Less Than or Equal x=5 print(x <= y) Output:
y=3 False

Logical Expressions
Logical expressions evaluate to a boolean value (True or False).
Example:
AND x = True print(x and y) Output:
y = False False
OR x = True print(x or y) Output:
y = False True
NOT x = True print(not x) Output:
y = False False

Q-8. Explain functions in Python with suitable example.


• A function is a block of code which only runs when it is called.
• You can pass data, known as parameters, into a function.
• A function can return data as a result.
Python for Data Science (3150713)

In Python a function is defined using the def keyword:


def my_function():
print("Hello from a function")

To call a function, use the function name followed by parenthesis:


def my_function():
print("Hello from a function")

my_function()

Function Types
1. Built-in Functions (e.g., len(), print())
• Python's standard library includes number of built-in functions. Some of Python's built-
in functions are print(), int(), len(), sum(), etc.
2. User-defined Functions
3. Anonymous Functions (Lambda Functions)
Anonymous functions defined using the lambda keyword.
Example : Lambda Function
double = lambda x: x * 2
print(double(5))
Output: 10

4. Recursive Functions
Functions that call themselves.
Example : Recursive Function
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
print(factorial(5))
Output:
120
Python for Data Science (3150713)

Q-9. List and Explain String functions in Python.


String Modification Functions
lower() Converts string to lowercase. print("HELLO".lower()) Output: hello
upper() Converts string to uppercase. print("hello".upper()) Output: HELLO
title() Converts string to title case. print("hello world".title()) Output:
Hello World
strip() Removes leading and trailing print("hello".strip()) Output: hello
whitespace.
lstrip() Removes leading whitespace. print("hello".lstrip()) Output: hello
rstrip() Removes trailing whitespace. print("hello".rstrip()) Output: hello

String Searching Functions


find() Returns index of first print("hello".find("l")) Output: 2
occurrence.
rfind() Returns index of last print("hello".rfind("l")) Output: 3
occurrence.
index() Returns index of first print("hello".index("l")) Output: 2
occurrence.
rindex() Returns index of last print("hello".rindex("l")) Output: 3
occurrence.
count() Returns number of print("hello".count("l")) Output: 2
occurrences.

String Splitting Functions


split() Splits string into print("hello world".split()) Output:
substrings. ["hello", "world"]
rsplit() Splits string into print("hello world".rsplit()) Output:
substrings from right. ["hello", "world"]
splitlines() Splits string into lines. print("hello\nworld".splitlines()) Output:
["hello", "world"]

String Joining Functions


join() Joins substrings into a print(",".join(["hello", "world"])) Output:
string. hello,world

String Replacement Functions


replace() Replaces print("hello world".replace("world", "Python")) Output:
occurrences. hello Python
Python for Data Science (3150713)

String Formatting Functions


format() Formats string. print("My name is {}".format("John")) Output:
My name is John
f-strings Formats string name = "John" Output:
(Python 3.6+). print(f"My name is {name}") My name is John

Q-10. Explain String Slicing in python with Example.


• You can return a range of characters by using the slice syntax.
• Specify the start index and the end index, separated by a colon, to return a part of the
string.
Syntax:
substring = string[start:end:step]

Get the characters from position 2 to position 5 (not included):


b = "Hello, World!"
print(b[2:5])
OutPut:- llo

Slice From the Start


By leaving out the start index, the range will start at the first character:
b = "Hello, World!"
print(b[:5])
OutPut:- Hello

Slice To the End


By leaving out the end index, the range will go to the end:
b = "Hello, World!"
print(b[2:])
OutPut:- llo, World!

Negative Indexing
Use negative indexes to start the slice from the end of the string:
b = "Hello, World!"
print(b[-5:-2])
OutPut:- orl
Python for Data Science (3150713)

Q-11. Explain String Formatting in python with example.


String formatting is the process of inserting values into a string. Python provides multiple ways
to format strings.

1. Percentage (%) Operator


name = "John"
age = 30
print("My name is %s and I'm %d years old." % (name, age))
Output:
My name is John and I'm 30 years old.

2. [Link]() Method
name = "John"
age = 30
print("My name is {} and I'm {} years old.".format(name, age))
Output:
My name is John and I'm 30 years old.

3. f-Strings (Python 3.6+)


name = "John"
age = 30
print(f"My name is {name} and I'm {age} years old.")
Output:
My name is John and I'm 30 years old.

Formatting Options
1. Integer Formatting
num = 12345
print(f"{num:,}")
Output:
12,345

2. *Float Formatting*
num = 123.456
print(f"{num:.2f}")
Output:
123.46
Python for Data Science (3150713)

3. *String Alignment*
name = "John" Output: John
print(f"{name:>10}")
name = "John" Output: John
print(f"{name:<10}")
name = "John" Output: John
print(f"{name:^10}")

4. *Precision*
num = 123.456789
print(f"{num:.4f}")
Output:
123.4568

Q-12. List and Explain all Data Structures in Python.


1. List
• Description: A list is an ordered, mutable (changeable) collection of elements. Lists can
hold items of different types (e.g., integers, strings, or even other lists).
• Syntax: Lists are defined by square brackets [] with items separated by commas.
Example:
my_list = [1, 2, 3, "hello", [4, 5]]
print(my_list)
Output:
[1, 2, 3, 'hello', [4, 5]]

2. Tuple
• Description: A tuple is an ordered, immutable collection of elements. Once a tuple is
created, it cannot be modified.
• Syntax: Tuples are defined by parentheses () with elements separated by commas.
Example:
my_tuple = (1, 2, 3, "hello")
print(my_tuple)
Output:
(1, 2, 3, 'hello')
Python for Data Science (3150713)

3. Set
• Description: A set is an unordered, mutable collection of unique elements. Sets do not
allow duplicates.
• Syntax: Sets are defined by curly braces {} or by using the set() function.
Example:
my_set = {1, 2, 3, 3, 4,4}
print(my_set)
Output:
{1, 2, 3, 4} (duplicates are removed)

4. Dictionary
• Description: A dictionary is an unordered collection of key-value pairs. Keys must be
unique and immutable (e.g., strings, numbers, tuples), while values can be of any type.
• Syntax: Dictionaries are defined by curly braces {} with key-value pairs separated by
colons.
Example:
my_dict = {"name": "Alice", "age": 25}
print(my_dict["name"])
Output:
Alice

[Link]
• Description: A string is a sequence of characters enclosed in quotes (either single or
double). Strings are immutable, meaning once created, they cannot be changed.
• Syntax: Strings are defined by enclosing characters in single quotes (') or double quotes
(").
Example:
my_string = "Hello, World!"
print(my_string)
Output:
Hello, World!

6. Range
• Description: A range object represents a sequence of numbers, commonly used in
loops. It generates numbers in a given range.
• Syntax: range(start, stop, step) where start is inclusive, stop is exclusive, and step is the
interval between numbers.
Python for Data Science (3150713)

Example:
r = range(1, 10, 2)
print(list(r))
Output:
[1, 3, 5, 7, 9]

Q-13. Explain Loops in Python with suitable example.


Loops in Python allow us to execute a block of code multiple times. Python supports two main
types of loops:
1. for loop
2. while loop
Each of these loops can be controlled using keywords like break, continue, and else.
1. for Loop
The for loop in Python is used for iterating over sequences like lists, tuples, strings, or ranges.
It repeats a block of code for each item in the sequence.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry

[Link] Loop: Used to repeat a block of code while a condition is true.


i=0
while i < 5:
print(i)
i += 1
Output:
0
1
2
3
4
Python for Data Science (3150713)

[Link] Loop: A loop inside another loop.


colors = ["red", "green", "blue"]
shapes = ["circle", "square", "triangle"]
for color in colors:
for shape in shapes:
print(color, shape)
Output:

red circle
red square
red triangle
green circle
green square
green triangle
blue circle
blue square
blue triangle

Loop Control Statements:


1. Break: Exits the loop immediately.
for i in range(5):
if i == 3:
break
print(i)
Output:
0
1
2

[Link]: Skips to the next iteration.


for i in range(5):
if i == 3:
continue
print(i)
Output:
0
1
4
Python for Data Science (3150713)

[Link]: Does nothing.


for i in range(5):
if i == 3:
pass
print(i)
Output:
0
1
2
3
4

Common questions

Powered by AI

Python's data types, such as integers, floats, strings, lists, tuples, sets, dictionaries, and more, provide flexibility and functionality for various forms of data manipulation. Numeric types like integers and floats allow for arithmetic calculations . Strings can be used for text processing through concatenation and slicing . Lists, being mutable sequences, allow for easy modification and can hold different data types, facilitating operations like appending and insertion . Dictionaries enable efficient data retrieval with key-value pairs . Sets offer unique item storage and automatic duplicate removal, useful for operations such as union and intersection .

Lists in Python are ordered and mutable sequences which allow for operations like item modification, appending, and slicing . They are suitable for collections of items where frequent modification is needed. Tuples are ordered but immutable sequences, meaning once they are created, they cannot be changed . They are ideal for storing collections of items that should not change and provide an efficiency edge over lists in such cases. Sets, on the other hand, are unordered collections that store unique items, automatically handling duplicate elimination . Their operations include unions, intersections, and differences, making them useful for membership testing and eliminating duplicates in a collection.

Iterative loops in Python, such as for and while loops, enable repeated execution of code blocks, supporting complex operations over data sequences like processing lists or performing repetitive calculations . For loops iterate over iterable objects like lists and ranges, executing the block for each element . While loops continue based on a given boolean condition until it evaluates to false, allowing operations contingent upon variable states . Loop control statements like break, continue, and pass further direct loop execution: break exits the loop prematurely, continue skips the current iteration and proceeds to the next loop cycle, while pass serves as a placeholder where a statement is syntactically required but no action is needed . These constructs enable developers to structure their programs with precision in handling repeated tasks.

Python is an excellent choice for rapid application development (RAD) due to its simple syntax, dynamic typing, and extensive library support, which together facilitate fast prototyping . The language's cross-platform capabilities allow for development across various operating systems without modification, while frameworks like Django and Flask provide robust infrastructures that speed up web application creation . However, challenges include Python's slow execution speed compared to compiled languages, which can be a drawback in performance-critical applications . Additionally, dependency management can become complex due to extensive use of third-party libraries, and the language's Global Interpreter Lock (GIL) can limit Python's suitability for multithreaded tasks .

Logical expressions in Python evaluate to boolean values (True or False) and are crucial in decision-making processes within code. They form the backbone of control structures such as if statements, allowing execution paths to be determined based on conditions . Logical operations include AND, OR, and NOT, which can be combined to form more complex conditions. For example, the expression 'x and y' returns True only if both x and y are true, while 'x or y' returns True if either x or y is true . The NOT operator inverts a boolean value, reversing the condition's logical state. Through such expressions, Python can evaluate conditions and direct the program flow accordingly.

Python offers several advantages for data science, including its simplicity and ease of learning due to its clear syntax . It is highly versatile, supporting various applications such as web development, data analysis, AI, and machine learning . Python also has a vast community and extensive libraries like NumPy and pandas, which simplify data manipulation . However, Python presents some disadvantages, such as slower performance due to its interpreted nature and limited multithreading capabilities because of the Global Interpreter Lock (GIL). The language can be memory-intensive and has issues with parallel processing, often not being ideal for mobile development or real-time systems .

Built-in functions in Python are predefined features of the language that perform common tasks such as printing output or converting data types (e.g., print(), len()). These functions are readily available and do not require any additional import to use. User-defined functions, on the other hand, are custom functions created by the programmer to perform specific tasks. They are defined using the def keyword, can accept parameters, and can return results . These types of functions offer more flexibility as they are tailored to specific requirements and can be modified to handle various inputs and produce different outputs as needed.

Python's Global Interpreter Lock (GIL) significantly affects parallel execution and performance by restricting the execution of multiple threads in a single process simultaneously . This means that even in a multithreaded application, only one thread can execute Python bytecode at a time, leading to inefficiencies especially in CPU-bound tasks which do not achieve true parallelism . The GIL hampers the performance of Python in multi-core processors where native thread parallelism could improve execution times. Python's performance is therefore reliant on workaround strategies like multiprocessing, where the GIL does not apply, but this introduces additional complexities in development.

String functions in Python significantly enhance textual data processing and manipulation through a variety of operations such as modification, searching, splitting, joining, and formatting . Functions like lower(), upper(), and title() modify the case of strings, enabling uniform text presentation. Searching functions such as find() and count() facilitate identifying and counting substrings within larger texts . Splitting and joining functions, like split() and join(), allow for efficient text parsing and concatenation, crucial in data preprocessing tasks. String formatting functions, such as format() and f-strings, provide a flexible way to insert variables into strings, enhancing readability and organization, especially in generating outputs and reports .

Dictionaries in Python implement hash tables to offer efficient data retrieval and manipulation. Each key-value pair is stored in an underlying array, and a hash function calculates the index for each key . This allows for average-case time complexity of O(1) for lookup, insert, and delete operations, enabling rapid access to values when the key is known. Keys must be immutable and hashable, which ensures consistency in access. Dictionary handling also supports iteration over keys and values, making it suitable for various applications where rapid access and manipulation of collections of data indexed by unique keys are necessary .

You might also like