如何使用 python 中的条件来解决下面显示的代码?
How can I use conditionals in python to solve the code shown below?
我的意图是创建一个包含 'username'、'password' 和 'age' 的用户字典,并使用条件来测试是否接受字典之外的对象,就像网站上的登录页面一样。但是由于我犯了一个错误,我没有得到我想要的结果。我需要做什么才能使条件产生我想要的结果?由于字典是可变的,我该怎么做才能确保用户名和密码不可变?
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")
可以这样写,但是尽量避免这样写,会降低代码的可读性
我的意图是创建一个包含 'username'、'password' 和 'age' 的用户字典,并使用条件来测试是否接受字典之外的对象,就像网站上的登录页面一样。但是由于我犯了一个错误,我没有得到我想要的结果。我需要做什么才能使条件产生我想要的结果?由于字典是可变的,我该怎么做才能确保用户名和密码不可变?
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")
可以这样写,但是尽量避免这样写,会降低代码的可读性