Understanding Data Types and String Manipulation
Today Goal:
Hello and welcome to the tip calculator.
How much was the whole bill? Rs. 1024.54
How many people will be splitting the bill? 5
What percentage tip do you want to give? 10, 12, or 15? 12
Each person should pay? Rs. 229.5
πBasic Data Types in Python
Python has several Basic data types, which are the basic building blocks for representing and manipulating data. The primitive data types in Python include:
Integer (int): This data type represents whole numbers without any fractional or decimal part. For example, 5, -2, 0 are integers.
x = 5 y = -10
Float (float): This data type represents decimal numbers or numbers with a fractional part. For example, 3.14, -0.5, 2.0 are floats.
pi = 3.14 temperature = 98.6
Boolean (bool): This data type represents True or False truth values. It is used for logical operations and control flow. For example, True, False are booleans.
is_raining = True has_car = False
String (str): This data type represents a sequence of characters enclosed in single quotes (' ') or double quotes (" "). For example, "hello", 'Python' are strings.
name = "Alice" message = 'Hello, world!'
List (list): Lists are ordered collections of items, which can be of different data types. They are denoted by square brackets [].
numbers = [1, 2, 3, 4, 5] fruits = ["apple", "banana", "orange"] mixed_list = [10, "hello", True]
Tuple (tuple): Tuples are similar to lists, but they are immutable, meaning their values cannot be changed once assigned. They are denoted by parentheses ().
coordinates = (3, 4)
person = ("Alice", 25, "New York")
- Dictionary (dict): Dictionaries are unordered collections of key-value pairs. They are denoted by curly braces {}.
student = {"name": "Alice", "age": 20, "grade": "A"}
car = {"brand": "Toyota", "model": "Camry", "year": 2020}
π Type Error, Type Checking and Type Conversion
Type Error: A type error occurs when an operation is performed on a value of an inappropriate data type. For example, trying to concatenate a string with an integer would result in a type error because they are incompatible types for that operation.
x = "Hello"
y = 42
result = x + y # This will raise a TypeError
Type Checking: Type checking is the process of verifying the data type of a value in a programming language. In Python, you can use the type()
function to determine the type of a variable or value.
x = 5
y = "Hello"
print(type(x)) # Output: <class 'int'>
print(type(y)) # Output: <class 'str'>
Type Conversion: Type conversion, also known as type casting, is the process of converting a value from one data type to another. Python provides built-in functions to convert between different data types.
# Integer to float
x = 5
y = float(x)
print(y) # Output: 5.0
# Float to integer
a = 3.14
b = int(a)
print(b) # Output: 3
# Integer to string
num = 10
text = str(num)
print(text) # Output: "10"
# String to integer
num_str = "20"
num_int = int(num_str)
print(num_int) # Output: 20
π Mathematical Operations in Python
Python provides several mathematical operations that can be performed on numerical data types. Here are some commonly used mathematical operations in Python:
Addition (+): Adds two values together.
x = 5 + 3
print(x) # Output: 8
Subtraction (-): Subtracts one value from another.
y = 10 - 2
print(y) # Output: 8
Multiplication (*): Multiplies two values.
z = 4 * 6
print(z) # Output: 24
Division (/): Divides one value by another. The result is a float.
a = 10 / 3
print(a) # Output: 3.3333333333333335
Floor Division (//): Divides one value by another and rounds the result down to the nearest whole number. The result is an integer.
b = 10 // 3
print(b) # Output: 3
Modulo (%): Returns the remainder of the division between two values.
c = 10 % 3
print(c) # Output: 1
Exponentiation (**): Raises a value to the power of another value.
d = 2 ** 3
print(d) # Output: 8
Increment and Decrement (+= and -=): Adds or subtracts a value from a variable and updates the variable with the result.
x = 5
x += 3 # Equivalent to x = x + 3
print(x) # Output: 8
y = 10
y -= 2 # Equivalent to y = y - 2
print(y) # Output: 8
These are some of the basic mathematical operations in Python.
π Number Manipulation and F strings in Python
Python provides several built-in functions and modules for number manipulation. Here are some commonly used techniques:
Absolute Value (abs()): Returns the absolute value of a number.
x = -10
y = abs(x)
print(y) # Output: 10
Round (round()): Rounds a floating-point number to a specified number of decimal places.
a = 3.14159
b = round(a, 2)
print(b) # Output: 3.14
Maximum and Minimum (max() and min()): Returns the largest or smallest number from a sequence of numbers.
numbers = [5, 2, 8, 1, 10]
max_num = max(numbers)
min_num = min(numbers)
print(max_num) # Output: 10
print(min_num) # Output: 1
Random Number Generation (random module): The random module provides functions for generating random numbers.
import random
# Generate a random integer between 1 and 10
random_number = random.randint(1, 10)
print(random_number)
F-strings in Python: F-strings, introduced in Python 3.6, provide a concise way to format strings that include variables or expressions. You can include the variable or expression directly within curly braces {} inside the string.
name = "Alice"
age = 25
# Using f-string to format a string
message = f"My name is {name} and I am {age} years old."
print(message)
F-strings allow you to embed variables and expressions directly within a string, making it easier to construct dynamic strings without the need for string concatenation or formatting functions.
x = 10
y = 20
# Performing arithmetic operation within f-string
result = f"The sum of {x} and {y} is {x + y}."
print(result)
F-strings support a wide range of expressions, including function calls, mathematical operations, and even complex expressions. They are a convenient and readable way to construct formatted strings in Python.
Complete the Second Assignment based on what you've learned so far.
#If the bill was Rs. 1500.00, split between 5 people, with 12% tip.
#Each person should pay (1500.00 / 5) * 1.12 = 336 #Format the result to 2 decimal places = 336.0
#Tip: There are 2 ways to round a number. You might have to do some Googling to solve this.πͺ
#Write your code below this line π
Solution:
print("Hello and welcome to the tip calculator.")
bill = float(input("How much was the whole bill? Rs."))
people = int(input("How many people will be splitting the bill?"))
tip = float(input("What percentage tip do you want to give? 10, 12, or 15?"))
tips_as_percentage = tip / 100
total_tip_amount = bill * tips_as_percentage
total_bill = bill + total_tip_amount
bill_per_person = total_bill / people
final_amount = round(bill_per_person, 2)
print(f"Each person should pay?: Rs.{final_amount}")
Output:
Hello and welcome to the tip calculator.
How much was the whole bill? Rs. 1024.54
How many people will be splitting the bill? 5
What percentage tip do you want to give? 10, 12, or 15? 12
Each person should pay? Rs. 229.5
If you miss The 100 days of the Python - Day - 01 see here
#100DaysofCode #Python