2017-08-24 73 views
0

我必須進行登錄,但由於某種原因,它不起作用。請給我一些幫助嗎?使用Python實現if-else條件

我有這段代碼,但我不能得到它的工作。

username=input("please enter your username") 
password=input("please enter your password") 
if username=="student1": 
password=="password123" 
print("accsess granted") 

else username!="student1": 
password !="password123" 
print "inncorect login" 
+2

你能更詳細一點的「它不工作」?究竟是什麼問題? – Mureinik

+1

閱讀[邏輯運算符](https://www.programiz.com/python-programming/operators#logical_operators)。另外,你的身份是錯誤的。縮進在Python中很重要 – litelite

+0

只需添加。不要按原樣存儲密碼。加密它們(使用sha1 +鹽等)。 – akp

回答

4
  1. 你縮進關閉

  2. if s爲畸形

  3. 你的矛盾print聲明讓人懷疑你使用的是什麼版本(版本問題!括號問題!)


幸運的是,修復非常簡單。您將需要一個if-else聲明。 else不需要條件。

username = input("please enter your username") 
password = input("please enter your password") 

if username == "student1" and password == "password123": 
    print("access granted") 

else: 
    print("incorrect login") 

如果您使用的是python2,請使用raw_input代替。

+0

和,訪問拼寫是inncorect :) – Vasif

+0

@cᴏʟᴅsᴘᴇᴇᴅ。而「inncorect」是不正確的。 – ekhumoro

+0

謝謝,都.. ..! –

1
if username=="student1" and password=="password123": 
    print("accsess granted") 
0

你已經得到了if/else錯誤的語法。正確的語法是:

if username == "student1" and password == "password123": 
    print("access granted") 
else: 
    print("incorrect login") 
0

現在你的腳本只檢查用戶名是否「student1」和執行上的密碼無用的檢查。試試這個版本(假設的Python 2.7):

username = raw_input("please enter your username") 
password = raw_input("please enter your password") 
if username == "student1" and password == "password123": 
    print "access granted" 
else: 
    print "incorrect login" 

更妙的是,你應該哈希密碼,因爲現在它足以打開Python文件,並環顧四周,找到正確的密碼。舉個例子:

from hashlib import md5 
username = raw_input("please enter your username") 
password = raw_input("please enter your password") 
password2 = md5() 
password2.update(password) 
if username == "student1" and password2.hexdigest() == "482c811da5d5b4bc6d497ffa98491e38": 
    print "access granted" 
else: 
    print "incorrect login" 

我生成這個代碼的哈希:

from hashlib import md5 
m = md5() 
m.update('password123') 
print m.hexdigest() 
+0

我很感激你用密碼去了更多的一英里,但是讓OP首先了解在移動到密碼之前是否 - 否則。 –