」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > Python 變得簡單:從初學者到進階 |部落格

Python 變得簡單:從初學者到進階 |部落格

發佈於2024-11-05
瀏覽:571

Python Made Simple: Beginner to Advanced | Blog

Python Course Code Examples

This is a Documentation of the python code i used and created , for learning python.
Its easy to understand and Learn.Feel free to learn from here.
I will update the blog with more advanced topics soon.

Table of Contents

  1. First Program
  2. Variables and Data Types
  3. Strings
  4. Numbers
  5. Getting Input from Users
  6. Building a Basic Calculator
  7. First Madlibs
  8. Lists
  9. List Functions
  10. Tuples
  11. Functions
  12. Return Statement
  13. If Statements
  14. If Comparisons
  15. Guessing Game 2
  16. For Loop
  17. Exponential Function
  18. 2D List and For Loops

First Program

This program is use to show how print() command works.

# 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)

Variables and Data Types

A variable in Python is a reserved memory location to store values.
Data types define the type of data a variable can hold ie integer,float, string etc.

# 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   ".")

Strings

Sequences of characters used to store and manipulate text. They are created by enclosing text in single quotes ('Hello'), double quotes ("Hello"), or triple quotes for multi-line strings ('''Hello'''). Example: "Hello, World!".

# 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"))

Numbers

Numbers are used for various numeric operations and math functions:

# 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

Getting Input from Users

This program is used to show how to use the input() function to get user 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   " .")

Building a Basic Calculator

This program creates a simple calculator that adds two numbers:

# 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)

First Madlibs

This program creates a simple Mad Libs game:

# 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   ".")

Lists

A list is a collection of items in Python that is ordered and changeable. Each item (or element) in a list has an index, starting from 0. Lists can contain items of different data types (like integers, strings, or even other lists).
A list is defined using square brackets [], with each item separated by a comma.

# 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)

List Functions

This script showcases various list methods:

# 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)

Tuples

A tuple is a collection of items in Python that is ordered but unchangeable (immutable). Once you create a tuple, you cannot add, remove, or change its elements. Like lists, tuples can contain items of different data types.
A tuple is defined using parentheses (), with each item separated by a comma.

# 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)

Functions

A function is a block of reusable code that performs a specific task. Functions can take inputs (called arguments), process them, and return an output. Functions help organize code, make it more modular, and avoid repetition.
n Python, a function is defined using the def keyword, followed by the function name, parentheses (), and a colon :. The code inside the function is indented.
This code demonstrates how to define and call functions:

# 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 Statement

he return statement is used in a function to send back (or "return") a value to the caller. When return is executed, it ends the function, and the value specified after return is sent back to where the function was called.

This program shows how to use the return statement in functions:

# 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 Statements

The if statement evaluates a condition (an expression that returns True or False).
If the condition is True, the block of code under the if statement is executed.
elif : Short for "else if," it allows you to check multiple conditions.
It is used when you have multiple conditions to evaluate, and you want to execute a block of code for the first True condition.
else: The else statement runs a block of code if none of the preceding if or elif conditions are True.

# 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 Comparisons

This code demonstrates comparison operations in if statements:

# 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 



Guessing Game 2

This script improves the guessing game with more features:

# 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 



For Loop

A for loop is used to iterate over a sequence of elements, such as a list, tuple, string, or range.
This code introduces the for loop:

# 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

Exponential Function

Exponential functions are mathematical functions where a constant base is raised to a variable exponent.
This script shows how to use the math.pow function:

# 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.

版本聲明 本文轉載於:https://dev.to/dipsankadariya/2024-python-full-course-blog-documentation-5k?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>
  • 僅使用 Python 建構前端
    僅使用 Python 建構前端
    對於專注於後端的開發人員來說,前端開發可能是一項艱鉅的、甚至是噩夢般的任務。在我職業生涯的早期,前端和後端之間的界線是模糊的,每個人都被期望能夠處理這兩者。 CSS,尤其是,是一場持續不斷的鬥爭;這感覺像是一個不可能的任務。 雖然我喜歡前端工作,但 CSS 對我來說仍然是一個複雜的挑戰,特別是因為...
    程式設計 發佈於2024-11-05
  • 如何在 Laravel 中執行 Cron 作業
    如何在 Laravel 中執行 Cron 作業
    在本教程中,我將向您展示如何在 Laravel 中運行 cron 作業,但最重要的是,我們會讓事情對我們的學生來說簡單易行。在建立 Laravel 應用程式時,我們將探索如何在您自己的電腦上設定和執行這些自動化任務。 首先,什麼是 cron 作業?將其視為您網站的私人助理 - 一個從不睡覺並且總是...
    程式設計 發佈於2024-11-05
  • 填滿如何影響內聯元素的間距以及如何解決衝突?
    填滿如何影響內聯元素的間距以及如何解決衝突?
    內聯元素上的填充:效果和限制內聯元素上的填充:效果和限制根據源碼,在內聯元素的頂部和底部添加內邊距並不影響周圍元素的間距。然而,「填充將與其他內聯元素重疊」這一說法表明,在某些特定情況下,填充確實會產生影響。 了解重疊填充填充主要影響它應用於的元素,增加其垂直邊框。在正常情況下,這不會導致與相鄰的內...
    程式設計 發佈於2024-11-05
  • Django 基於類別的視圖變得簡單
    Django 基於類別的視圖變得簡單
    眾所周知,django在開發Web應用程式時使用MVT(模型-視圖-模板)進行設計。 View 本身是一個可呼叫的,它接受請求並回傳回應。它不僅僅是一個函數,因為 Django 提供了一種稱為「基於類別的視圖」的東西,因此開發人員可以使用基於類別的方法或您可以說 OOP 方法來編寫視圖。這個基於類...
    程式設計 發佈於2024-11-05
  • 使用 VAKX 建立您的無程式碼 AI 代理
    使用 VAKX 建立您的無程式碼 AI 代理
    If you’ve been keeping up with the AI space, you already know that AI agents are becoming a game-changer in the world of automation and customer inter...
    程式設計 發佈於2024-11-05
  • 這裡是我如何在 jQuery Datatable 中實作基於遊標的分頁。
    這裡是我如何在 jQuery Datatable 中實作基於遊標的分頁。
    在 Web 應用程式中處理大型資料集時,分頁對於效能和使用者體驗至關重要。標準的基於偏移量的分頁(通常與資料表一起使用)對於大型資料集可能效率低。 基於遊標的分頁提供了一種效能更高的替代方案,特別是在處理即時更新或大量資料載入時。在本文中,我將引導您了解如何在 jQuery DataTable 中...
    程式設計 發佈於2024-11-05
  • 為什麼同步引擎可能是 Web 應用程式的未來
    為什麼同步引擎可能是 Web 應用程式的未來
    在不断发展的 Web 应用程序世界中,效率、可扩展性和无缝实时体验至关重要。传统的 Web 架构严重依赖于客户端-服务器模型,这些模型可能难以满足现代对响应能力和同步的需求。这就是同步引擎发挥作用的地方,它为开发人员当今面临的许多挑战提供了一个有前途的解决方案。但同步引擎到底是什么?为什么它们可能是...
    程式設計 發佈於2024-11-05
  • Python 電腦視覺簡介(第 1 部分)
    Python 電腦視覺簡介(第 1 部分)
    注意:在这篇文章中,我们将仅使用灰度图像以使其易于理解。 什么是图像? 图像可以被认为是值的矩阵,其中每个值代表像素的强度。图像格式主要分为三种类型: Binary:此格式的图像由值为 0(黑色)和 1(白色)的单个二维矩阵表示。这是最简单的图像表示形式。 Grey-Scale:在此...
    程式設計 發佈於2024-11-05
  • 網站 HTML 程式碼
    網站 HTML 程式碼
    我一直在嘗試建立一個與航空公司相關的網站。我只是想確認我是否可以使用人工智慧生成程式碼來產生整個網站。 HTML 網站是否相容於博客,或者我應該使用 JavaScript?這是我用作演示的程式碼。 <!DOCTYPE html> <html lang="en">[](url...
    程式設計 發佈於2024-11-05
  • 像程式設計師一樣思考:學習 Java 基礎知識
    像程式設計師一樣思考:學習 Java 基礎知識
    本文介紹了 Java 程式設計的基本概念和結構。它首先介紹了變數和資料類型,然後討論了操作符和表達式,以及控制流程。其次,它解釋了方法和類,然後介紹了輸入和輸出操作。最後,本文透過一個工資計算器的實際範例展示了這些概念的應用。 像程式設計師一樣思考:掌握Java 基礎1. 變數與資料型別 ]Java...
    程式設計 發佈於2024-11-05
  • PHP GD 可以比較兩個影像的相似性嗎?
    PHP GD 可以比較兩個影像的相似性嗎?
    PHP GD 可以確定兩個影像的相似度嗎? 正在考慮的問題詢問是否可以使用以下命令確定兩個圖像是否相同PHP GD 通過比較它們的差異。這需要獲取兩個影像之間的差異並確定它是否完全由白色(或任何統一的顏色)組成。 根據所提供的答案,雜湊函數(如其他回應所建議的)不適用於此情境。比較必須涉及圖像內容而...
    程式設計 發佈於2024-11-05
  • 使用這些鍵編寫進階測試(JavaScript 中的測試需求)
    使用這些鍵編寫進階測試(JavaScript 中的測試需求)
    在本文中,您將學習每個高級開發人員都應該了解的 12 個測試最佳實踐。您將看到 Kent Beck 的文章“Test Desiderata”的真實 JavaScript 範例,因為他的文章是用 Ruby 編寫的。 這些屬性旨在幫助您編寫更好的測試。了解它們還可以幫助您在下一次工作面試中取得好成績。...
    程式設計 發佈於2024-11-05
  • 透過將 matlab/octave 演算法移植到 C 來實現 AEC 的最佳解決方案
    透過將 matlab/octave 演算法移植到 C 來實現 AEC 的最佳解決方案
    完畢!對自己有點印象。 我們的產品需要迴聲消除功能,確定了三種可能的技術方案, 1)利用MCU偵測audio out和audio in的音訊訊號,編寫演算法計算兩側聲音訊號的強度,根據audio out和audio in的強弱在兩個通道之間進行可選的切換,實現半雙工通話效果,但現在市面上都是全雙工...
    程式設計 發佈於2024-11-05
  • 逐步建立網頁:探索 HTML 中的結構和元素
    逐步建立網頁:探索 HTML 中的結構和元素
    ?今天標誌著我軟體開發之旅的關鍵一步! ?我編寫了第一行程式碼,深入研究了 HTML 的本質。涵蓋的元素和標籤。昨天,我探索了建立網站的拳擊技術,今天我透過創建頁眉、頁腳和內容區域等部分將其付諸實踐。我還添加了各種 HTML 元素,包括圖像元素和連結元素,甚至嘗試在單頁網站上進行內部連結。看到這些部...
    程式設計 發佈於2024-11-05
  • 專案創意不一定是獨特的:原因如下
    專案創意不一定是獨特的:原因如下
    在創新領域,存在一個常見的誤解,即專案創意需要具有開創性或完全獨特才有價值。然而,事實並非如此。我們今天使用的許多成功產品與其競爭對手共享一組核心功能。讓他們與眾不同的不一定是想法,而是他們如何執行它、適應用戶需求以及在關鍵領域進行創新。 通訊應用案例:相似但不同 讓我們考慮一下 ...
    程式設計 發佈於2024-11-05

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3