Here is a small exercise for getting started with Python basics with simple library usage:
- Output the current date and time
Requirements: Output the current date and time, and format the output.
from datetime import datetime
now = datetime.now()
print("Current date and time: ", now.strftime("%Y-%m-%d %H:%M:%S"))
- Generate random numbers
Requirements: Use the random library to generate a random integer between 1 and 100.
import random
num = random.randint(1, 100)
print(num)
- Count the number of occurrences of elements in a list
Requirements: Enter a list and count the number of occurrences of each element in it.
from collections import Counter
lst = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5]
counter = Counter(lst)
print(counter)
- Determine whether a number is a prime number
Requirements: Input a positive integer and determine whether it is a prime number.
num = int(input("输入一个数字: "))
is_prime = True
for i in range(2, num):
if num % i == 0:
is_prime = False
break
if is_prime:
print(num, "是质数")
else:
print(num, "不是质数")
- Count the number of occurrences of each word in a string
Requirements: Enter a string and count the number of occurrences of each word in it.
str = "this is a test string for testing purposes"
word_counts = {
}
words = str.split()
for word in words:
if word in word_counts:
word_counts[word] += 1
else:
word_counts[word] = 1
print(word_counts)
- Sort a list
Requirement: Enter a list, sort it in ascending or descending order.
lst = [5, 2, 8, 1, 9, 3]
sort_type = input("Enter 'asc' for ascending or 'desc' for descending: ")
if sort_type == 'asc':
sorted_lst = sorted(lst)
elif sort_type == 'desc':
sorted_lst = sorted(lst, reverse=True)
else:
print("Invalid input")
print(sorted_lst)
Finally—————— Learning Python is a challenge, but it is also an opportunity to grow. Persevere, you will see the process of your continuous improvement, come on