Python 課程程式碼範例
這是我使用和建立的 python 程式碼的文檔,用於學習 python。
它易於理解和學習。歡迎從這裡學習。
我很快就會用更多高級主題更新部落格。
目錄
- 第一個節目
- 變數與資料型別
- 字串
- 數字
- 取得使用者的輸入
- 建構一個基本計算器
- 第一個 Madlibs
- 列表
- 列表函數
- 元組
- 功能
- 退貨聲明
- If 語句
- 如果比較
- 猜謎遊戲2
- For 循環
- 指數函數
- 二維列表與 For 迴圈
第一個節目
此程式用於展示 print() 命令如何運作。
# This is a simple "Hello World" program that demonstrates basic print statements # Print the string "Hello world" to the console print("Hello world") # Print the integer 1 to the console print(1) # Print the integer 20 to the console print(20)
變數和資料類型
Python 中的變數是用來儲存值的保留記憶體位置。
資料型別定義變數可以保存的資料型別,即整數、浮點、字串等
# This program demonstrates the use of variables and string concatenation # Assign the string "Dipsan" to the variable _name _name = "Dipsan" # Assign the integer 20 to the variable _age _age = 20 # Assign the string "piano" to the variable _instrument _instrument = "piano" # Print a sentence using string concatenation with the _name variable print("my name is" + _name + ".") # Print a sentence using string concatenation, converting _age to a string print("I'm" + str(_age) + "years old") # Converting int to string for concatenation # Print a simple string print("i dont like hanging out") # Print a sentence using string concatenation with the _instrument variable print("i love " + _instrument + ".")
弦樂
用於儲存和操作文字的字元序列。它們是透過將文字括在單引號 ('Hello')、雙引號 ("Hello") 或多行字串的三引號 ('''Hello''') 來創建的。例:「你好,世界!」。
# This script demonstrates various string operations # Assign a string to the variable 'phrase' phrase = "DipsansAcademy" # Print a simple string print("This is a string") # Concatenate strings and print the result print('This' + phrase + "") # Convert the phrase to uppercase and print print(phrase.upper()) # Convert the phrase to lowercase and print print(phrase.lower()) # Check if the uppercase version of phrase is all uppercase and print the result print(phrase.upper().isupper()) # Print the length of the phrase print(len(phrase)) # Print the first character of the phrase (index 0) print(phrase[0]) # Print the second character of the phrase (index 1) print(phrase[1]) # Print the fifth character of the phrase (index 4) print(phrase[4]) # Find and print the index of 'A' in the phrase print(phrase.index("A")) # Replace "Dipsans" with "kadariya" in the phrase and print the result print(phrase.replace("Dipsans", "kadariya"))
數位
數字用於各種數字運算和數學函數:
# Import all functions from the math module from math import * # Importing math module for additional math functions # This script demonstrates various numeric operations and math functions # Print the integer 20 print(20) # Multiply 20 by 4 and print the result print(20 * 4) # Add 20 and 4 and print the result print(20 + 4) # Subtract 4 from 20 and print the result print(20 - 4) # Perform a more complex calculation and print the result print(3 + (4 - 5)) # Calculate the remainder of 10 divided by 3 and print the result print(10 % 3) # Assign the value 100 to the variable _num _num = 100 # Print the value of _num print(_num) # Convert _num to a string, concatenate with other strings, and print print(str(_num) + " is my fav number") # Converting int to string for concatenation # Assign -10 to the variable new_num new_num = -10 # Print the absolute value of new_num print(abs(new_num)) # Absolute value # Calculate 3 to the power of 2 and print the result print(pow(3, 2)) # Power function # Find the maximum of 2 and 3 and print the result print(max(2, 3)) # Maximum # Find the minimum of 2 and 3 and print the result print(min(2, 3)) # Minimum # Round 3.2 to the nearest integer and print the result print(round(3.2)) # Rounding # Round 3.7 to the nearest integer and print the result print(round(3.7)) # Calculate the floor of 3.7 and print the result print(floor(3.7)) # Floor function # Calculate the ceiling of 3.7 and print the result print(ceil(3.7)) # Ceiling function # Calculate the square root of 36 and print the result print(sqrt(36)) # Square root
取得使用者的輸入
此程式用於示範如何使用 input() 函數取得使用者輸入:
# This script demonstrates how to get user input and use it in string concatenation # Prompt the user to enter their name and store it in the 'name' variable name = input("Enter your name : ") # Prompt the user to enter their age and store it in the 'age' variable age = input("Enter your age. : ") # Print a greeting using the user's input, concatenating strings print("hello " + name + " Youre age is " + age + " .")
建構一個基本計算器
程式建立一個簡單的計算器,將兩個數字相加:
# This script creates a basic calculator that adds two numbers # Prompt the user to enter the first number and store it in 'num1' num1 = input("Enter first number : ") # Prompt the user to enter the second number and store it in 'num2' num2 = input("Enter second number: ") # Convert the input strings to integers and add them, storing the result result = int(num1) + int(num2) # Print the result of the addition print(result)
第一瘋狂
這個程式創造了一個簡單的 Mad Libs 遊戲:
# This program is used to create a simple Mad Libs game. # Prompt the user to enter an adjective and store it in 'adjective1' adjective1 = input("Enter an adjective: ") # Prompt the user to enter an animal and store it in 'animal' animal = input("Enter an animal: ") # Prompt the user to enter a verb and store it in 'verb' verb = input("Enter a verb: ") # Prompt the user to enter another adjective and store it in 'adjective2' adjective2 = input("Enter another adjective: ") # Print the first sentence of the Mad Libs story using string concatenation print("I have a " + adjective1 + " " + animal + ".") # Print the second sentence of the Mad Libs story print("It likes to " + verb + " all day.") # Print the third sentence of the Mad Libs story print("My " + animal + " is so " + adjective2 + ".")
清單
清單是Python中有序且可更改的項目的集合。清單中的每個項目(或元素)都有索引,從 0 開始。清單可以包含不同資料類型的項目(如整數、字串,甚至其他清單)。
清單使用方括號 [] 定義,每個項目以逗號分隔。
# This script demonstrates basic list operations # Create a list of friends' names friends = ["Roi", "alex", "jimmy", "joseph"] # Print the entire list print(friends) # Print the first element of the list (index 0) print(friends[0]) # Print the second element of the list (index 1) print(friends[1]) # Print the third element of the list (index 2) print(friends[2]) # Print the fourth element of the list (index 3) print(friends[3]) # Print the last element of the list using negative indexing print(friends[-1]) # Print a slice of the list from the second element to the end print(friends[1:]) # Print a slice of the list from the second element to the third (exclusive) print(friends[1:3]) # Change the second element of the list to "kim" friends[1] = "kim" # Print the modified list print(friends)
清單功能
此腳本展示了各種清單方法:
# This script demonstrates various list functions and methods # Create a list of numbers numbers = [4, 6, 88, 3, 0, 34] # Create a list of friends' names friends = ["Roi", "alex", "jimmy", "joseph", "kevin", "tony", "jimmy"] # Print both lists print(numbers) print(friends) # Add all elements from 'numbers' to the end of 'friends' friends.extend(numbers) # Add "hulk" to the end of the 'friends' list friends.append("hulk") # Insert "mikey" at index 1 in the 'friends' list friends.insert(1, "mikey") # Remove the first occurrence of "Roi" from the 'friends' list friends.remove("Roi") # Print the index of "mikey" in the 'friends' list print(friends.index("mikey")) # Remove and print the last item in the 'friends' list print(friends.pop()) # Print the current state of the 'friends' list print(friends) # Remove all elements from the 'friends' list friends.clear() # Print the empty 'friends' list print(friends) # Sort the 'numbers' list in ascending order numbers.sort() # Print the sorted 'numbers' list print(numbers)
元組
元組是Python中有序但不可更改(不可變)的項目的集合。一旦建立了元組,就無法新增、刪除或變更其元素。與清單一樣,元組可以包含不同資料類型的項目。
元組使用括號 () 定義,每個項目以逗號分隔。
# This script introduces tuples and their immutability # Create a tuple with two elements values = (3, 4) # Print the entire tuple print(values) # Print the second element of the tuple (index 1) print(values[1]) # The following line would cause an IndexError if uncommented: # print(values[2]) # This would cause an IndexError # The following line would cause a TypeError if uncommented: # values[1] = 30 # This would cause a TypeError as tuples are immutable # The following line would print the modified tuple if the previous line worked: # print(values)
功能
函數是執行特定任務的可重複使用程式碼區塊。函數可以接受輸入(稱為參數)、處理它們並傳回輸出。函數有助於組織程式碼,使其更加模組化,並避免重複。
在 Python 中,函數是使用 def 關鍵字定義的,後面跟著函數名稱、括號 () 和冒號 :。函數內的程式碼是縮排的。
此程式碼示範如何定義和呼叫函數:
# This script demonstrates how to define and call functions # Define a function called 'greetings' that prints two lines def greetings(): print("HI, Welcome to programming world of python") print("keep learning") # Print a statement before calling the function print("this is first statement") # Call the 'greetings' function greetings() # Print a statement after calling the function print("this is last statement") # Define a function 'add' that takes two parameters and prints their sum def add(num1, num2): print(int(num1) + int(num2)) # Call the 'add' function with arguments 3 and 4 add(3, 4)
退貨聲明
return 語句在函數中用來向呼叫者傳回(或「回傳」)一個值。當執行return時,函數結束,return後指定的值被傳回函數呼叫的地方。
此程式展示如何在函數中使用 return 語句:
# This script demonstrates the use of return statements in functions # Define a function 'square' that returns the square of a number def square(num): return num * num # Any code after the return statement won't execute # Call the 'square' function with argument 2 and print the result print(square(2)) # Call the 'square' function with argument 4 and print the result print(square(4)) # Call the 'square' function with argument 3, store the result, then print it result = square(3) print(result)
如果語句
if 語句計算一個條件(傳回 True 或 False 的表達式)。
如果條件為 True,則執行 if 語句下的程式碼區塊。
elif :「else if」的縮寫,它允許您檢查多個條件。
當您有多個條件需要評估,並且您想要執行第一個 True 條件的程式碼區塊時,可以使用它。
else:如果前面的 if 或 elif 條件都不為 True,則 else 語句將執行一段程式碼。
# This script demonstrates the use of if-elif-else statements # Set boolean variables for conditions is_boy = True is_handsome = False # Check conditions using if-elif-else statements if is_boy and is_handsome: print("you are a boy & youre handsome") print("hehe") elif is_boy and not (is_handsome): print("Youre a boy but sorry not handsome") else: print("youre not a boy")
如果比較
此程式碼示範了 if 語句中的比較操作:
# This script demonstrates comparison operations in if statements # Define a function to find the maximum of three numbers def max_numbers(num1, num2, num3): if num1 >= num2 and num1 >= num3: return num1 elif num2 >= num1 and num2 >= num3: return num2 else: return num3 # Test the max_numbers function with different inputs print(max_numbers(20, 40, 60)) print(max_numbers(30, 14, 20)) print(max_numbers(3, 90, 10)) print("For min_number") # Define a function to find the minimum of three numbers def min_numbers(num1, num2, num3): if num1 <h2> 猜謎遊戲2 </h2> <p>此腳本透過更多功能改進了猜謎遊戲:<br> </p> <pre class="brush:php;toolbar:false"># This script improves the guessing game with more features import random # Generate a random number between 1 and 20 secret_number = random.randint(1, 20) # Initialize the number of attempts and set a limit attempts = 0 attempt_limit = 5 # Loop to allow the user to guess the number while attempts <h2> For循環 </h2> <p>for 迴圈用於迭代元素序列,例如列表、元組、字串或範圍。 <br> 這段程式碼引入了for循環:<br> </p> <pre class="brush:php;toolbar:false"># List of numbers numbers = [1, 2, 3, 4, 5] # Iterate over each number in the list for number in numbers: # Print the current number print(number) # Output: # 1 # 2 # 3 # 4 # 5 # List of friends friends = ["Roi", "alex", "jimmy", "joseph", "kevin", "tony", "jimmy"] # Iterate over each friend in the list for friend in friends: # Print the name of the current friend print(friend) # Output: # Roi # alex # jimmy # joseph # kevin # tony # jimmy # Use range to generate numbers from 0 to 4 for num in range(5): print(num) # Output: # 0 # 1 # 2 # 3 # 4
指數函數
指數函數是一種數學函數,其中恆定基數被提升為可變指數。
此腳本展示如何使用 math.pow 函數:
# This script demonstrates the use of the exponential function def exponentialFunction(base,power): result = 1 for index in range(power): result = result * base return result print(exponentialFunction(3,2)) print(exponentialFunction(4,2)) print(exponentialFunction(5,2)) #or you can power just by print(2**3) #number *** power
2D List and For Loops
A 2D list (or 2D array) in Python is essentially a list of lists, where each sublist represents a row of the matrix. You can use nested for loops to iterate over elements in a 2D list. Here’s how you can work with 2D lists and for loops:
# This script demonstrates the use of 2D List and For Loops # Define a 2D list (list of lists) num_grid = [ [1, 2, 3], # Row 0: contains 1, 2, 3 [4, 5, 6], # Row 1: contains 4, 5, 6 [7, 8, 9], # Row 2: contains 7, 8, 9 [0] # Row 3: contains a single value 0 ] # Print specific elements in num_grid print(num_grid[0][0]) # Print value in the zeroth row, zeroth column (value: 1) print(num_grid[1][0]) # Print value in the first row, zeroth column (value: 4) print(num_grid[2][2]) # Print value in the second row, second column (value: 9) print("using nested for loops") for row in num_grid : for col in row: print(col)
This is how we can use 2D List and For Loops.
以上是Python 變得簡單:從初學者到進階 |部落格的詳細內容。更多資訊請關注PHP中文網其他相關文章!

每天學習Python兩個小時是否足夠?這取決於你的目標和學習方法。 1)制定清晰的學習計劃,2)選擇合適的學習資源和方法,3)動手實踐和復習鞏固,可以在這段時間內逐步掌握Python的基本知識和高級功能。

Python在Web開發中的關鍵應用包括使用Django和Flask框架、API開發、數據分析與可視化、機器學習與AI、以及性能優化。 1.Django和Flask框架:Django適合快速開發複雜應用,Flask適用於小型或高度自定義項目。 2.API開發:使用Flask或DjangoRESTFramework構建RESTfulAPI。 3.數據分析與可視化:利用Python處理數據並通過Web界面展示。 4.機器學習與AI:Python用於構建智能Web應用。 5.性能優化:通過異步編程、緩存和代碼優

Python在開發效率上優於C ,但C 在執行性能上更高。 1.Python的簡潔語法和豐富庫提高開發效率。 2.C 的編譯型特性和硬件控制提升執行性能。選擇時需根據項目需求權衡開發速度與執行效率。

Python在現實世界中的應用包括數據分析、Web開發、人工智能和自動化。 1)在數據分析中,Python使用Pandas和Matplotlib處理和可視化數據。 2)Web開發中,Django和Flask框架簡化了Web應用的創建。 3)人工智能領域,TensorFlow和PyTorch用於構建和訓練模型。 4)自動化方面,Python腳本可用於復製文件等任務。

Python在數據科學、Web開發和自動化腳本領域廣泛應用。 1)在數據科學中,Python通過NumPy、Pandas等庫簡化數據處理和分析。 2)在Web開發中,Django和Flask框架使開發者能快速構建應用。 3)在自動化腳本中,Python的簡潔性和標準庫使其成為理想選擇。

Python的靈活性體現在多範式支持和動態類型系統,易用性則源於語法簡潔和豐富的標準庫。 1.靈活性:支持面向對象、函數式和過程式編程,動態類型系統提高開發效率。 2.易用性:語法接近自然語言,標準庫涵蓋廣泛功能,簡化開發過程。

Python因其簡潔與強大而備受青睞,適用於從初學者到高級開發者的各種需求。其多功能性體現在:1)易學易用,語法簡單;2)豐富的庫和框架,如NumPy、Pandas等;3)跨平台支持,可在多種操作系統上運行;4)適合腳本和自動化任務,提升工作效率。

可以,在每天花費兩個小時的時間內學會Python。 1.制定合理的學習計劃,2.選擇合適的學習資源,3.通過實踐鞏固所學知識,這些步驟能幫助你在短時間內掌握Python。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境

Dreamweaver Mac版
視覺化網頁開發工具

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。