- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我制作了一个程序来存储您输入的登录详细信息,并允许您使用它登录到菜单的主要部分。例如,当所有数据类型都是字符串时,一切都运行良好; modea = input("Etc")
为了允许用户通过输入与选项相对应的数字输入来选择选项,例如“2”,它应该在满足 if modea == 2
时调用其分配的函数。语句,但如果我尝试将字符串更改为整数数据类型,例如 modea = int(input("Etc"))
,即使我输入了预期的输入,循环也永远不会停止并继续运行,就好像我什么都没输入一样,这与简单地使用 modea = input("etc")
相反它将所有内容都视为一个字符串,它仍然会接受数字输入并执行其分配的操作,但如果数据类型是整数则不会?
我在这里添加了完整的代码以使其更有意义,大多数代码都可以按预期运行而被忽略,但我似乎无法理解 logged()
是怎么回事。我试图获取 modea = int(input("etc"))
的代码的功能部分通过在满足 if 语句时终止其循环来工作,但它只是继续循环,就好像一切都为空一样。帮助将不胜感激。
#import modules
import time
import sys
import re
#Initialise variables that could help with error handling
name = ""
mode = ""
username = ""
password = ""
addusername = ""
addpassword = ""
exit = ""
modea = ""
new_app = ""
new_pass = ""
quit = ""
#Dictionary to store more than one set of login details
vault = {}
#Lists to store website names and passwords
appvault = []
passvault = []
#FIRST MENU AND REGISTERING LOGIN DETAILS -----------------------------------------------------------------------------------------------------------------------------------------
def menu(): #The menu function is the 1st menu that asks the user to either register their login details or to login with existing login details saved into the vault dictionary
print("--------------------------*ENTERING THE MAIN MENU*-----------------------------------\n") #triple """ used to effectively format the menu
mode = input(str("""Hello {}, below are the modes that you can choose from:\n
##########################################################################
a) Login with username and password
b) Register as a new user
To select a mode, enter the corresponding letter of the mode below
##########################################################################\n
> """.format(name))).strip() #greets user and removes any white space
return mode #returns the input
def login(username, password): #The login function is where the user logins in with existing registered details in the vault dictionary
if len(vault) > 0 : #user has to append usernames and passwords before it asks for login details
print("Welcome {} to the login console".format(name))
noloop = True #Starts a loop if True will begin looping
while noloop:
addusername = input("Please enter username: ")
if addusername == "":
print("Username not entered, try again!")
continue #returns to the beginning of the while loop if null
addpassword = input("Please enter password: ")
if addpassword == "":
print("Password not entered, try again!")
continue #returns to the beginning of the while loop if null
try:
if vault[addusername] == addpassword: #If the username and password match with the login details appended into the dictionary, it will count as matching details.
print("Username matches!")
print("Password matches!")
print("Logging into password vault...\n")
noloop = logged() #jumps to logged function and tells the user they are logged on
return noloop #to return the noloop depending on users option (True or False)
except KeyError: #the except keyerror recognises the existence of the username and password in the list
print("The entered username or password is not found!")
else:
print("You have no usernames and passwords stored!") #When the user selects option A before adding any login details to the dictionary
return True #returning to the start of the loop when the else statement is printed
def register(): #example where the username is appended. Same applies for the password
global username #initialises global variables
global password
print("Please create a username and password into the password vault.\n")
while True:
validname = True #whileloop will loop the username variable and while True it runs the loop
while validname:
username = input("Please enter a username you would like to add to the password vault. NOTE: Your username must be at least 3 characters long: ").strip().lower()
if not username.isalnum(): #handles usernames with no input, contain spaces between them or have symbols in them.
print("Your username cannot be null, contain spaces or contain symbols \n")
elif len(username) < 3: #any username with less than 3 characters is rejected and looped back
print("Your username must be at least 3 characters long \n")
elif len(username) > 30: #any username with more than 30 characters is rejected and looped back
print("Your username cannot be over 30 characters long \n")
else:
validname = False #whileloop is False will mean the loop will break and proceed onto asking password
validpass = True #whileloop will loop the password variable and while True it runs the loop
while validpass:
password = input("Please enter a password you would like to add to the password vault. NOTE: Your password must be at least 8 characters long: ").strip().lower()
if not password.isalnum(): #handles null input passwords, passwords that contain spaces or symbols
print("Your password cannot be null, contain spaces or contain symbols \n")
elif len(password) < 8: #passwords that are less than 8 characters long are rejected and loops back
print("Your password must be at least 8 characters long \n")
elif len(password) > 20: #passwords that are more than 20 characters long are rejected and loops back
print("Your password cannot be over 20 characters long \n")
else:
validpass = False #The validpass has to be True to stay in the function, otherwise if it is false, it will execute another action, in this case the password is appended.
vault[username] = password #the appending process of username and passwords to the dictionary
validinput = True #whileloop asking for the user if they want to quit or add more login details
while validinput:
exit = input("\nDo you want to register more usernames and passwords? Enter 'end' to exit or any key to continue to add more username and passwords:\n> ")
if exit in ["end", "End", "END"]: #if input matches these conditions, the loop will then break and thus jump back to the main menu
return #returns outputs to the called function
else:
validinput = False #if user decides not to quit and to add more login details, then register is called and the process of asking for login input repeats
register()
return register #returns login details to the function
#LOGGED ONTO THE PASSWORD AND WEBSITE APP ADDING CONSOLE------------------------------------------------------------------------------------------------------------------------
def logged(): #The logged function is the 2nd menu where the user is able to access after logging in with their registered login details
print("-----------------------------*ENTERING THE PASSWORD VAULT MENU*-----------------------------------\n")
print("You are logged in, welcome to the password vault console.")
keeplooping = True #whileloop that is True will keep the menu in a loop
while keeplooping:
try:
modea = int(input("""Below are the options you can choose from in the password vault console:
##########################################################################\n
1) Find the password for an existing website/app
2) Add a new website/app and a new password for it
3) Summary of the password vault
4) Exit
##########################################################################\n
> """))
except ValueError:
print("Please enter a valid option!")
if modea == 1: #if the user enters 1 as instructed, then they have decided to choose to find existing apps and passwords
viewapp() #viewapp function is called
elif modea == 2: #if user enters 2 as instructed, then they have decided to add new app/websites and the passwords for it
addapp() #addapp function is called
elif modea == 3: #if the user enters 3 as instructed, then they have decided to look at the summary of passwords entered so far
summary() #summary function is called
elif modea == 4: #if the user enters 4 as instructed, then they have deicided to quit the entire program. All loops stop and program ends with print statement saying "Goodbye"
keeplooping = False
print("*Exiting program*\n")
time.sleep(2)
print("############################################################")
print("Goodbye user and thanks for using the password vault program")
print("############################################################")
return keeplooping
else:
print("That was not a valid option, please try again: ")
validintro = False
def viewapp(): #The viewapp function is the 1st option of the password and vault menu that allows the user to view the app/websites and passwords stored so far
if len(appvault) > 0: #The website/apps and passwords are only shown once the user has entered a set of the info, otherwise no info will be shown
print("""Below are the details of the website/apps and passwords stored so far:
(NOTE: Websites/apps and passwords are shown in order of being appended; 1st password is for 1st website, etc...\n""")
for app in appvault:
print("Here are the website/app you have stored:")
print("- {}\n".format(app)) #Website/app is printed out here
if len(passvault) > 0 : #The website/apps and passwords are only shown once the user has entered a set of the info, otherwise no info will be shown
for code in passvault:
print("Here are the password you have stored for the websites/apps: ")
print("- {}\n".format(code)) #The passwords are printed out here
else:
print("You have no apps or passwords entered yet!")
def addapp():
while True:
validapp = True
while validapp:
new_app = input("Enter the new website/app name: ").strip().lower()
if len(new_app) > 20: #if the user enters a website with more than 20 characters, it is rejected and loops back and asks for input again
print("Please enter a new website/app name with no more than 20 characters: ")
elif len(new_app) < 1: #if the user enters nothing, program loops back and asks for input again
print("Please enter a valid new website/app name: ")
else:
validapp = False
appvault.append(new_app)
validnewpass = True
while validnewpass:
new_pass = input("Enter a new password to be stored in the passsword vault: ").strip()
if not new_pass.isalnum(): #checks if the entered username has spaces, or symbols or is a null input, which would be rejected and the program will loop back
print("Your password for the website/app cannot be null, contain spaces or contain symbols \n")
elif len(new_pass) < 8: #the password must be at least 8 characters long to be accepted as valid
print("Your new password must be at least 8 characters long: ")
elif len(new_pass) > 20: #the password must not exceed 20 characters, otherwise it would be rejected and will loop back
print("Your new password cannot be over 20 characters long: ")
else:
validnewpass = False
passvault.append(new_pass)
validquit = True
while validquit:
quit = input("\nDo you want to enter more websites/apps and passwords? Enter 'end' to exit or any key to continue to add more website/app names and passwords for them: \n> ")
if quit in ["end", "End", "END"]:
return
else:
validquit = False
addapp()
return addapp
def summary(): #The summary function is a print statement of how many password have been stored, the passwords with the longest or shortest characters are also displayed
if len(passvault) > 0: #The user must have entered at least 1 password before the summary option can be viewed
print("----------------------------------------------------------------------")
print("Here is a summary of the passwords stored in the password vault:\n")
print("The number of passwords stored so far:", len(passvault)) #len counts the amount of passwords stored in the passvault list
print("Passwords with the longest characters: ", max(new_pass for (new_pass) in passvault)) #max finds the passwords appended in the passvault list with the longest password
print("Passwords with the shortest charactrs: ", min(new_pass for (new_pass) in passvault)) #min finds the passwords appended in the passvault list with the shortet password
print("----------------------------------------------------------------------")
else:
print("You have no passwords entered yet!")
#Main routine
print("Welcome user to the password vault program")
print("In this program you will be able to store your usernames and passwords in password vaults and view them later on.\n")
validintro = False
while not validintro:
name = input(str("Greetings user, what is your name?: ")).lower().strip()
if not re.match("^[a-z]*$", name):
print("Your name must only contain letters from a-z: ")
elif len(name) < 1:
print("Please enter a name that is valid: ")
elif len(name) > 30:
print("Please enter a name with no more than 30 characters long: ")
else:
validintro = True
print("Welcome to the password vault program {}.\n".format(name))
#The main program to run in a while loop for the program to keep on going back to the menu part of the program for more input till the user wants the program to stop
validintro = False
while not validintro:
chosen_option = menu()
validintro = False
if chosen_option in ["a", "A"]:
validintro = not login(username, password)
elif chosen_option in ["b", "B"]:
register()
else:
print("""That was not a valid option, please try again:\n """)
validintro = False
最佳答案
你有一个缩进错误。
您的 while keeplooping:
循环在 logged()
中只包含 try/except
block ,因此它会一遍又一遍地循环。我想你想缩进它下面的 if
语句。
根据评论编辑:
当您 try/except
到达 except
时,它会打印语句然后继续。您没有在 except
语句中包含任何内容来告诉 while 循环重新开始。由于 modea
的分配失败,因此未分配它并在您尝试引用它时导致错误。如果您想在用户输入错误值时尝试其他输入,您可以使用 continue
:
except ValueError:
print("Please enter a valid option!")
continue
这将导致整个指令字符串再次打印——可能有更好的逻辑,但至少可以防止错误。
关于python-3.x - python : Unable to terminate loop with different type of variable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45362296/
我知道这类问题已经得到解答,但就我而言,我已经尝试了所有配置,但仍然不起作用。我需要对我的配置有一个新的看法(我确信我错过了一些东西)。两个附加程序都会记录所有级别 我想将所有包的信息 >= 记录到控
我正在对 Windows 移动设备上的代码性能进行一些基准测试,并注意到某些算法在某些主机上的表现明显更好,而在其他主机上则明显更差。当然,考虑到时钟速度的差异。 供引用的统计数据(所有结果均由同一个
我有一个程序可以计算多边形的面积和周长。程序还会确认面积和周长的计算结果是否与预期结果相同。 我不明白发生了什么,但确认面积和周长是否与预期相同的验证部分无法正常工作。 例如,我现在测试并在所有情况下
Codepen :(对于那些想直接进入的人来说,这是一个代码笔。在 Chrome 和 IE 中尝试一下,看看结果的不同) 我正在尝试使用 css3 转换/过渡,因为它们比 jquery 效果更流畅。
我有几个不同的正则表达式要在给定文本中匹配和替换。 regex1 :如果文本包含单词“Founder”,则将所有文本替换为首席执行官 正则表达式2:如果文本包含9位数字,则将其替换为NUM 我尝试使用
我编写了多线程应用程序,它从每个线程的数据库连接到一些电子邮件帐户。我知道 JavaMail 没有任何选项可以使用 SOCKS5 进行连接,因此我决定通过 System.setProperty 方法使
如您所见,这是我当前 Storyboard的不同设备预览。底部的透明绿色被另一个 View Controller 占用,但需要为每个不同的尺寸类固定间距。我尝试将 Storyboard 中的宽度和高度
我正在创建一个游戏,我需要能够改变玩家 Sprite 的速度。我认为最好的选择是通过重力影响 Sprite 。为了给用户运动的感觉,我希望背景以完全相同的速度向相反的方向移动。 我怎样才能给背景一个不
我正在查看BTrees库并注意到有多个 TreeSet (和其他)类,例如 BTrees.IOBTree.TreeSet BTrees.OOBTree.TreeSet BTrees.LFBTree.T
我有一个小型 C++ 库,必须为 armeabi 和 armeabi7a 编译。我还有一个非常大的 c++ 库,只需要为 armeabi 编译。现在正在为两种架构编译它们(使用 NDK),但这使我的
我需要根据站点的当前部分稍微更改主题。 似乎 MuiThemeProvider 只在加载时设置 muiTheme;但需要在 props 变化时更新。 如何做到这一点? 最佳答案 您可以尝试将主题放在包
如何创建两个每个都有自己的计数器的 lSTListing 环境? 如果我使用例如 \lstnewenvironment{algorithm}[2]{ \renewcommand\lstlist
我想使用 Travis-CI 和 Github 基于分支设置部署。 IE。 - 如果我们从 develop 构建- 然后执行 /deploy.rb使用 DEV 环境主机名,如果 master - 然后
我有一个带有数据验证的 WPF MVVM 数据表单窗口。很多控件都是文本框。目前,数据绑定(bind)触发器设置为默认值,即。 e.失去焦点。这意味着仅在可能完全填写字段时才对其进行验证。所以当删除一
我有许多应用程序的内容页面,并最终为每个内容页面编写了很多 View 模型。例如。如果我有一个包含项目组的列表,我将有一个 ShowAllViewModel并绑定(bind)到内容页面和列表中单个项目
我有一个通用 View 和 4 个其他 View 。我在通用 View 中使用 Bootstrap 选项卡(导航选项卡)。我希望其他 4 个 View 成为通用 View 中 4 个选项卡的内容。由于
我希望针对 Maven 发布插件的不同目标有不同的配置选项。故事是这样的: 我正在将 Git 用于 SCM。我希望release:prepare插件在本地完成所有操作,并让release:perfor
我正在为一个项目使用AbstractTableModel制作一个自定义TableModel,并且我需要找到一种方法让复选框显示在某些行上,而不是其他行上。我已经实现了 getColumn 方法,但我希
摘自《Javascript 忍者的 secret 》一书: EVENTS ARE ASYNCHRONOUS Events, when they happen, can occur at unpredi
我正在尝试配置我的第一个 GWT 记录器,到目前为止,我已经将日志消息打印到我的 JS 控制台(FF 的 Firebug): 最终,我希望非SEVERE 消息转到consoleHa
我是一名优秀的程序员,十分优秀!