Python Course
Python comes with several built-in data types. These are used to define the type of data that a variable holds.
Python automatically detects the type when you assign a value to a variable (thanks to dynamic typing).
Common Data Types
Type Example Description int 10 Integer float 10.5 Decimal number str "Hello" Text string bool True, False Boolean (True/False)
- int: Used to store whole numbers (positive, negative, or zero).
- float: Used for numbers with decimal points.
- str: A sequence of characters enclosed in quotes (single or double).
- bool: Represents logical values — True or False.
Let's see some examples,
age = 25 # int price = 19.99 # float name = "Praveen" # str is_member = True # bool
Type Checking
You can check the type of any variable using the type() function:
print(type(age)) # <class 'int'> print(type(price)) # <class 'float'> print(type(name)) # <class 'str'> print(type(is_member)) # <class 'bool'>
Let's see an example for dynamic typing.
x = 10 # int x = "Ten" # str — Python allows this
Type Conversion
Used to convert from one data type to another.
int("10") # Converts string to integer float("3.14") # Converts string to float str(100) # Converts integer to string
Let's see some examples.
print(int(14/3)) # It prints 4 and it just skips the decimal part print(round(14/3)) # It prints 5 by rounding off print(round(14/3,2)) # It prints 4.67 by rounding off to 2 decimals print(int('100', 2)) # It prints 4 by converting binary '100' to decimal print(10 // 3) # It prints 3, which is integer division (floor division) print(10 % 3) # It prints 1, which is the remainder (modulus) print(2 ** 3) # It prints 8, which is 2 raised to the power 3 print(float(5)) # It prints 5.0 by converting integer to float print(int("7")) # It prints 7 by converting string to int print(str(123)) # It prints "123" by converting int to string print(type(3.14)) # It prints <class 'float'> print(isinstance(5, int)) # It prints True because 5 is an integer print("hello".capitalize()) # It prints "Hello" with first letter capitalized print("python".upper()) # It prints "PYTHON" in uppercase print("test"[1:3]) # It prints "es" (substring from index 1 to 2) print("data" * 2) # It prints "datadata" by repeating the string print(True and False) # It prints False because both are not True print(True or False) # It prints True because at least one is True print(not True) # It prints False because it's the opposite of True print(5 > 3) # It prints True since 5 is greater than 3
Decimal
When working with money or financial values in Python, it's best to use the Decimal type from the decimal module instead of float, to avoid rounding errors caused by floating-point precision issues.
Why Use Decimal for Money?
Floating-point numbers can lead to inaccurate results in financial calculations:
print(0.1 + 0.2) # It prints 0.30000000000000004 – not good for money!
With Decimal, it's precise and accurate:
from decimal import Decimal print(Decimal('0.1') + Decimal('0.2')) # It prints 0.3 – perfect!
Let's see more examples.
from decimal import Decimal, ROUND_HALF_UP # Define money amounts precisely price = Decimal('19.99') tax = Decimal('1.50') total = price + tax print(total) # It prints 21.49 – accurate sum of money # Rounding to 2 decimal places (like dollars and cents) discounted = total.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP) print(discounted) # It prints 21.49 # Applying a discount discount = Decimal('5.00') final_price = total - discount print(final_price) # It prints 16.49 # Multiplying (e.g., 3 items) quantity = 3 subtotal = price * quantity print(subtotal) # It prints 59.97
Let's see getcontext() from Python's decimal module.
What is getcontext()?
The getcontext() function is part of the decimal module in Python. It retrieves the current context used by all Decimal operations.
This context includes:
- Precision (how many digits to keep)
- Rounding mode
- Flags and traps for arithmetic conditions (e.g., division by zero)
It's like a global setting that controls how all Decimal math behaves.
Let's see an example.
from decimal import Decimal, getcontext, ROUND_HALF_UP # Set global context for financial calculations ctx = getcontext() ctx.prec = 10 # total digits of precision ctx.rounding = ROUND_HALF_UP # standard rounding (0.5 rounds up) # Prices of items in the cart item_1 = Decimal('19.99') item_2 = Decimal('5.75') item_3 = Decimal('3.40') # Calculate subtotal subtotal = item_1 + item_2 + item_3 print("Subtotal:", subtotal) # Exact subtotal # Apply tax (e.g., 8.5%) tax_rate = Decimal('0.085') tax_amount = (subtotal * tax_rate).quantize(Decimal('0.01')) print("Tax:", tax_amount) # Apply discount (e.g., $5.00) discount = Decimal('5.00') final_total = (subtotal + tax_amount - discount).quantize(Decimal('0.01')) print("Final Total:", final_total)
String
A string in Python is a sequence of characters enclosed in either single quotes ' or double quotes ".
name = "Praveen" greeting = 'Hello'
Strings are used to represent:
- Words and sentences
- User input (names, emails, etc.)
- File paths, URLs, commands
- Anything text-based
Strings are immutable, which means once created, they cannot be changed — but we can create modified versions using string functions.
Basic String Characteristics
s = "Hello, World!" print(type(s)) # <class 'str'> print(len(s)) # 13 – total number of characters print(s[0]) # 'H' – indexing (0-based) print(s[-1]) # '!' – negative index (from end) print(s[0:5]) # 'Hello' – slicing
Common String Functions
str.lower() / str.upper()
email = "UsEr@Example.COM" print(email.lower()) # 'user@example.com' – normalize for comparison
str.strip()– Removes whitespace
name = " Praveen " print(name.strip()) # 'Praveen' – clean input fields
str.replace(old, new)– Replace parts of string
text = "Price: $100" print(text.replace("$", "")) # 'Price: 100' – useful for currency cleaning
str.find()– Find position (returns -1 if not found)
email = "user@example.com" if email.find("@") != -1: print("Looks like a valid email")
str.split()– Split a string into a list
data = "Praveen,Oruganti,39" parts = data.split(",") print(parts) # ['Praveen', 'Oruganti', '39']
str.join()– Join list into a string
words = ["apple", "banana", "cherry"] sentence = ", ".join(words) print(sentence) # 'apple, banana, cherry'
str.startswith() / str.endswith()
filename = "report.pdf" print(filename.endswith(".pdf")) # True – file type validation
str.isdigit() / str.isalpha() / str.isalnum()
age = "39" print(age.isdigit()) # True – check if all characters are digits
str.capitalize() / str.title()
name = "praveen oruganti" print(name.title()) # 'Praveen Oruganti' – used for display
str.zfill(width)– Pad numbers with zeros
invoice_id = "45" print(invoice_id.zfill(6)) # '000045' – standardized invoice format