搜尋
首頁後端開發Python教學Python中如何確保使用者輸入有效?

How to Ensure Valid User Input in Python?

請求有效的使用者輸入直至收到

請求使用者輸入時,優雅地處理無效回應而不是崩潰或接受不正確的值至關重要。以下技術可確保獲得有效的輸入:

嘗試/排除異常輸入

使用 try/ except 擷取無法解析的特定輸入。例如:

while True:
    try:
        age = int(input("Please enter your age: "))
    except ValueError:
        print("Sorry, that's not a valid age.")
        continue
    break

附加規則的自訂驗證

有時,可以解析的輸入可能仍然不滿足某些條件。您可以新增自訂驗證邏輯來拒絕特定值:

while True:
    data = input("Enter a positive number: ")
    if int(data) <p><strong>結合異常處理和自訂驗證</strong></p><p>結合這兩種技術來處理無效解析和自訂驗證規則:</p><pre class="brush:php;toolbar:false">while True:
    try:
        age = int(input("Please enter your age: "))
    except ValueError:
        print("Sorry, that's not a valid age.")
        continue
    if age <p><strong>封裝在函數</strong></p><p>要重複使用自定義輸入驗證邏輯,請將其封裝在函數中:</p><pre class="brush:php;toolbar:false">def get_positive_age():
    while True:
        try:
            age = int(input("Please enter your age: "))
        except ValueError:
            print("Sorry, that's not a valid age.")
            continue
        if age <p><strong>進階輸入清理</strong></p><p>您可以建立一個更通用的輸入函數來處理各種驗證場景:</p><pre class="brush:php;toolbar:false">def get_valid_input(prompt, type_=None, min_=None, max_=None, range_=None):
    while True:
        try:
            value = type_(input(prompt))
        except ValueError:
            print(f"Invalid input type. Expected {type_.__name__}.")
            continue
        if max_ is not None and value > max_:
            print(f"Value must be less than or equal to {max_}.")
            continue
        if min_ is not None and value <p>此函數可讓您指定使用者輸入的資料類型、範圍和其他限制。 </p>

以上是Python中如何確保使用者輸入有效?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
Python是否列表動態陣列或引擎蓋下的鏈接列表?Python是否列表動態陣列或引擎蓋下的鏈接列表?May 07, 2025 am 12:16 AM

pythonlistsareimplementedasdynamicarrays,notlinkedlists.1)他們areStoredIncoNtiguulMemoryBlocks,mayrequireRealLealLocationWhenAppendingItems,EmpactingPerformance.2)LinkesedlistSwoldOfferefeRefeRefeRefeRefficeInsertions/DeletionsButslowerIndexeDexedAccess,Lestpypytypypytypypytypy

如何從python列表中刪除元素?如何從python列表中刪除元素?May 07, 2025 am 12:15 AM

pythonoffersFourmainMethodStoreMoveElement Fromalist:1)刪除(值)emovesthefirstoccurrenceofavalue,2)pop(index)emovesanderturnsanelementataSpecifiedIndex,3)delstatementremoveselemsbybybyselementbybyindexorslicebybyindexorslice,and 4)

試圖運行腳本時,應該檢查是否會遇到'權限拒絕”錯誤?試圖運行腳本時,應該檢查是否會遇到'權限拒絕”錯誤?May 07, 2025 am 12:12 AM

toresolvea“ dermissionded”錯誤Whenrunningascript,跟隨台詞:1)CheckAndAdjustTheScript'Spermissions ofchmod xmyscript.shtomakeitexecutable.2)nesureThEseRethEserethescriptistriptocriptibationalocatiforecationAdirectorywherewhereyOuhaveWritePerMissionsyOuhaveWritePermissionsyYouHaveWritePermissions,susteSyAsyOURHomeRecretectory。

與Python的圖像處理中如何使用陣列?與Python的圖像處理中如何使用陣列?May 07, 2025 am 12:04 AM

ArraysarecrucialinPythonimageprocessingastheyenableefficientmanipulationandanalysisofimagedata.1)ImagesareconvertedtoNumPyarrays,withgrayscaleimagesas2Darraysandcolorimagesas3Darrays.2)Arraysallowforvectorizedoperations,enablingfastadjustmentslikebri

對於哪些類型的操作,陣列比列表要快得多?對於哪些類型的操作,陣列比列表要快得多?May 07, 2025 am 12:01 AM

ArraySaresificatificallyfasterthanlistsForoperationsBenefiting fromDirectMemoryAcccccccCesandFixed-Sizestructures.1)conscessingElements:arraysprovideconstant-timeaccessduetocontoconcotigunmorystorage.2)iteration:araysleveragececacelocality.3)

說明列表和數組之間元素操作的性能差異。說明列表和數組之間元素操作的性能差異。May 06, 2025 am 12:15 AM

ArraySareBetterForlement-WiseOperationsDuetofasterAccessCessCessCessCessCessCessCessAndOptimizedImplementations.1)ArrayshaveContiguucuulmemoryfordirectAccesscess.2)列出sareflexible butslible butslowerduetynemicizing.3)

如何有效地對整個Numpy陣列進行數學操作?如何有效地對整個Numpy陣列進行數學操作?May 06, 2025 am 12:15 AM

在NumPy中进行整个数组的数学运算可以通过向量化操作高效实现。1)使用简单运算符如加法(arr 2)可对数组进行运算。2)NumPy使用C语言底层库,提升了运算速度。3)可以进行乘法、除法、指数等复杂运算。4)需注意广播操作,确保数组形状兼容。5)使用NumPy函数如np.sum()能显著提高性能。

您如何將元素插入python數組中?您如何將元素插入python數組中?May 06, 2025 am 12:14 AM

在Python中,向列表插入元素有兩種主要方法:1)使用insert(index,value)方法,可以在指定索引處插入元素,但在大列表開頭插入效率低;2)使用append(value)方法,在列表末尾添加元素,效率高。對於大列表,建議使用append()或考慮使用deque或NumPy數組來優化性能。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

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

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具