【Python編程基礎練習】 Python編程基礎練習100題學習記錄第一期(1~10)

来源:https://www.cnblogs.com/qin1999/archive/2022/07/28/Python-programming-exercises-1.html
-Advertisement-
Play Games

1.此為GitHub項目的學習記錄,記錄著我的思考,代碼基本都有註釋。 2.可以作為Python初學者鞏固基礎的絕佳練習,原題有些不妥的地方我也做了一些修正。 3.建議大家進行Python編程時使用英語,工作時基本用英語。 4.6~17題為level1難度,18-22題為level3難度,其餘都為l ...


1.此為GitHub項目的學習記錄,記錄著我的思考,代碼基本都有註釋。
2.可以作為Python初學者鞏固基礎的絕佳練習,原題有些不妥的地方我也做了一些修正。
3.建議大家進行Python編程時使用英語,工作時基本用英語。
4.6~17題為level1難度,18-22題為level3難度,其餘都為level1難度。
項目名稱:
100+ Python challenging programming exercises for Python 3

#!usr/bin/env Python3.9     # linux環境運行必須寫上
# -*- coding:UTF-8 -*-      # 寫一個特殊的註釋來表明Python源代碼文件是unicode格式的

"""Question:
    Write a program which will find all such numbers
    which are divisible by 7 but are not a multiple of 5,
    between 2000 and 3200 (both included).
    The numbers obtained should be printed
    in a comma-separated sequence on a single line."""

'''Hints: Consider use range(#begin, #end) method'''

l1 = []  # 建立空列表
for i in range(2000, 3201):     # for迴圈尋找能被7整除但不能被5整除的數字
    if (i % 7 == 0) and (i % 5 != 0):
        l1.append(str(i))       # 列表裡的數據需要是字元串
print(','.join(l1))             # 在一行顯示,以逗號隔開
#!usr/bin/env Python3.9
# -*- coding:UTF-8 -*-

"""
Question:
Write a program which can compute the factorial of a given numbers.
The results should be printed in a comma-separated sequence on a single line.
Suppose the following input is supplied to the program: 8 Then, the output should be: 40320
"""

'''Hints: In case of input data being supplied to the question, it should be assumed to be a console input.'''
i = 1
result = 1
t = int(input('請輸入一個數字: '))
while i <= t:                   # while迴圈
    result = result * i         # 實現階乘
    i += 1
print(result)

# 源代碼
'''
def fact(x):
    if x == 0:
        return 1
    return x * fact(x - 1)

x=int(input('請輸入一個數字: '))
print(fact(x))
'''
#!usr/bin/env Python3.9
# -*- coding:UTF-8 -*-
"""
Question:
With a given integral number n,
write a program to generate a dictionary
that contains (i, i*i) such that is an integral number between 1 and n (both included).
and then the program should print the dictionary.
Suppose the following input is supplied to the program: 8
Then, the output should be: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}
"""

'''
Hints: In case of input data being supplied to the question, it should be assumed to be a console input. 
Consider use dict()
'''
m = int(input('請輸入一個數字1~n:'))
n = {}                      # 創建一個空字典
for i in range(1, m+1):
    n[i] = (i * i)          # 將鍵值對存入空字典
    i += 1
print(n)

# 源代碼
'''
n=int(input())
d=dict()
for i in range(1,n+1):
    d[i]=i*i

print(d)

'''
#!usr/bin/env Python3.9
# -*- coding:UTF-8 -*-

"""
Question:
Write a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple
which contains every number.
Suppose the following input is supplied to the program: 34,67,55,33,12,98
Then, the output should be: ['34', '67', '55', '33', '12', '98'] ('34', '67', '55', '33', '12', '98')
"""

'''
Hints: In case of input data being supplied to the question, 
it should be assumed to be a console input. 
tuple() method can convert list to tuple
'''

import re

t = input('請輸入數據:')
d = t.split(',')                 # split()函數按照所給參數分割序列
k = re.findall(r'\d+', t)        # findall()函數在字元串中找到正則表達式所匹配的所有子串,並組成一個列表返回
# \d  相當於[0-9],匹配0-9數字
r = tuple(k)                     # 轉換為元組類型
print(k)
print(r)

#!usr/bin/env Python3.9
# -*- coding:UTF-8 -*-

"""
Question:
Define a class which has at least two methods:
getString: to get a string from console
input printString: to print the string in upper case.
Also please include simple test function to test the class methods.
"""

'''
Hints: Use init method to construct some parameters
'''


class InputOutputString():      # 創建類函數
    def __init__(self):
        self.s = ''

    def __getString__(self):
        self.s = input('Please input what you want:')

    def __printString__(self):
        print(self.s.upper())       # upper()函數使字元串字母變為大寫


stringRan = InputOutputString()
stringRan.__getString__()
stringRan.__printString__()

#!usr\bin\env Python3
# encoding:UTF-8

"""
Question:
Write a program that calculates and prints the value according to the given formula:
Q = Square root of [(2 * C * D)/H]
Following are the fixed values of C and H: C is 50. H is 30.
D is the variable whose values should be input to your program in a comma-separated sequence.
Example Let us assume the following comma separated input sequence is given to the program: 100,150,180
The output of the program should be: 18,22,24
"""

'''
If the output received is in decimal form, 
it should be rounded off to its nearest value 
(for example, if the output received is 26.0, it should be printed as 26) 
In case of input data being supplied to the question, it should be assumed to be a console input.
'''

import math

C = 50
H = 30
value = []      # 創建空列表
t = input('Please input your values, example:34, 23, 180, ... :')
x = [i for i in t.split(',')]           # 列表推導式

for d in x:
    value.append(str(round(math.sqrt((2 * C * float(d)) / H))))  # round()函數實現四捨五入,sqrt表示平方

print(','.join(value))
#!usr\bin\env Python3
# encoding:UTF-8

"""
Question:
Write a program which takes 2 digits, X,Y as input and generates a 2-dimensional array.
The element value in the i-th row and j-th column of the array should be i*j.
Note: i=0,1.., X-1; j=0,1,¡..., Y-1.
Example Suppose the following inputs are given to the program: 3,5
Then, the output of the program should be: [[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]]
"""

'''
Note: In case of input data being supplied to the question, 
it should be assumed to be a console input in a comma-separated form.
'''

input_String = input('Please input 2 digits, example:2,3.:')
dimensions = [int(x) for x in input_String.split(',')]  # 表示數組行數和列數
rowNum = dimensions[0]  # 賦予行數
colNum = dimensions[1]  # 賦予列數
multi_list = [[0 for col in range(colNum)] for row in range(rowNum)]  # 創建一個空數組列表

for col in range(colNum):
    for row in range(rowNum):
        multi_list[row][col] = col * row  # 向空數組填入數值
print(multi_list)

#!usr\bin\env Python3
# encoding:UTF-8

"""
Question:
Write a program that accepts a comma separated sequence of words as input
and prints the words in a comma-separated sequence after sorting them alphabetically.
Suppose the following input is supplied to the program: without,hello,bag,world
Then, the output should be: bag,hello,without,world
"""

'''
Hints: In case of input data being supplied to the question, it should be assumed to be a console input.
'''

temp = input('Please input your words:')
inputStr = temp.split(',')              # 按“, ”分隔輸入的單詞
inputStr.sort()                         # 按字母順序進行排列
print(','.join(inputStr))               # 輸出按字母順序排列的單詞,單詞之間用逗號分隔


# 源代碼
"""
items=[x for x in input().split(',')]
items.sort()
print(','.join(items))
"""
#!usr/bin/env Python3.9
# -*- coding:UTF-8 -*-

"""
Question:
Write a program that accepts sequence of lines as input
and prints the lines after making all characters in the sentence capitalized.
Suppose the following input is supplied to the program: Hello world Practice makes perfect
Then, the output should be: HELLO WORLD PRACTICE MAKES PERFECT
"""

'''
Hints: In case of input data being supplied to the question, it should be assumed to be a console input.
'''
lines = []

while True:
    s = input('Please input your sentences:')
    if s:
        lines.append(s.upper())             # 將大寫過後的句子放進列表裡,可以放進去多個句子
    else:
        break

for sentence in lines:                      # 列印每一句句子
    print(sentence)
#!usr/bin/env Python3.9
# -*- coding:UTF-8 -*-
"""
Question:
Write a program that accepts a sequence of whitespace separated words as input
and prints the words after removing all duplicate words and sorting them alphanumerically.
Suppose the following input is supplied to the program: hello world and practice makes perfect and hello world again
Then, the output should be: again and hello makes perfect practice world
"""

'''
Hints: In case of input data being supplied to the question, it should be assumed to be a console input. 
We use set container to remove duplicated data automatically and then use sorted() to sort the data.
'''

temp = input('Please input your words: ')               # 輸入想說的話
words = [x for x in temp.split(' ')]                    # 按照空格分割,把單詞放進列表

print(' '.join(sorted(list(set(words)))))               # 用set()函數創建一個無序的、不重覆(可利用這一點刪除重覆元素)
                                                        # 元素集,並可進行與或等運算。經過排序後再用空格分隔裝進列表列印出來

再附上Python常用標準庫供大家學習使用:
Python一些常用標準庫解釋文章集合索引(方便翻看)

“學海無涯”


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 多線程簡介 1.Process與Thread 程式本身是指定和數據的有序集合,其本身沒有任何運行的含義,是一個靜態的概念。 而進程則是執行程式中的一次執行過程,是一個動態的概念。是系統能夠資源分配的單位。 通常在一個進程里,可以包含若幹個線程,當然一個進程至少有一個線程,不然沒有存在的意義。 線程是 ...
  • 作者:明明如月學長 鏈接:https://juejin.cn/post/7118073840999071751 一、背景 有些業務場景下需要將 Java Bean 轉成 Map 再使用。 本以為很簡單場景,但是坑很多。 二、那些坑 2.0 測試對象 import lombok.Data; impor ...
  • 前言 😋 嗨嘍,大家好呀~這裡是愛看美女的茜茜吶 本次採集網介紹:圖書頻道-全球最大中文網上書店 專業提供小說傳記,青春文學,成功勵志,投資理財等各品類圖書 暢銷榜最新報價、促銷、評論信息,引領最新網上購書體驗! 環境使用 🎈: Python 3.8 Pycharm 模塊使用 🎠: reque ...
  • 1. 簡介 1.1什麼是Mybatis MyBatis 是一款優秀的持久層框架 它支持自定義 SQL、存儲過程以及高級映射。 MyBatis 免除了幾乎所有的 JDBC 代碼以及設置參數和獲取結果集的工作。 MyBatis 可以通過簡單的 XML 或註解來配置和映射原始類型、介面和 Java POJ ...
  • 問題描述 用python 讀取csv文件時,報錯utf-8' codec can't decode byte 0xff in position 0: invalid start byte 問題原因 打開所用的編碼方式不對,需要指定該csv文件所用編碼 解決方法 1.找到該csv文件所用編碼方法 用記 ...
  • 兄弟們,溫故而知新,可以為師矣。 就是說,我們所學過的東西,要去多複習,這樣才能總結出屬於自己的理解,這樣就可以做老師了。 但是我以為的我以為,後面可以改成,將自己所學及所領會的教給別人,這樣才能更加記憶深刻。 今日內容:Python將多個文件多列進行關聯 知識點 文件讀寫 基礎語法 異常處理 迴圈 ...
  • 背景 過去,我們運維著“能做一切”的大型單體應用程式。這是一種將產品推向市場的很好的方式,因為剛開始我們也只需要讓我們的第一個應用上線。 而且我們總是可以回頭再來改進它的。部署一個大應用總是比構建和部署多個小塊要容易。 集中式: 集群: 分散式: 分散式和集中式會配合使用。 我們在搭建網站的時候,為 ...
  • static關鍵字 1.Java中的靜態 1.1static修飾成員變數 static修飾的成員變數屬於類、也稱為類變數,類對象可以使用。使用時可以直接用類名調用。 定義格式:`static 數據類型 變數名;` 例子: class A{ static String city="China"; } ...
一周排行
    -Advertisement-
    Play Games
  • Timer是什麼 Timer 是一種用於創建定期粒度行為的機制。 與標準的 .NET System.Threading.Timer 類相似,Orleans 的 Timer 允許在一段時間後執行特定的操作,或者在特定的時間間隔內重覆執行操作。 它在分散式系統中具有重要作用,特別是在處理需要周期性執行的 ...
  • 前言 相信很多做WPF開發的小伙伴都遇到過表格類的需求,雖然現有的Grid控制項也能實現,但是使用起來的體驗感並不好,比如要實現一個Excel中的表格效果,估計你能想到的第一個方法就是套Border控制項,用這種方法你需要控制每個Border的邊框,並且在一堆Bordr中找到Grid.Row,Grid. ...
  • .NET C#程式啟動閃退,目錄導致的問題 這是第2次踩這個坑了,很小的編程細節,容易忽略,所以寫個博客,分享給大家。 1.第一次坑:是windows 系統把程式運行成服務,找不到配置文件,原因是以服務運行它的工作目錄是在C:\Windows\System32 2.本次坑:WPF桌面程式通過註冊表設 ...
  • 在分散式系統中,數據的持久化是至關重要的一環。 Orleans 7 引入了強大的持久化功能,使得在分散式環境下管理數據變得更加輕鬆和可靠。 本文將介紹什麼是 Orleans 7 的持久化,如何設置它以及相應的代碼示例。 什麼是 Orleans 7 的持久化? Orleans 7 的持久化是指將 Or ...
  • 前言 .NET Feature Management 是一個用於管理應用程式功能的庫,它可以幫助開發人員在應用程式中輕鬆地添加、移除和管理功能。使用 Feature Management,開發人員可以根據不同用戶、環境或其他條件來動態地控制應用程式中的功能。這使得開發人員可以更靈活地管理應用程式的功 ...
  • 在 WPF 應用程式中,拖放操作是實現用戶交互的重要組成部分。通過拖放操作,用戶可以輕鬆地將數據從一個位置移動到另一個位置,或者將控制項從一個容器移動到另一個容器。然而,WPF 中預設的拖放操作可能並不是那麼好用。為瞭解決這個問題,我們可以自定義一個 Panel 來實現更簡單的拖拽操作。 自定義 Pa ...
  • 在實際使用中,由於涉及到不同編程語言之間互相調用,導致C++ 中的OpenCV與C#中的OpenCvSharp 圖像數據在不同編程語言之間難以有效傳遞。在本文中我們將結合OpenCvSharp源碼實現原理,探究兩種數據之間的通信方式。 ...
  • 一、前言 這是一篇搭建許可權管理系統的系列文章。 隨著網路的發展,信息安全對應任何企業來說都越發的重要,而本系列文章將和大家一起一步一步搭建一個全新的許可權管理系統。 說明:由於搭建一個全新的項目過於繁瑣,所有作者將挑選核心代碼和核心思路進行分享。 二、技術選擇 三、開始設計 1、自主搭建vue前端和. ...
  • Csharper中的表達式樹 這節課來瞭解一下表示式樹是什麼? 在C#中,表達式樹是一種數據結構,它可以表示一些代碼塊,如Lambda表達式或查詢表達式。表達式樹使你能夠查看和操作數據,就像你可以查看和操作代碼一樣。它們通常用於創建動態查詢和解析表達式。 一、認識表達式樹 為什麼要這樣說?它和委托有 ...
  • 在使用Django等框架來操作MySQL時,實際上底層還是通過Python來操作的,首先需要安裝一個驅動程式,在Python3中,驅動程式有多種選擇,比如有pymysql以及mysqlclient等。使用pip命令安裝mysqlclient失敗應如何解決? 安裝的python版本說明 機器同時安裝了 ...