繁体   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