1. Trang chủ
  2. » Tất cả

Báo cáo lập trình cơ bản

51 16 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Báo cáo thực hành kỹ thuật lập trình mã học phần: ELE20004
Tác giả Trần Ngọc Phú
Người hướng dẫn Ts. Hồ Sỹ Phương
Trường học Trường Đại Học Vinh - Viện Kỹ Thuật Và Công Nghệ
Chuyên ngành Kỹ Thuật & Công Nghệ
Thể loại Báo cáo thực hành
Năm xuất bản 2022
Thành phố Nghệ An
Định dạng
Số trang 51
Dung lượng 4,15 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Cấu trúc

  • 2.1. Mục đích (3)
  • 2.2. Cơ sở lý thuyết (3)
  • 2.3 Bài tập thực hành (3)
  • BÀI 3. LẬP TRÌNH HÀM TRONG PYTHON (9)
    • 3.1. Mục đích (9)
    • 3.2. Cơ sở lý thuyết (9)
    • 3.3. Bài tập thực hành (9)
  • BÀI 4. CÁC DỮ LIỆU CÓ CẤU TRÚC TRONG PYTHON (15)
    • 4.1. Mục đích (15)
    • 4.2. Cơ sở lý thuyết (15)
    • 4.3. Bài tập thực hành (15)
  • BÀI 5. THIẾT KẾ MODULE TRONG PYTHON (23)
    • 5.1. Mục đích (23)
    • 5.2. Cơ sở lý thuyết (23)
    • 5.3. Thiết bị thực hành thí nghiệm và vật tư tiêu hao (23)
    • 5.4. Bài tập thực hành (23)
  • BÀI 6: LẬP TRÌNH HƯỚNG ĐỐI TƯỢNG TRONG PYTHON (33)
    • 6.1. Mục đích (33)
    • 6.2. Cơ sở lý thuyết (33)
    • 6.3. Bài tập thực hành (33)
  • BÀI 7: THAO TÁC TRÊN TẬP TIN VÀ THƯ MỤC TRONG PYTHON (37)
    • 7.1. Mục đích (37)
    • 7.2. Cơ sở lý thuyết (37)
    • 7.3. Bài tập thực hành (37)
  • BÀI 8: LẬP TRÌNH GIAO DIỆN TRONG PYTHON (42)
    • 8.1. Mục đích (42)
    • 8.2. Cơ sở lý thuyết (42)
    • 8.3. Bài tập thực hành (42)

Nội dung

BÀI 2. CÁC CÚ PHÁP, KIỂU DỮ LIỆU, LỆNH ĐIỀU KIỂN TRONG LẬP TRÌNH PYTHON 2.1. Mục đích Giúp sinh viên nắm bắt các kiến thức cơ bản như kiểu dữ liệu, các kiểu cú pháp, các lệnh điều khiển khi viết một chương trình bằng ngôn ngữ python. 2.2. Cơ sở lý thuyết Xem các khái niệm: Định danh, các từ khóa, dòng lệnh, khối lệnh, trích dẫn, comment, biến, toán tử, cấu trúc điều khiển trong python. 2.3 Bài tập thực hành 1. Viết đoạn chương trình sau và sửa lỗi Code: n1=int(input(enter n1 value)); n2=int(input(enter n2 value)); if n1>n2: print(n1 is big ) else: print(n2 is big )

Mục đích

Giúp sinh viên nắm bắt các kiến thức cơ bản về ngôn ngữ Python, bao gồm kiểu dữ liệu, các kiểu cú pháp và lệnh điều khiển Việc hiểu rõ các khái niệm này sẽ tạo nền tảng vững chắc để viết các chương trình Python hiệu quả và chính xác Đây là bước quan trọng giúp sinh viên làm quen và làm chủ ngôn ngữ lập trình Python trong quá trình học tập.

Cơ sở lý thuyết

Xem các khái niệm: Định danh, các từ khóa, dòng lệnh, khối lệnh, trích dẫn, comment, biến, toán tử, cấu trúc điều khiển trong python.

Bài tập thực hành

1 Viết đoạn chương trình sau và sửa lỗi

Code: n1=int(input("enter n1 value")); n2=int(input("enter n2 value")); if n1>n2: print("n1 is big ") else: print("n2 is big ")

2 Viết chương trình nhập hai điểm và tính khoảng cách

Code: import math x1 = int(input("Nhap x1:")) y1 = int(input("Nhap y1:")) x2 = int(input("Nhap x2:")) y2 = int(input("Nhap y2:")) d1 = (x2-x1) * (x2-x1); d2 = (y2-y1) * (y2-y1); res = math.sqrt(d1+d2) print("Khoang cach giua hai diem la:",res)

3 Viết chương trình nhập vào một số và kiểm tra số đó là chẵn hay lẻ, in thông báo ra màn hình

Code: n = int(input("Nhap n:")) if n % 2==0: print("n la so chan") else: print("n la so le")

4 Viết chương trình in ra màn hình số nghịch đảo và kết quả dưới dạng thập phân của một dãy số tự nhiên trong khoảng (a,b)

Code: i=1 for j in range(2,10): print("i:",i,"j:",j) print(i,"/",j) print(i/j)

5 Viết chương trình nhập vào một số tự nhiên n > 0, in ra màn hình các số tự nhiên giảm dần từ n đến 0, mỗi ký tự in trên 1 hàng

Code: n = int(input("Nhap n: ")) while n>=0: print(n) n=n-1

6 Viết chương trình tìm tất cả các số chia hết cho 7 nhưng không phải bội số của

5, nằm trong đoạn 2000 và 3200 (tính cả 2000 và 3200) Các số thu được sẽ được in thành chuỗi trên một dong, cách nhau bằng dấu phẩy.

Dưới đây là chương trình tạo ra một dictionary chứa các cặp số (i, i*i) từ 1 đến n, trong đó n là một số nguyên cố định Ví dụ, nếu n là 8, chương trình sẽ in ra dictionary là {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64} Chương trình này giúp dễ dàng tạo và hiển thị các phần tử theo thứ tự từ 1 đến n, phù hợp cho các bài tập lập trình về xử lý dictionaries trong Python.

Code: n = int(input("nhap vao mot so:")) d=dict() for i in range (1,n+1): d[i]=i*i print(d)

8 Viết chương trình in ra màn hình dãy số Fibonacci nhỏ hơn 4.000.000, tìm tổng các số chẵn trong dãy đã in

9 Viết chương trình đếm số ký tự trong 1 xâu ký tự nhập vào từ bàn phím, lưu các ký tự vào cấu trúc từ điển

10 Viết chương trình sử dụng các phương thức split và join để tách nhập xâu ký tự

11.Viết chương trình kết nối các danh sách vào từ điển

Code: l=[1,'python',4,7] k=['case',2,'gintur',8] m=[] m.append(l) m.append(k) print(m) d={1:1,2:k,'combine_list':m} print(d)

13.Viết chương trình giải phương trình bậc 2: ax2 +bx+c=0, với các hệ số a, b, c nhập từ bàn phím

LẬP TRÌNH HÀM TRONG PYTHON

Mục đích

Giúp sinh viên nắm bắt các kiến thức trong lập trình python sử dụng hàm.

Cơ sở lý thuyết

Trong Python, việc khai báo hàm, gọi hàm và quản lý giá trị trả về là các bước quan trọng để xây dựng mã nguồn rõ ràng và hiệu quả Các tham số truyền vào giúp làm linh hoạt hàm, trong khi tham số mặc định cung cấp giá trị mặc định nếu không truyền tham số Phạm vi của biến xác định nơi biến đó có thể truy cập trong mã nguồn, đảm bảo tính tổ chức và tránh xung đột Đồng thời, Python cung cấp nhiều hàm có sẵn trong các thư viện, giúp lập trình viên tiết kiệm thời gian và nâng cao hiệu suất lập trình Các quy tắc này giúp viết mã Python chuẩn và tối ưu hơn trong các dự án phần mềm.

Bài tập thực hành

1 Viết hàm sum() tính tổng hai số

Code: def sum(a, b): print("sum = " + str(a + b))

2 Viết hàm sum() với kết quả trả về Đáp án :

3 Tìm và sửa lỗi chương trình

Code: def say_hello(): a = "Hello" print(a) print(a)

4 Viết chương trình có phạm vi biến sau

5 Viết chương trình sau và xem sự thay đổi của biến

6 Viết chương trình sau và giải thích việc truyền tham số của hàm

7 Định nghĩa hàm có thể chấp nhận input là số nguyên và in "Đây là một số chẵn" nếu nó chẵn và in "Đây là một số lẻ" nếu là số lẻ

Code: def checkValue(n): if n%2 == 0: print ("Đây là một số chẵn") else: print ("Đây là một số lẻ") checkValue(7)

8 Một Robot di chuyển trong mặt phẳng bắt đầu từ điểm đầu tiên (0,0) Robot có thể di chuyển theo hướng UP, DOWN, LEFT và RIGHT với những bước nhất định.Dấu di chuyển của robot được đánh hiển thị như sau:

9 Chương trình máy tính thực hiện các phép tính đơn giản Đáp án :

10 Viết hàm “def Tinh(R):” tính chu vi và diện tích hình tròn, với bán kính R được nhập từ bàn phím, và kiểm tra giá trị bán kính đầu vào là hợp lệ.

R = int(input("NHap ban kinh r: ")) pi=3.14 def Tinh(R): if R1): print(i)

19 Hãy tạo ra tuple P gồm các số nguyên tố nhỏ hơn 1 triệu.

Code: t = tuple() for i in range(1,100): dem = 0 for j in range(1,i+1): if(i%j==0): dem = dem + 1 if(dem == 2): t = t+(i,) print(t)

20 Nhập n, in n dòng đầu tiên của tam giác pascal.

21 Viết một chương trình chấp nhận đầu vào là chuỗi các số nhị phân 4 chữ số, phân tách bởi dấu phẩy, kiểm tra xem chúng có chia hết cho 5 không Sau đó in các số chia hết cho 5 thành dãy phân tách bởi dấu phẩy Ví dụ đầu vào là: 0100,0011,1010,1001 Đầu ra sẽ là: 1010

22 Viết một chương trình tìm tất cả các số trong đoạn 1000 và 3000 (tính cả 2 số này) sao cho tất cả các chữ số trong số đó là số chẵn In các số tìm được thành chuỗi cách nhau bởi dấu phẩy, trên một dòng.

23 Viết một chương trình chấp nhận đầu vào là một câu, đếm chữ hoa, chữ thường

This Python script prompts the user to input a sentence and counts the number of uppercase and lowercase letters within it It initializes a dictionary to track the counts of uppercase and lowercase characters, then iterates through each character in the input string During the iteration, it increments the respective counters when it detects an uppercase or lowercase letter Finally, the program displays the total counts of uppercase and lowercase characters, providing a simple way to analyze the letter case composition of any input sentence.

26 Viết chương trình tính số tiền thực của một tài khoản ngân hàng dựa trên nhật ký giao dịch được nhập vào từ giao diện điều khiển.

This Python script processes transaction logs to calculate the net amount Users are prompted to enter transaction details, with each input consisting of an operation type ('D' for deposit or 'W' for withdrawal) followed by the transaction amount The program updates the net balance accordingly, adding for deposits and subtracting for withdrawals Input continues until the user submits an empty line, at which point the script displays the final net amount This code effectively demonstrates how to manage financial transactions and calculate account balances using Python.

THIẾT KẾ MODULE TRONG PYTHON

Mục đích

Giúp sinh viên nắm bắt việc thiết kế module trong lập trình python, sử dụng module thue viện numpy trong các ứng dụng.

Cơ sở lý thuyết

Xem các quy tắc khai báo, thiết kế và sử dụng module trong python, các thuật toán tìm kiếm, sắp xếp, cài đặt và sử dụng thư viện numpy.

Thiết bị thực hành thí nghiệm và vật tư tiêu hao

Thiết bị thực hành thí nghiệm: Máy tính

Vật tư tiêu hao: Không

Bài tập thực hành

1 Sử dụng module Định nghĩa một module toán học gọi là mymath và sử dụng module này từ một tập lệnh riêng biệt

## My script using the math module ##

Import mymath # note no py values=[2,4,6,8,10] print('Squares: ') for v in values: print(mymath.square(v)) print('Cubes:') for v in values: print(mymath.cube(v)) print('Average: '+ str( mymath.average(values)))

2 Sử dụng thư viện tiêu chuẩn của python (datetime)

3 Viết chương trình sử dụng thư viện NumPy để tạo một mảng với các giá trị nằm trong khoảng từ 12 đến 38.

Code: import numpy as np x

4 Viết chương trình để tạo một mảng với các giá trị nằm trong khoảng từ 12 đến 38 và đảo ngược mảng đã tạo (phần tử đầu tiên trở thành cuối cùng).

Code: import numpy as np x = np.arange(12, 38) languages = x reverse_list = x[::-1] print(reverse_list)

4 Viết chương trình tìm phần tử lớn nhất và nhỏ nhất của một danh sách

- Số lượng và giá trị của list được nhập từ bàn phím

The article presents a module for sorting and finding the largest element in an array, including functions like `Find_Max`, which iterates through the list to identify the maximum value, and `Find_Min`, which finds the smallest element It emphasizes user input handling with the `Enter_List` function that prompts users to enter each list item, storing them in an array Additionally, the `Show_List` function displays the array elements, providing a clear view of the list's contents Implementing these functions facilitates efficient data processing and retrieval in Python programming.

#chuong trinh chinh n = int(input("Nhap vao so luong phan tu: n = ")) print("Nhap vao mang:") arr = Enter_List(n) print("Mang vua nhap la:")

Show_List(arr) print("\nPhan tu lon nhat la: ", Find_Max(arr)) print("Phan tu nho nhat la: ", Find_Min(arr))

6 In ra vị trí phần tử lớn nhất và nhỏ nhất tìm được ở bài tập trên.

Code: s=[1,2,3,4,5] max=s[0] min=s[0] for i in s: if imax: max=i print(min) print(max)

7 Viết chương trình sử dụng thư viện NumPy để tạo một mảng có cấu trúc từ tên sinh viên, chiều cao, lớp và các kiểu dữ liệu của họ Bây giờ sắp xếp các mảng theo chiều cao.

8 Xây dựng hàm “Sequential_Search(dlist, item)” (giải thuật tìm kiếm tuyến tính) dưới dạng module Viết chương trình nhập một dlist n phần tử từ bàn phím và tìm kiếm phần tử item bất kỳ

The article demonstrates a simple sequential search algorithm in Python, which iterates through a list to find a specific item Users can input the number of items and then enter each item to build the list dynamically The program prompts for the target item to search within the list, then uses the sequential search function to determine if the item exists If found, it outputs the position of the item; otherwise, it indicates that the item is not present in the array This example highlights how to implement a basic search method with user interaction in Python.

9 Xây dựng hàm “binary_search(list, value)” (giải thuật tìm kiếm nhị phân) dưới dạng module Viết chương trình nhập một list n phần tử từ bàn phím và tìm kiếm phần tử value bất kỳ

The provided code implements a binary search algorithm in Python to efficiently locate an element within a sorted array Users are prompted to input the number of elements in the array, followed by the individual elements themselves After building the array, the user inputs the value 'x' they wish to find The binary search function recursively searches the array and returns the position of 'x' if found, or indicates if the element is not present in the array This approach highlights how binary search accelerates search operations compared to linear methods, making it ideal for large datasets and emphasizing the importance of sorted data for effective searching.

10 Xây dựng hàm “bubbleSort (nlist)” (giải thuật sắp xếp nổi bọt) dưới dạng module Viết chương trình nhập một nlist n phần tử từ bàn phím và sắp xếp Sample Data: [14,46,43,27,57,41,45,21,70] Expected Result: [14, 21, 27, 41, 43, 45, 46, 57, 70].

The provided code demonstrates the implementation of the Bubble Sort algorithm in Python, which efficiently sorts an array of numbers in ascending order The algorithm works by repeatedly stepping through the list, comparing adjacent elements, and swapping them if they are in the wrong order This process continues for multiple passes until the entire list is sorted, as shown in the example where an unsorted array is sorted and printed element by element Bubble Sort is a simple yet fundamental sorting technique widely used for educational purposes and small datasets.

Sử dụng thư viện NumPy để tạo một mảng có cấu trúc chứa thông tin của sinh viên, bao gồm tên, chiều cao, lớp và kiểu dữ liệu tương ứng giúp quản lý dữ liệu hiệu quả Tiếp theo, sắp xếp mảng theo lớp, và nếu các sinh viên cùng lớp, thì sắp xếp theo chiều cao để có thứ tự rõ ràng và dễ truy xuất Quá trình này tối ưu hóa việc xử lý dữ liệu sinh viên trong Python, đồng thời đảm bảo tính chính xác và linh hoạt khi làm việc với dữ liệu phức tạp.

Code: import numpy as np data_type = [('name', 'S15'), ('class', int), ('height', float)] students_details = [('James', 5, 48.5), ('Nail', 6, 52.5),('Paul', 5,

# create a structured array students = np.array(students_details, dtypea_type) print("Original array:") print(students) print("Sort by height") print(np.sort(students, order='height'))

LẬP TRÌNH HƯỚNG ĐỐI TƯỢNG TRONG PYTHON

Mục đích

Giúp sinh viên nắm bắt về lập trình hướng đối tượng trong lập trình python.

Cơ sở lý thuyết

Xem các quy tắc xây dựng class, các phương thức và thuộc tính của đối tượng.

Bài tập thực hành

1 Định nghĩa một class có tên là Circle có thể được xây dựng từ bán kính.

Circle có một method có thể tính diện tích

Code: class Circle(object): def init (self,r): self.radius = r

#bai1 def area(self): return self.radius**2*3.14 r = int (input("nhap ban kinh: ")) aCircle=Circle(r) print('dien tich la: ',aCircle.area())

2 Định nghĩa class có tên là Hinhchunhat được xây dựng bằng chiều dài và chiều rộng Class Hinhchunhat có method để tính diện tích.

This Python code defines a class named "Hinhchunhat" to model a rectangle The class constructor initializes the length ("dai") and width ("rong") based on user input, which are converted to integers An "area" method calculates the rectangle's area by multiplying its length and width Users are prompted to enter the dimensions, and the program creates an instance of the class to compute and display the rectangle's area This implementation demonstrates fundamental object-oriented programming principles in Python, useful for developing geometric calculation applications.

The article defines a base class called "Nguoi" (Person) along with two subclasses, "Nam" (Male) and "Nu" (Female) All classes include a method named "getGender" that outputs "Nam" when called from the Nam class and "Nu" when called from the Nu class, ensuring clear gender identification across the class hierarchy.

4 Viết chương trình Python dưới dạng class để chuyển đổi một số La Mã thành một số nguyên.

The provided code defines a Python class `py_solution` with a method `roman_to_int`, which converts Roman numerals to their integer equivalents The method utilizes a dictionary to map Roman characters to their values and processes each character in the input string, adjusting the total sum whenever a smaller numeral precedes a larger one to correctly interpret subtractive notation For example, it correctly converts 'MMMCMLXXXVI' to its integer value, as well as other Roman numerals like 'MMMM' and 'I' This implementation offers an efficient way to perform Roman numeral conversions with clear logic and adherence to common Roman numeral rules.

6 Viết một class Python có hai phương thức get_String và print_String. get_String chấp nhận một chuỗi từ người dùng và print_String in chuỗi đó bằng chữ in hoa

The provided code defines a Python class called `InputOutString` designed for user interaction It prompts the user to input a string using the `get_String()` method Once the input is received, the `print_String()` method displays the entered string in uppercase letters This simple program demonstrates how to capture user input and manipulate string data effectively in Python.

THAO TÁC TRÊN TẬP TIN VÀ THƯ MỤC TRONG PYTHON

Mục đích

Giúp sinh viên có thể thao tác với các file văn bản sử dụng python.

Cơ sở lý thuyết

Xem các quy tắc mở, đóng file văn bản, đọc và ghi nội dung của các file.

Bài tập thực hành

1 Chương trình đọc file và in đảo ngược kết quả.

Code: input_file=open('a.txt','r') for line in input_file: l=len(line) s=' ' while(l>=1): s=s+line[l-1] l = l-1 print(s) input_file.close()

2 Chương trình đọc một file, tính số ký tự, số từ và số dòng của file

This article discusses a Python script designed to analyze text files The script opens the file "a.txt" in read mode and initializes counters for characters, words, and lines It iterates through each line of the file, counting characters and detecting specific characters to tally words and lines accurately Specifically, it increments the character count for each character in the line, increases the word count when encountering the '/m' marker, and updates the line count when encountering the 'n' character Finally, it outputs the total number of characters, words, and lines within the text file, providing a basic overview of the file's content for SEO-friendly content analysis.

4 Chương trình Python để đọc n dòng đầu tiên của tệp

Code: def file_read_from_head(fname, nlines): from itertools import islice with open(fname) as f: for line in islice(f, n lines) print(line) file_read('abc.txt')

5 Chương trình Python để nối văn bản vào tệp và hiển thị văn bản

The provided code defines a function named `file_read` intended to work with file operations in Python However, it contains multiple errors, including improper indentation, incorrect use of the `from` statement inside a function, and inconsistent file modes The function attempts to open a file named 'abc.txt' in write mode, write specific text strings like "python exercises" and "jav exercises," and then read its contents Due to these issues, the code will not execute as intended For effective file handling in Python, proper syntax and logic are essential, such as using correct indentation, appropriate file modes, and avoiding invalid import statements within functions This highlights the importance of understanding Python's file I/O operations to prevent runtime errors and ensure accurate data manipulation.

6 Chương trình Python để đọc n dòng cuối cùng của tệp.

This article provides a Python script designed to efficiently read the last few lines from a file It employs a buffer size of 8,192 bytes to handle large files without loading the entire content into memory The function `file_read_from_tail` calculates the file size and reads data from the end in chunks, using `seek` and `readlines()`, until the desired number of lines is retrieved or the beginning of the file is reached This approach ensures quick access to the tail of any file, making it valuable for log file analysis and monitoring The script demonstrates how to implement an effective "tail" command in Python, enabling users to extract the most recent entries from large datasets efficiently.

7 Viết chương trình Python để đếm số dòng trong tệp văn bản.

Code: num_lines = sum(1 for line in open('2.txt')) print(num_lines)

LẬP TRÌNH GIAO DIỆN TRONG PYTHON

Mục đích

Giúp sinh viên làm quen với lập trình đồ họa và sử dụng thư viện turtle,

Cơ sở lý thuyết

Xem các quy tắc xây dựng và quản lý layout, widget, hộp thoại, đồ họa trong python.

Bài tập thực hành

1 Viết chương trình đồ họa sử dụng thư viện turtle, kiểm tra kết quả và giải thích chương trình.

This article demonstrates how to create a simple graphic using Python's turtle module It begins by setting up the drawing window with a light green background, followed by initializing a turtle object named 'painter' with blue fill and pen colors and a pen size of 3 The core function, 'drawsq', commands the turtle to draw a square with sides of a specified length The code includes a loop that calls the 'drawsq' function 180 times, with the turtle turning left by 18 degrees each iteration to create a rotating square pattern This example showcases basic turtle graphics techniques for creating colorful, geometric designs in Python.

2 Dựa trên các kết quả đạt được từ các chương trình trên hãy viết chương trình hiển thị hình ảnh đồ họa sau.

This article demonstrates how to create colorful spiral patterns using Python's turtle graphics module By randomly selecting colors from a predefined list, the program draws multiple circles with varying hues to produce vibrant visual effects The code involves setting up a turtle object with a specific pen size, then repeatedly drawing circles at the same position while rotating the turtle to achieve a dynamic, layered design This approach showcases the simplicity and flexibility of turtle graphics for generating engaging, colorful artwork through looping and randomization techniques.

3 Viết chương sử dụng thư viện đồ họa tkinter thực hiện a, Xây dựng cửa sổ đồ họa window form

Code: from tkinter import * window = Tk( window.title ("Welcome to likeGeeks app") window.mainloop() b, Thêm một widget (button) vào window form

Code: from tkinter import * window = Tk() window.title ("Welcome to likeGeeks app")

Lbl = Label(window, text="Hello")

Lbl.grid (column=0, row=0) window.mainloop() c, Xây dựng phương thức xử lý sự kiện phím bấm

This article provides a simple example of creating a GUI application using Python's Tkinter library It demonstrates how to set up a window with a welcome message and a button that, when clicked, updates the label text to indicate the button was pressed The code customizes the window size, background color, and button appearance with specific fonts and colors, illustrating how to build interactive and visually appealing desktop applications with Tkinter.

4 Sử dụng thư viện tkinter thực hiện: Thay thế các radio button thành các indicator như hình.

Code: import tkinter as tk root = tk.Tk() v = tk.IntVar() v.set(1)

# initializing the choice, i.e Pyt languages = [ ("Python", 1),("Perl",2),("Java",3),("C++", 4),

The "ShowChoice" function displays the user's selected programming language by retrieving the current value of the variable A label prompts users to "Choose your favourite programming language," enhancing user engagement The interface dynamically generates radio buttons for each language option, allowing users to select their preference seamlessly This implementation improves user interaction and provides real-time feedback based on the user's choice Ensuring accessibility and clarity, the design supports an intuitive selection process within the application.

5 Viết chương trình thực hiện tạo menu theo các bước sau

- Thực hiện tạo mới window form và các menu theo code mẫu

This article demonstrates how to create a simple graphical user interface (GUI) using Tkinter in Python, featuring a menu bar with "File" and "Help" options The "File" menu includes commands like "New" and "Exit," while the "Help" menu provides an "About " option to display application information The example emphasizes basic menu creation, command binding, and event handling in Tkinter for building user-friendly desktop applications.

6 Sử dụng thư viện đồ họa tkinter thực hiện các bước sau.

Code: import tkinter import random colours = ['Red','Blue','Green','Pink','Black',

This interactive color-matching game challenges players to identify colors accurately within a time limit, enhancing cognitive skills and reaction speed The game initializes with a countdown timer of 30 seconds, during which players must match text input to the displayed color When the user inputs the correct color name, their score increases, and the game quickly shuffles the color sequence to maintain engagement Real-time updates of the score and remaining time keep players motivated and informed, providing a dynamic and educational experience that combines quick thinking with visual perception Optimized for SEO, this game promotes cognitive development and quick decision-making skills through an engaging, colorful interface.

+ str(timeleft)) timeLabel.after(1000, countdown) root = tkinter.Tk() root.title("COLORGAME") root.geometry("375x200") instructions = tkinter.Label(root, text = "Type in the colour"

This article discusses implementing a simple typing game using Tkinter in Python It features key interface components such as labels displaying instructions, score, and remaining time, which enhance user engagement The game initializes with prompts like "Press enter to start" and dynamically updates the time left, creating an interactive experience for players By binding the Enter key to start the game and setting focus to the input entry, the setup ensures smooth user interaction Overall, this code snippet demonstrates how to create an engaging, time-based typing game application with effective use of Tkinter widgets.

7 Viết chương trình graphic sử dụng thư viện Tkinter thực hiện.

This Python script creates an interactive GUI application using Tkinter, featuring three radio buttons labeled "First," "Second," and "Third," allowing users to select options The selected value is stored in an `IntVar()` variable, which updates dynamically as users choose different options A "Click Me" button is included, and when clicked, it triggers a function that retrieves and prints the selected radio button's value, facilitating user interaction and data collection Additionally, the interface includes a label titled "Thông tin cá nhân :", providing a section for personal information input, enhancing the form's functionality for user data entry This example demonstrates how to build a simple, user-friendly interface with radio buttons, buttons, and labels using Tkinter, suitable for various Python GUI applications.

Roman',14)) a.place(x , y ) b = Label(window, text = "Họ tên : ", fon = ('Times New Roman',14)) b.place(x, yP)

Ngày đăng: 31/01/2023, 21:30

w