Search code examples
pythondictionaryinputconditional-statementspassword-checker

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


My intention is to create a user dictionary that contains 'username', 'password' and 'age' and to use conditions to test if an object outside what is in the dictionary will be accepted, just like a login page on a site. But I didn't get my desired result because of an error I made. What do I need to do to make the conditionals produce my desired results? And since dictionaries are mutable, what can I do to ensure the username and password are immutable?


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')

Solution

  • I guess you're asking about the ternary operator

    Syntax :

    [on_true] if [expression] else [on_false] 
    

    Ans :

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

    Edit 1:

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

    You can do like this,but try to avoid writing like this,It reduces code readability