簡體   English   中英

如何更改 function 中的值,然后將其應用於 while 循環?

[英]How to change the value within function, then apply it to while loop?

所以我有這個function:

def check_List(listname, input_num):
    if input_num in listname:
        print('Duplicated Number')
        input_num=0
        return input_num

目的是更改我為 input_num 輸入的任何內容,如果它是列表中的重復項並且它有效,則變為 0。 但是,我有一個 while 循環語句,說明如果輸入小於 1 或大於 9,它將 go 進入循環。 當我將此功能放入循環時,它確實提到它是重復的,但它會保留輸入的原始值。

這是我的完整代碼:

guess=[]

while guess != rnd:
    count=0
    strike=0
    ball=0
    
    guess1=int(input("Input First Number: "))
    while guess1>9 or guess1<1:
        print('Input a number between 1-9')
        guess1=int(input("Input First Number: "))
    guess.append(guess1)

    guess2=int(input('Input Second number: '))
    check_List(guess,guess2)
    print(guess2)
    while guess2>9 or guess2<1:
        print('Input a number between 1-9')
        guess2=int(input("Input Second Number: "))
    
    guess.append(guess2)


    guess3=int(input('Input Thrid number: '))
    while guess3>9 or guess3<1:
        print('Input a number between 1-9')
        guess3=int(input("Input Thrid Number: "))
    guess.append(guess3)

    guess4=int(input('Input Fourth number: '))
    while guess4>9 or guess4<1:
        print('Input a number between 1-9')
        guess4=int(input("Input Fourth Number: "))
    guess.append(guess4)
    print(guess, rnd)

我認為您觀察到的行為可能會喜歡這樣一個事實,即您僅在一個輸入上使用check_List 我建議稍微清理一下代碼:

counting= ['first', 'second', 'third','fourth']
guess = []
while len(guess) < 4:
    c_guess = int(input(f"Input {counting[len(guess)]} Number: "))
   
    if c_guess in guess:
        print('Duplicated Number')
        continue
    
    if 9 > c_guess >= 1:
        guess.append(c_guess)
        continue
    
    print('Input a number between 1-9')

您可以通過處理錯誤(非整數)輸入來進一步改進它:

try:
    c_guess = int(input(f"Input {counting[len(guess)]} Number: "))
except:
    print('Not a valid integer number.')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM