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

Lesson 1 Python Basics

Uploaded by

Lan Chi Vũ
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Lesson 1 Python Basics

Uploaded by

Lan Chi Vũ
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

HANOI UNIVERSITY OF SCIENCE AND PYTHON APPLICATION PRACTICE

TECHNOLOGY
SCHOOL OF ECONOMICS

PRACTICE 3.1

BASIC APPLICATIONS OF PYTHON


The practice helps learners get acquainted with the basic concepts of Python, thinking in a coherent
logical flow.

Product The experiment includes the Condition


following main contents
Jupyter notebook
- Variables and data types.
Levels Functions and basic Notes
Beginners commands Students need to set up
- Conditional sentence python environment
Subject
structure
Basic Queries
Author - Loops (for, while)
Pham Thi Thanh - Import and use libraries
Hong (numpy, pandas, matplotlib
Nguyen Dac Viet Ha and others)

Version Last updated


1.0 March 08, 2024
Exercise 1: Variables, data types, and mathematical operations. Functions and
basic commands (be careful to comment with important lines of code)
Write a statement to perform some of the following tasks:
- Name and assign values to 3 variables, knowing that these variables have the following types
of values: string, integer, complex.
- Declare a list of 5 elements with all types of string data, integers, and complex numbers
- Print the value of the whole variable with the following format "The value of the 3 variables
is ... , ... and ...". Print out the final value of the list in the format "The final value of the list
is...". Print the value of the first 3 elements of the string using slice
- Add and remove one element to the list above with append, remove, insert
- Declare a list of 5 elements with values ranging from 1 to 5. Arrange that list in descending
order. Use the function len() to find out the length of the list
- Scan the list above and print the value of each element in the format "Element value is...".
Then scanning that list but only printing values > 2
- Scan the list and
o Print "Customer age is... - minor" for those elements <= 18
o Print "Customer Age is... - Youth " for those 19 to 30
o Print "Customer age is... - Middle age" for those elements 31 to 60
o Print "Other customers" for elements that do not fall into the above cases
o Breaking the for loop when encountering a value that does not fall in the above cases
- Declare a dictionaries with the following values: favorite_languages = {'jen': 'python', 'sarah':
'c', 'edward': 'ruby', 'phil': 'python'}. And a list has the following value: friend = ['edward',
'phil']
- Scan all the elements in the dictionaries above. If the key of an element is in a friend list,
proceed to print the value of that element in the format 'Hello..., your favorite programming
language is...'

Content 2: Declare the function


Write a statement to perform some of the following tasks:
- Create a person_introduction function with 2 input parameters, a person's first and last name.
Output prints the result "My name is..."
- Create a cal_age function with the input parameter being the year of birth and the output
being printing the age
- Create a max_value function with the input parameter being an integer list and the output
return the largest value in the list
- Create a odd_even function with the input parameter being an integer list and printout output
(Use):
o "The odd elements in the list are..."
o "The even parts of the list are..."
Instructions for performing the experiment
Content 1: Variables, data types, and mathematical operations. Functions and basic
commands (be careful to comment with important lines of code)

Step 1: Name and assign values to 3 variables

Step 2: Print the values of the variables according to the preset format. In which:
 print(...): This is the command to print the content to the screen.
 f'...': is a format-string, which allows you to insert the values of variables
directly into the string of characters. Variables or expressions need to be placed
in pairs of {}.
 {variable_1}, {variable_2}, and {variable_3}: are placeholders in the string
where the values of variable_1, variable_2, and variable_3 will be inserted
(these variables have been assigned values).

Step 3: Declare a list and use slicing


 Declaring list_1 and assigning its elements includes:
o 1 : an integer.
o 3.5: a decimal number (float).
o 'Hello world': a string.
o 3 : an integer.
o 6 : an integer.
 Print the last value in the list, list_1[4] access the 5th element in the list (the
index starts at 0, so the 5th element has an index of 4).
 list_1[0:3] is the slicing syntax in Python, used to take a subparagraph of a list.
o 0 is the starting indicator (first element).
o 3 is the end index (but the element at this index is not included).
Step 4: Use append, remove, and insert to add, edit, delete complaints in the list
List_1.append('test'):
 Description: This command uses the append() method to add a new element to
the end of the list_1 list.
 Result: After executing this command, the list_1 list will have an additional
'test' element at the end.
list_1.remove(1)
 Description: The remove() method is used to remove the first element with a
value equal to the input parameter (in this case, 1) from the list.
 Result: If list_1 contains element 1, this command removes it from the list.
list_1.insert(1, 'test')
 Description: The insert() method is used to insert a new element into a list at a
specific location. In this command, 'test' will be inserted where the indicator is
1.
 Result: The 'test' element will be added to the second position (since the index
starts at 0).

Step 5: Sort the list and find the length of the list

list_2.sort(reverse=True)
 Description: The sort() method is used to sort elements in a list. The
reverse=True parameter specifies that the list will be sorted in descending order
(from largest to smallest).
 Result: After executing this command, the list of list_2 will be sorted in
descending order

length_list = len(list_2)
 Description: The len() function is used to calculate the length (number of
elements) of a list_2 list and save the result to the length_list variable.
 Result: In this case, the list_2 list has 5 elements, so length_list will be
assigned a value of 5.

Step 6: Use a for loop with a list

for i in list_2:
 Description: This is a for loop used to iterate through each element in the list_2
list. In each iteration, the value of the current element in the list is assigned to
the variable i.
 Uses: This loop will perform operations (in this case, print) for each element in
the list_2 list.

When combined, the loop performs the following steps:


1. Iterate through each element of the list_2 list.
2. Assign the value of the current element to the variable i.
3. Print the value of the variable i with the message "Element value is {i}".
Step 7: Use for in combination with if, elif, else

customer_age = list(range(10,90,3))
 Description: Create a customer_age list containing integers from 10 to 90, with
a step of 3.
o range(10, 90, 3) produces a sequence of numbers starting at 10, ending
before 90, with a step of 3.
o list(...) converts this sequence of numbers into a list.

for age in customer_age:


 Description: Starts a for loop to iterate through each element in the
customer_age list. The variable age will take the value of each element in the
list at each loop.

If, elif, else conditions


 Description: In each loop, check the value of age and classify by age group:
o if age <= 18: If age is less than or equal to 18, print "underage".
o elif age <= 30:: If the age is greater than 18 but less than or equal to 30,
print out "youth".
o elif age <= 60:: If the age is greater than 30 but less than or equal to 60,
print "middle-aged".
o else:: If the age is greater than 60, the break command will stop the loop.
Step 8: Declare a dictionaries and use the for loop to print the key and value

favorite_languages = {'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil':


'python'}
 Description: Create a favorite_languages dictionary in which:
o Keys are the names of individuals.
o Values are the programming language that each individual loves.

for key, value in favorite_languages.items():


 Description: Start a for loop to iterate through each key pair and value in the
favorite_languages dictionary.
o key will get the value of the key (username).
o value will get the corresponding value of that key (your favorite
programming language).

if key in friend:
 Description: Check if the key (username) is in the friends list.
o If it does, it will proceed to print according to the print command
(f'Hello {key}, your favorite programming language is {value}')
Step 9: Define the function to print out the full name based on the input parameters of
first name and last name

def person_introduction(first_name, last_name):


 Description: This is the syntax for defining a function in Python. The name of
the function in this case is person_introduction.
 Parameter: This function has two parameters:
o first_name: Used to get the value of the first name (or name).
o last_name: Used to get their value (or last name).

print(f"My name is {first_name} {last_name}")


 Description: In the body of the function, this command prints a string of
characters. This string uses f-string to embed the values of first_name and
last_name parameters into the string.
o f"My name is {first_name} {last_name}" is an f-string, which allows
inserting the values of first_name and last_name variables into a string of
characters.
 Result: When the function is called, the printed string will have the format "My
name is [first_name] [last_name]", with [first_name] and [last_name] replaced
with the values of the parameters.

Step 10: Define the function to print out the age based on the input parameter as age
(assuming the current year is 2024)

def cal_age(birth_year):
 Description: This is the syntax for defining a function in Python. The name of
the function is cal_age.
 Parameter: This function has a parameter:
o birth_year: Used to get the value of the user's year of birth.

age = 2024 - birth_year


 Description: In the body of the function, this command calculates the user's
age by subtracting the year of birth (birth_year) from the current year (2024).
o age is the variable used to store the calculation results.

print(f"Your age is: {age}")


 Description: This command prints out a string of characters that uses the
format-string to embed the value of the age variable in the string.
o f"Your age is: {age}" is an f-string, which allows the value of the age
variable to be inserted into a string of characters.
 Result: When the function is called, the printed string will have the format
"Your age is: [age]", with [age] replaced by the value of the age variable.

Step 11: Define the function to find and return the largest value in the list with the
following main logic

Declare the function max_value find the largest value in the numbers list.

Implement:
 Assign the first value of the list to the max_num variable.
 Iterate through all the elements in the list. If the current element is larger than
max_num, update the max_num with that value.
 After the iteration is complete, return the corresponding max_num value which
is also the largest value in the list.
Step 12: Define the function

The function odd_even classifies the numbers in the input numbers list into odd and
even numbers:
Implement:
 Initialize two empty lists: odd_numbers for odd numbers and even_numbers
for even numbers.
 Repeat through each number in numbers. If that number is divisible by 2 (even
number), add even_numbers; if not, add odd_numbers.
 Print the list of odd and even numbers after the end of the lpawj round
(even_number and odd_number respectively)

You might also like