程序在if语句中突然关闭

时间:2018-03-14 08:40:54

标签: python python-3.x

这是我的代码中不起作用的部分。 else语句工作正常,但当password错误时,程序突然关闭。

if logged_in == 'admin':
            tries = -3
            while tries < 0:
                password = input("enter supersecret password. ")
                if password != 'strange alien colour':
                    print("incorrect password. Try again. " + tries + " tries left.")
                    tries = tries + i
                else:
                    print("Hello admin, would you like to see a status report?")
                    input()
                    import sys
                    sys.exit(0)

这是整个代码:

users = ['anonymous', 'me', 'bill', 'me123']
i = 1
while i == 1:
    logged_in = input("Username:\n")

    if logged_in == 'admin':
        tries = -3
        while tries < 0:
            password = input("enter supersecret password. ")
            if password != 'strange alien colour':
                print("incorrect password. Try again. " + tries + " tries left.")
                tries = tries + i
            else:
                print("Hello admin, would you like to see a status report?")
                input()
                import sys
                sys.exit(0)

    if logged_in in users:
        print ("Hello " + logged_in + ", welcome back!")
        break

    else:
        print ("invalid username. Do you wish to create an account? (Y/N)\n")
        create_account = input()
        if create_account == 'Y' or create_account == 'y':
            new_username = input("Enter new username: ")
            print("You have creted a new account. Welcome, " + new_username)
            users.append(new_username)
        else:
            print ("Goodbye.")
            break
input()

2 个答案:

答案 0 :(得分:4)

你的错误是在这一行

print("incorrect password. Try again. " + tries + " tries left.")

tries是一个int,而其他部分是字符串。由于无法添加这两种类型,因此会出现错误

TypeError: must be str, not int

要解决此问题,只需将行更改为

即可
print("incorrect password. Try again. " + str(tries) + " tries left.")

在不相关的说明中,通常建议导入位于程序的顶部。

答案 1 :(得分:1)

print("incorrect password. Try again. " + str(tries) + " tries left.")

这是不正确的,因为try是一个整数,因此不能与引号中的其他两个部分连接,因为它们是字符串,需要首先转换为字符串才能这样做。例如

#Get the Data
require(tidyverse)
require(rvest)

#specify the url
url <- 'https://www.travsport.se/sresultat?kommando=tevlingsdagVisa&tevdagId=570243&loppId=0&valdManad&valdLoppnr&source=S'

#get data
url %>%
  read_html() %>% 
  html_nodes(".green div:nth-child(1)") %>% 
  html_text()
character(0)