簡體   English   中英

對 if 語句和函數感到困惑

[英]Confused about if statements and functions

我對 random 模塊非常熟悉,但是當涉及到函數時,我總是被絆倒。 如何使 function 僅在滿足特定條件時出現? 當我試圖驗證我的答案時,它沒有給我 output ...

choice = input ("Which type of password would you like to generate? \n 1. Alphabetical \n")

if choice == 1:
    characters = list(string.ascii_letters)
    def generate_random_abc_password():
            length = int(input("Enter password length: "))

            random.shuffle(characters)
            
            password = []
            for i in range(length):
                    password.append(random.choice(characters))

            random.shuffle(password)

            print("".join(password))
            
    generate_random_abc_password()

似乎是初學者中最常見的錯誤。 當您使用 input() function 時,它會返回一些數字/文本/浮點數或十進制數,但為字符串類型。 例如

x = input("Enter your number")
# If i would input 2, my x variable would contain "2"
# 3 => "3"
# 550 => "550" and so on...

為避免此類問題並以正確的類型存儲您的值,您需要使用 int() function 包裝您的輸入,如下所示

x = int(input(("Enter your number"))
# From now, whenever i prompt any number from my keyboard, it will 
# be an integer number, which i can substract, add, multiply and divide.

就這么簡單。 快樂學習!

您應該將輸入轉換為integer ,因為默認情況下input的數據類型是string

或者,除了更改輸入數據類型之外,您還可以將其與str(1)進行比較,或者將if choice == 1:更改為if choice == '1':

您可以嘗試使用:

import string
import random

choice = int(input ("Which type of password would you like to generate? \n 1. Alphabetical \n"))

if choice == 1:
    characters = list(string.ascii_letters)
    def generate_random_abc_password():
            length = int(input("Enter password length: "))

            random.shuffle(characters)
            
            password = []
            for i in range(length):
                    password.append(random.choice(characters))

            random.shuffle(password)

            print("".join(password))
            
    generate_random_abc_password()

上面的代碼將導致:

Which type of password would you like to generate? 
 1. Alphabetical 
1
Enter password length: 10
MEQyTcspdy

這里的問題是您已經在 if 塊中定義了 characters 變量。 那是你的 function 不知道變量,這就是為什么你應該將字符變量作為輸入傳遞給 function 代碼應該看起來像


choice = input ("Which type of password would you like to generate? \n 1. Alphabetical \n")

if choice == 1:
    characters = list(string.ascii_letters)
    def generate_random_abc_password(characters):
            length = int(input("Enter password length: "))

            random.shuffle(characters)
            
            password = []
            for i in range(length):
                    password.append(random.choice(characters))

            random.shuffle(password)

            print("".join(password))
            
    generate_random_abc_password(characters)


function 的工作方式就像一段獨立的代碼,它接受自己的輸入並返回自己的輸出,或者做一些事情。

正如上面提到的答案所說,輸入也沒有轉換為 int ...

暫無
暫無

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

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