2017-11-18 73 views
0

回答如何检查,如果用户的信息是正确的python

所以,我想提出一个密码系统。 它要求用户输入密码,然后检查它是否正确。我遇到以下错误:

%Run HelloPython.py 
    File "/home/pi/Python Coding/HelloPython.py", line 17 
    print('Welcome home,', name,) 
     ^
SyntaxError: expected an indented block 

有些错误。 代码:

print('What is your name?') 

# Stores everything typed up until ENTER 
name = sys.stdin.readline() 

print('Hello', name,'Enter password.') 
password = sys.stdin.readline() 
if password == ("1"): 
print('Welcome home,', name,) 
    else: 
     print("Password:", password,"Is incorect. Please try again.") 
+0

您正在比较一个字符串与数字 –

+0

那么我该怎么做? – Firework

+0

@aaron我如何关闭这个问题? – Firework

回答

2

SyntaxError: expected an indented block

缩进你if - else之类的语句下面。

  1. 要检查“等于”,使用==代替=这是一个赋值。
  2. readline返回一个字符串,所以您应该将其与'1'字符串进行比较。
  3. readline最后包含换行\n,所以请拨打strip()就可以了。
import sys 

print('What is your name?') 

# Stores everything typed up until ENTER 
name = sys.stdin.readline()  
print('Hello', name, 'Enter password.') 

password = sys.stdin.readline().strip() 
if password == '1': 
    print("Welcome home,", name) 
else: 
    print("Password:", password, "Is incorrect. Please try again.") 
1

这是不是你唯一的错误,但它可能是最容易被忽视:

if password = 1: 

这是怎么回事:1获得存储到变量password(由于=是存储操作员)。然后if password正在评估;变量是python中的变量,因此无论您在上面的password中存储了什么,都将评估为True

为了解决这个问题,使用==比较password,也因为password是一个字符串,使其作为一个字符串相比把1引号。

if password == "1": 

您还需要修复缩进,python依赖于空格。

2

所以我重写了你的代码。你忘记缩进你的if语句。 http://www.secnetix.de/olli/Python/block_indentation.hawk

import sys # Import the 'sys' module 

print('What is your name?') 

name = sys.stdin.readline() 

print('Hello ', name, '. Enter password.') 
password = sys.stdin.readline() 

# Use '==' 
if password == 1: 
    print("Welcome home, ", name) 
    # Here you need indentation. 
else: 
    print("Password: ", password," is incorect. Please try again.") 
相关问题