簡體   English   中英

如何使用 python 中的條件來解決下面顯示的代碼?

[英]How can I use conditionals in python to solve the code shown below?

我的目的是創建一個包含“用戶名”、“密碼”和“年齡”的用戶字典,並使用條件來測試字典中的 object 是否會被接受,就像網站上的登錄頁面一樣。 但由於我犯了一個錯誤,我沒有得到我想要的結果。 我需要做什么才能使條件產生我想要的結果? 由於字典是可變的,我能做些什么來確保用戶名和密碼是不可變的?


user1 = {
  'username': 'Casper',
  'age': 26,
  'password': 'schism'
}

user2 = {
  'username': 'Stone',
  'age': 32,
  'password': 'kalamari'
}

user_name = input('What is your username: ')
pass_word = input('What is your password: ')

if user_name and pass_word == user1['username' and 'password']:
  print(' Your details are correct')

else:
  print('Incorrect details')

我猜你在問三元運算符

句法:

[on_true] if [expression] else [on_false] 

答:

print("correct") if pass_word ==user1['password'] and user_name == user1['username'] else print("wrong")

編輯1:

print("correct") if [pass_word,user_name] ==[user1['password'],user1['username']] else print("wrong")

你可以這樣做,但盡量避免這樣寫,它會降低代碼的可讀性

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM