条件后未定义变量

时间:2019-02-14 01:32:30

标签: python variables

这应该是Python 3中的密码生成器程序。

import string
from random import *

print("Type Yes or No For The Following Questions:")

letters = raw_input("Do you want letters in your passcode?" )
if raw_input == 'Yes': chars1 = string.ascii_letters 
elif raw_input == 'No': chars1  = ""

digits = raw_input("Do you want digits in your passcode?" )
if raw_input == 'Yes':chars2 = string.digits
elif raw_input == 'No': chars2 = ""

symbols = raw_input("Do you want symbols in your passcode?" )
if raw_input == 'Yes': chars3 = string.punctuation 
elif raw_input == 'No': chars3  = ""

requestedlength = input("What passcode length do you want? Type any   number: ")
length = int(requestedlength)

chars = chars1 + chars2 + chars3

passcode = raw_input("Type Enter To Generate Random Passcode: ")
print("".join(choice(chars) for x in range((length))))

我在这里做错了什么?该错误指出未定义chars1 chars2和chars3。在条件语句中更改这些变量后,如何定义这些变量?我是Python的新手,如果代码混乱,我深表歉意 :(

编辑:谢谢大家的回答!

3 个答案:

答案 0 :(得分:1)

因为您的if语句没有问正确的事情

您在输入中设置了一些变量

letters = raw_input("Do you want letters in your passcode?" )

然后询问raw input是否为“是”(从未如此)

if raw_input == 'Yes': chars1 = string.ascii_letters 

所以您的if语句始终为false,并且变量(chars1等)永远都不会被设置,因此您会收到错误消息

要解决此问题,只需更改您的if语句

if letters == 'Yes': chars1 = string.ascii_letters 

答案 1 :(得分:0)

在其他循环中,将if语句中的“输入”拼写更改为“字母”等:

double

答案 2 :(得分:0)

这就是我的工作方式:

import string
from random import *

print("Type Yes or No For The Following Questions:")

letters = input("Do you want letters in your passcode?" )
if letters == 'Yes': chars1 = string.ascii_letters 
elif letters == 'No': chars1  = ""

digits = input("Do you want digits in your passcode?" )
if digits == 'Yes':chars2 = string.digits
elif digits == 'No': chars2 = ""

symbols = input("Do you want symbols in your passcode?" )
if symbols == 'Yes': chars3 = string.punctuation 
elif symbols == 'No': chars3  = ""

requestedlength = input("What passcode length do you want? Type any   number: ")
length = int(requestedlength)

chars = chars1 + chars2 + chars3

passcode = input("Type Enter To Generate Random Passcode: ")
print("".join(choice(chars) for x in range((length))))