0% found this document useful (0 votes)
14 views18 pages

Python Basics for Data Science

The document provides a comprehensive overview of Python basics for data science, covering topics such as variable assignment, conditional statements, data types, functions, and loops. It emphasizes the importance of readability and clarity in code, while also introducing built-in functions and methods for working with data structures like lists and dictionaries. Additionally, it touches on operator overloading and best practices for importing libraries and exploring unknown objects.

Uploaded by

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

Python Basics for Data Science

The document provides a comprehensive overview of Python basics for data science, covering topics such as variable assignment, conditional statements, data types, functions, and loops. It emphasizes the importance of readability and clarity in code, while also introducing built-in functions and methods for working with data structures like lists and dictionaries. Additionally, it touches on operator overloading and best practices for importing libraries and exploring unknown objects.

Uploaded by

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

🐍 Python for Data Science – Basics Summary

🔰 Introduction
 Course assumes some coding experience.
 Covers Python syntax, variables, arithmetic, and basic functions.

📌 Python Basics
✅ Variable Assignment
python
CopyEdit
spam_amount = 0
 = is the assignment operator.
 No need to declare type or initialize variables beforehand.
✅ Print Function
python
CopyEdit
print(spam_amount)
 print() outputs to console.
✅ Comments
python
CopyEdit
# This is a comment
✅ Reassignment and Arithmetic
python
CopyEdit
spam_amount = spam_amount + 4
 You can reassign variables using arithmetic expressions.

🔁 Conditional Statements
python
CopyEdit
if spam_amount > 0:
print("But I don't want ANY spam!")
 if starts a code block (indentation matters!).
 Colons : signal the start of an indented block.

🧵 Strings and Operators


python
CopyEdit
viking_song = "Spam " * spam_amount
print(viking_song)
 Strings can be repeated using *.
 Operator overloading allows * to work with strings and numbers.

🔢 Data Types
python
CopyEdit
type(0) → int
type(19.95) → float
 int: whole numbers
 float: decimals
 type() checks data type

➕ Arithmetic Operators

Operat Example (a = 5, Resul


Name
or b = 2) t

+ Addition a+b→7

- Subtraction a - b → 3

Multiplicatio
* a * b → 10
n

/ True Division a / b → 2.5 Float

Floor
// a // b → 2 Int
Division

% Modulus a%b→1

** Exponentiati a ** b → 25
Operat Example (a = 5, Resul
Name
or b = 2) t

on

-a Negation -a → -5

🧠 Order of Operations (PEMDAS)


python
CopyEdit
total = (hat_height + my_height) / 100
 Use parentheses () to control calculation order.

🛠 Built-in Functions
 min(a, b, c): Smallest value
 max(a, b, c): Largest value
 abs(x): Absolute value
 int(): Converts to integer
 float(): Converts to float
python
CopyEdit
int('807') + 1 → 808

----------

🧠 Functions in Python – Short Notes


📘 Getting Help in Python
 help() is a built-in function used to get documentation about other
functions.
 Example:
python
CopyEdit
help(round)
 Avoid calling the function inside help (e.g., help(round())); pass the
function name, not its result.

🔧 Understanding Function Signatures


 round(number, ndigits=None)
o number: required argument

o ndigits: optional, defaults to None

 print(value, ..., sep=' ', end='\n', file=[Link], flush=False)


o Has multiple optional keyword arguments.

Defining Functions
 Syntax:
python
CopyEdit
def function_name(parameters):
# block of code
return result
 Example:
python
CopyEdit
def least_difference(a, b, c):
return min(abs(a-b), abs(b-c), abs(a-c))

📄 Docstrings
 Description added just after function definition using triple quotes """.
 Helps describe what the function does.
 Example:
python
CopyEdit
def greet():
"""This function prints a greeting."""
print("Hello!")
 help(greet) will now show the docstring.

❌ Functions Without return


 If no return is specified, function returns None.
 Used when function has side effects like print().

🧩 Default Arguments
 Provide default values to parameters:
python
CopyEdit
def greet(who="Colin"):
print("Hello,", who)
 Can override defaults by passing arguments:
python
CopyEdit
greet("Kaggle") # Output: Hello, Kaggle

🔁 Functions as Arguments
 You can pass functions as arguments to other functions.
 Example:
python
CopyEdit
def call(fn, arg):
return fn(arg)
 Higher-order functions: functions that take other functions as inputs or
return them.

📈 Using key with max()


 max() can take a key function to determine comparison basis:
python
CopyEdit
def mod_5(x):
return x % 5

max(100, 51, 14, key=mod_5) # Returns 14

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

🟩 Booleans in Python
 bool type has two values: True and False
 Created by:
python
CopyEdit
x = True
type(x) # <class 'bool'>

🟨 Comparison Operators

Operati
Meaning
on

a == b a equals b

a != b a not equal to b

a<b a less than b

a>b a greater than b

a less than or equal to


a <= b
b

a greater than or equal


a >= b
to b

Examples:
python
CopyEdit
'3' == 3 # False
3.0 == 3 # True

🟧 Functions Using Comparisons


python
CopyEdit
def can_run_for_president(age):
return age >= 35

🟥 Modulus and Boolean Use Case


python
CopyEdit
def is_odd(n):
return (n % 2) == 1
❗ Use == for comparison, not =

🟦 Combining Boolean Values


 Use: and, or, not
python
CopyEdit
def can_run_for_president(age, is_natural_born_citizen):
return is_natural_born_citizen and (age >= 35)
Order of operations:
 not > and > or
✔ Use parentheses to clarify precedence.

🟪 Example: Weather Preparedness


python
CopyEdit
prepared_for_weather = (
have_umbrella
or ((rain_level < 5) and have_hood)
or (not (rain_level > 0 and is_workday))
)

🟫 Conditionals (if, elif, else)


python
CopyEdit
def inspect(x):
if x == 0:
print("zero")
elif x > 0:
print("positive")
else:
print("negative")
 Use colons : and indentation to define blocks
 elif = “else if”; optional and repeatable

🟥 Boolean Conversion
python
CopyEdit
bool(1) # True
bool(0) # False
bool("hi") # True
bool("") # False
 Non-zero numbers and non-empty strings/lists → True
 0, "", [], etc. → False
Used implicitly:
python
CopyEdit
if 0:
print("won’t run")
elif "spam":
print("spam") # This prints

✅ Lists
 Definition: Ordered, mutable collections.
 Creation:
python
CopyEdit
primes = [2, 3, 5, 7]
 Types: Can contain any data type, even other lists.
 Indexing:
o list[0] – first element

o list[-1] – last element

 Slicing:
o list[start:end] – elements from start to end-1

o list[:3], list[3:], list[1:-1], etc.

 Mutability:
o Lists can be modified using assignment:

python
CopyEdit
planets[3] = 'Malacandra'
planets[:3] = ['Mur', 'Vee', 'Ur']
 Useful Functions:
o len(), sorted(), sum(), min(), max()

 Common Methods:
o append() – adds to the end

o pop() – removes and returns the last item

o index() – finds the index of an item

o in operator – checks membership

🧠 Objects & Methods


 Objects: Everything in Python is an object.
 Attributes: Non-function properties (e.g., [Link])
 Methods: Functions attached to objects (e.g., x.bit_length())

📦 Tuples
 Definition: Ordered, immutable collections.
 Creation:
python
CopyEdit
t = (1, 2, 3)
t = 1, 2, 3 # same
 Immutability:
o Cannot change elements (t[0] = 100 → ❌ TypeError)

 Use case: Often used to return multiple values from a function.


python
CopyEdit
x = 0.125
numerator, denominator = x.as_integer_ratio()

🔁 Loops Overview
Loops allow repeated execution of code.

🪐 for Loop
python
CopyEdit
planets = ['Mercury', 'Venus', 'Earth', ...]
for planet in planets:
print(planet, end=' ')
 Iterates over items in any iterable: list, tuple, string, etc.
 Structure: for <var> in <iterable>:

🧮 Looping Over Other Types


python
CopyEdit
# Tuple
multiplicands = (2, 2, 2, 3, 3, 5)
product = 1
for mult in multiplicands:
product *= mult # 360

# String
s = 'someText'
for char in s:
if [Link]():
print(char, end='')
 Works with tuples, strings, or anything that supports iteration.

🔢 range()
python
CopyEdit
for i in range(5):
print(i)
 Produces numbers from 0 to n-1
 Can also use range(start, stop, step)

🔁 while Loop
python
CopyEdit
i=0
while i < 10:
print(i)
i += 1
 Repeats while the condition is True.

🔄 List Comprehensions
Compact way to create lists.
python
CopyEdit
squares = [n**2 for n in range(10)]
# Equivalent to:
squares = []
for n in range(10):
[Link](n**2)
With condition:
python
CopyEdit
short_planets = [planet for planet in planets if len(planet) < 6]
With transformation + condition:
python
CopyEdit
[[Link]() + '!' for planet in planets if len(planet) < 6]

🔍 List Comprehension as Filtering/Counting Tool


python
CopyEdit
def count_negatives(nums):
return len([num for num in nums if num < 0])
Or even:
python
CopyEdit
def count_negatives(nums):
return sum([num < 0 for num in nums])
(Because True is 1 and False is 0 in Python.)

🧘‍♂️Final Advice (from Zen of Python)


 Readability counts.
 Explicit is better than implicit.
Use concise tools like comprehensions—but always prefer clarity.

Strings
Definition & Syntax
 Can be enclosed in single or double quotes:
python
CopyEdit
'hello' == "hello"
 Use escaping (\) to include quotes or special characters:
\', \", \\, \n (newline)
Multi-line & Print
 Triple-quoted strings allow literal newlines:
python
CopyEdit
"""line1
line2"""
 print(..., end='') prevents auto-newline
Sequence behavior
 Support indexing, slicing, len(), iteration
 Immutable – cannot change in place
Common methods
 .upper(), .lower()
 .index(sub), .startswith(prefix), .endswith(suffix)
Splitting & Joining
 .split() → list of words
 [Link](list) → string with sep between items
Formatting
 Concatenate with +, but better:
python
CopyEdit
"{} weighs about {:.2} kg".format(var, num)
 Supports positional formatting, number formatting, commas, percent,
exponents

Dictionaries
Definition
 Key→value mappings:
python
CopyEdit
d = {'one': 1, 'two': 2}
Access & Modify
 Access via d[key]; add/change via assignment:
python
CopyEdit
d['three'] = 3
Comprehensions
 Create dicts from iterables:
python
CopyEdit
{p: p[0] for p in planets}
Membership & Iteration
 key in d checks presence
 Looping iterates keys:
python
CopyEdit
for k in d:
print(k, d[k])
Convenient methods
 .keys(), .values(), .items() for keys, values, and key-value pairs
 Use .items() to loop with unpacking:
python
CopyEdit
for k, v in [Link]():
...

🚀 Imports in Python
 Standard vs. external libraries:
o Standard library modules (like math) are built-in.

o External packages (e.g., numpy, pandas) can be installed via pip.

 Import syntax:
python
CopyEdit
import math
import math as mt # alias
from math import log, pi # specific names
from math import * # discouraged: can cause name conflicts
 Why avoid import *:
o Overwrites names from other modules

o Harder to track name origins and debug

 Submodules:
o Modules can contain other modules:

python
CopyEdit
[Link](...)

🔍 Exploring Unknown Library Objects


When working with unfamiliar objects (e.g., [Link]), use these tools:
1. type(obj) → shows class/type
2. dir(obj) → lists attributes and methods
3. help(obj) → detailed documentation
Example:
python
CopyEdit
rolls = [Link](...)
type(rolls) # → [Link]
dir(rolls) # → methods like mean(), shape
help([Link]) # explains what it does

✨ Operator Overloading
 Python allows custom behavior for operators (+, <, in, etc.) via special
methods like __add__, __lt__, __contains__.
 Example differences:
o Lists: [1,2,3] + 10 → error

o NumPy arrays: array + 10 → adds 10 to every element

o TensorFlow Tensor: a + b → returns symbolic tensor, not immediate


value
 Overloaded operators make expressions intuitive (e.g., df[(df['pop'] > 1e6)
& (df['continent']=='SA')]), but they can hide complex behaviors.
🧭 Takeaways
 Use explicit imports and clear aliases to avoid conflicts.
 Explore unknown types with type(), dir(), help().
 Be aware that operators might behave differently depending on the object
(due to overloading).
 As you work with third-party libraries, learning these tools will help you
navigate and debug code effectively.

Common questions

Powered by AI

List and dictionary comprehensions in Python streamline data-processing by enabling concise syntax for creating and transforming collections. For example, 'short_planets = [planet.upper() + '!' for planet in planets if len(planet) < 6]' uses a list comprehension to filter and transform planets based on length. Similarly, a dictionary comprehension like '{p: len(p) for p in planets}' maps each planet to its length. These techniques enhance readability and performance, crucial for efficient data handling .

In Python, variable assignment is straightforward; you assign a value to a variable using the '=' operator without needing to declare the type or initialize beforehand. Reassignment is similar and supports arithmetic operations within the assignment, such as 'spam_amount = spam_amount + 4'. This flexibility allows for rapid prototyping and iterative testing, crucial in data science where datasets and analytical requirements may change quickly .

The 'help()' function in Python is crucial for improving programming efficiency by providing immediate access to function documentation, including parameter descriptions and usage examples. This is particularly valuable in collaborative projects where understanding different parts of a codebase quickly is crucial. For example, using 'help(greet)' can display the function’s docstring, explaining its purpose and usage. This can reduce onboarding time for new team members and aid in debugging by making function intentions clear .

Default arguments in Python functions allow you to specify default values for parameters, streamlining function calls when standard values suffice. This is particularly useful in data science where scripts might use common default configurations often. For instance, 'def greet(who="Colin"): print("Hello,", who)' allows 'greet()' to work without explicitly passing 'who', unless a different value is needed, thus enhancing flexibility and reducing redundant code .

List comprehensions in Python offer a concise and efficient way to generate and manipulate lists by applying filtering and transformations in a single, readable line of code. For instance, '[planet for planet in planets if len(planet) < 6]' generates a list of planets with names shorter than 6 characters. This method is not only succinct but also improves performance, especially beneficial in data manipulation tasks common in data science .

Higher-order functions, which either take other functions as arguments or return them, improve code modularity by enabling function reuse and separation of concerns. For instance, 'def call(fn, arg): return fn(arg)' allows execution of any function 'fn' with 'arg'. This abstraction makes code more flexible and modular, as different behavior can be passed around systematically, fostering a more maintainable codebase .

Boolean conversion simplifies decision-making by evaluating non-Boolean expressions as True or False, allowing their use in logical operations. In an 'if' statement, anything non-zero or non-empty evaluates to True. For instance, 'if 0:' will not execute, whereas 'elif "spam":' will, as non-empty strings evaluate to True. Such conversions allow more readable and efficient code by reducing explicit condition checks, enhancing decision processes in complex logic .

Tuples in Python are immutable ordered collections which makes them ideal for function outputs when the returning data shouldn't be modified. This immutability ensures data integrity when functions return multiple values. For example, using 'numerator, denominator = x.as_integer_ratio()' returns a tuple, ensuring ratio components remain unchanged. Compared to lists, tuples provide a level of protection against unintended data modifications, which is valuable in ensuring consistent outputs from functions .

Conditional statements in Python are uniquely characterized by the use of 'if', 'elif', and 'else' keywords, along with a colon ':' to signal the start of an indented block. Indentation is crucial as it defines the scope of the code block. For example, in 'if spam_amount > 0: print("But I don't want ANY spam!")', the conditional checks if 'spam_amount' is greater than zero, and if so, executes the print statement within the indented block .

Python uses operator overloading to extend the functionality of traditional operators beyond numerical calculations. For instance, the '*' operator in Python can multiply numbers but also repeat strings. For example: 'viking_song = "Spam " * spam_amount'. Here, 'viking_song' repeats the string 'Spam ' a number of times specified by 'spam_amount', demonstrating the versatility and power of operator overloading .

You might also like