0% found this document useful (0 votes)
0 views

lab1python

The document is a Python script that demonstrates various programming concepts, including variable types, conditional statements, mathematical calculations, and data handling using pandas. It includes functionalities like calculating the area and perimeter of a rectangle, finding roots of a quadratic equation, and processing customer data. The script also showcases user input handling and basic data manipulation techniques.

Uploaded by

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

lab1python

The document is a Python script that demonstrates various programming concepts, including variable types, conditional statements, mathematical calculations, and data handling using pandas. It includes functionalities like calculating the area and perimeter of a rectangle, finding roots of a quadratic equation, and processing customer data. The script also showcases user input handling and basic data manipulation techniques.

Uploaded by

trinh123profc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 5

# -*- coding: utf-8 -*-

"""Demo1.ipynb

Automatically generated by Colab.

Original file is located at


https://colab.research.google.com/drive/1NbmVYhlX5_4syMfz5PXPLvywSoxc0jfJ
"""

import random
luckyStudent = random.randint(1,65)
print(f"Lucky Student - (luckyStudent)")

# Variables: number - integer, decimal,...; string; boolean; datetime,...


name, nickName, age, score = "Binh", "John", 20, 8.0

print(f"Hello. My name is",name,"(Type - ",type(name),")")


print(f"Hello. My nickname is",nickName,"(Type - ",type(nickName),")")
print("I'm",age,"years old","(Type - ",type(age),")")
print("My score is",score,"(Type - ",type(score),")")

print(f"Hello. My name is {name} (Type - {type(name)})")


print(f"My nick name is '{nickName}'. (Type - {type(nickName)})")
print(f"I'm {age} years old (Type - {type(age)})")
print(f"My score is {score} (Type - {type(score)})")

a=4
b=5
a,b = b,a
print(a,b)

width = int(input("Nhập chiều dài hình chữ nhật: "))


height = int(input("Nhập chiều rộng hình chữ nhật: "))

perimeter = 2 * (width + height)


area = width * height

print(f"Chu vi hình chữ nhật là: {perimeter}")


print(f"Diện tích hình chữ nhật là: {area}")

cm = float(input("Nhập cm: "))

dm = cm / 10

inch = cm * 0.393701

print(f"Chiều dài dm là: {dm} dm")


print(f"chiều dài inches là: {inch:} inches")

import random

number = random.randint(10, 999)


print(f"Con số được tạo ra là: {number}")

if 10 <= number <= 99:


print("Số này là số có 2 chữ số.")
elif 100 <= number <= 999:
print("Số này là số có 3 chữ số.")
else:
print("số này không phải 2 chữ số không phải 3 chữ số")

import random

number = random.randint(-100, 100)


print(f"Số ngẫu nhiên được tạo là: {number}")

if number > 0:
print("Đây là số dương.")
elif number < 0:
print("Đây là số âm")
else:
print("Đây là số 0.")

if 10 <= abs(number) <= 99:


print("Số này có 2 chữ số.")
else:
print("Số này không có 2 chữ số")

import random

number = random.randint(10, 150)


print(f"Số ngẫu nhiên được tạo là: {number}")

normalized_number = (number - 10) / (150 - 10)

print(f"Số được chuẩn hóa trong khoảng [0, 1] là: {normalized_number:.2f}")

import math

def calculate_angle(hour, minute):

hour = hour % 12

hour_angle = (360 / 12) * hour + (360 / 12 / 60) * minute


minute_angle = (360 / 60) * minute

angle_in_degree = abs(hour_angle - minute_angle)

angle_in_degree = min(angle_in_degree, 360 - angle_in_degree)

angle_in_radian = math.radians(angle_in_degree)

return angle_in_degree, angle_in_radian

hour = int(input("Nhập giờ (0-23): "))


minute = int(input("Nhập phút (0-59): "))

# Calculate the angles


degree, radian = calculate_angle(hour, minute)
# Output the result
print(f"Góc giữa kim giờ và kim phút là: {degree:.2f}° (degrees)")
print(f"Góc giữa kim giờ và kim phút là: {radian:.2f} radians")

import math

a = 1
b = 5
c = 6

print(f"Quadratic equation: {a}x^2 + {b}x + {c} = 0")

discriminant = b**2 - 4*a*c


print(f"Step 2: Discriminant (Δ) = b^2 - 4ac = {b}^2 - 4*{a}*{c} = {discriminant}")

if discriminant > 0:
print("Step 3: Discriminant > 0, so the equation has two distinct real roots.")

root1 = (-b + math.sqrt(discriminant)) / (2 * a)


root2 = (-b - math.sqrt(discriminant)) / (2 * a)
print(f"Step 4: Roots are calculated as:")
print(f"x1 = (-b + √Δ) / 2a = ({-b} + √{discriminant}) / (2*{a}) =
{root1:.2f}")
print(f"x2 = (-b - √Δ) / 2a = ({-b} - √{discriminant}) / (2*{a}) =
{root2:.2f}")
elif discriminant == 0:
print("Step 3: Discriminant = 0, so the equation has one real root (double
root).")

root = -b / (2 * a)
print(f"Step 4: Root is calculated as:")
print(f"x = -b / 2a = {-b} / (2*{a}) = {root:.2f}")
else:
print("Step 3: Discriminant < 0, so the equation has two complex roots.")

real_part = -b / (2 * a)
imaginary_part = math.sqrt(abs(discriminant)) / (2 * a)
print(f"Step 4: Roots are calculated as:")
print(f"x1 = {-b} / (2*{a}) + i√{abs(discriminant)} / (2*{a}) = {real_part:.2f}
+ {imaginary_part:.2f}i")
print(f"x2 = {-b} / (2*{a}) - i√{abs(discriminant)} / (2*{a}) = {real_part:.2f}
- {imaginary_part:.2f}i")

text = "Today is Sunday and we don't need to wake up at 6 am"

words = text.split()
word_count = len(words)
print(f"Step 1: The total number of words in the string is: {word_count}")

has_number = False
for index, word in enumerate(words):
if word.isdigit():
has_number = True
print(f"Step 2: Found a number '{word}' at position {index + 1} (1-based
index)")

if not has_number:
print("Step 2: No numbers were found in the string.")

name = input("Enter the name of the student: ")


dob = input("Enter the date of birth (e.g., YYYY-MM-DD): ")

subject1 = input("Enter the name of Subject 1: ")


mark1 = float(input(f"Enter the mark for {subject1}: "))

subject2 = input("Enter the name of Subject 2: ")


mark2 = float(input(f"Enter the mark for {subject2}: "))

subject3 = input("Enter the name of Subject 3: ")


mark3 = float(input(f"Enter the mark for {subject3}: "))

average_mark = (mark1 + mark2 + mark3) / 3

print("\n=== Student Profile ===")


print(f"Name: {name}")
print(f"Date of Birth: {dob}")
print(f"{subject1}: {mark1}")
print(f"{subject2}: {mark2}")
print(f"{subject3}: {mark3}")
print(f"Average Mark: {average_mark:.2f}")

import math

x1, y1 = map(float, input("Enter coordinates of Point 1 (x1 y1): ").split())


x2, y2 = map(float, input("Enter coordinates of Point 2 (x2 y2): ").split())

euclidean_distance = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)


print(f"Euclidean Distance: {euclidean_distance:.2f}")

manhattan_distance = abs(x2 - x1) + abs(y2 - y1)


print(f"Manhattan Distance: {manhattan_distance:.2f}")

dot_product = x1 * x2 + y1 * y2
magnitude_p1 = math.sqrt(x1**2 + y1**2)
magnitude_p2 = math.sqrt(x2**2 + y2**2)

if magnitude_p1 == 0 or magnitude_p2 == 0:
cosine_distance = 1.0
print("Cosine Distance: Undefined (division by zero). Assuming 1.")
else:
cosine_similarity = dot_product / (magnitude_p1 * magnitude_p2)
cosine_distance = 1 - cosine_similarity
print(f"Cosine Distance: {cosine_distance:.2f}")
from datetime import datetime

birthday_str = input("Enter your birthday (format: DD-MM-YYYY): ")


birthday = datetime.strptime(birthday_str, "%d-%m-%Y")

weekday_name = birthday.strftime("%A")
month_name = birthday.strftime("%B")

today = datetime.now()
age = today.year - birthday.year
if (today.month, today.day) < (birthday.month, birthday.day):
age -= 1

print("\n=== Your Birthday Information ===")


print(f"Weekday Name: {weekday_name}")
print(f"Month Name: {month_name}")
print(f"Your Age: {age} years old")

import pandas as pd

customers = input("Enter the list of customers (comma-separated): ").split(",")


products = input("Enter the list of products (comma-separated): ").split(",")
quantity_list = input("Enter the list of quantities (comma-separated, e.g., '2kg,
3kg'): ").split(",")

data = {
'Customer': customers,
'Product': products,
'QuantityList': quantity_list
}

df = pd.DataFrame(data)

df[['Quantity', 'Unit']] = df['QuantityList'].str.extract(r'(\d+)(\D+)')

df['Quantity'] = pd.to_numeric(df['Quantity'])

pork_customers = df[(df['Product'] == 'Pork') & (df['Quantity'] > 2)]

print("\n=== DataFrame ===")


print(df)

print("\n=== Customers who bought Pork over 2kg ===")


print(pork_customers[['Customer', 'Quantity', 'Unit']])

You might also like