如何在python中的“ if”命令列表后添加“ else”选项

时间:2019-11-03 08:02:45

标签: python if-statement

有一个银行应用程序,您必须登录,并且某些代码具有某些用户。如果没有使用任何密码,我该怎么办?我会收到一条消息,说没有输入有效的密码?

#login id 10
account_name1 = "Mark"
account_balance1 = "150"

#login id 11
account_name2 = "John"
account_balance2 = "190"

#login id 12
account_name3 = "Bob"
account_balance3 = "210"

login_id = input("What is your login id?")

if login_id == "10":
    print("Hello, %s, your balance is $%s." % (account_name1, account_balance1))


if login_id == "11":
    print("Hello, %s, your balance is $%s." % (account_name2, account_balance2))


if login_id == "12":
    print("Hello, %s, your balance is $%s." % (account_name3, account_balance3))

#then here i would have code making it to where if something except 10,11,12 was entered, it would give a message

2 个答案:

答案 0 :(得分:6)

使用id作为关键字将帐户数据放入字典中。如果存在ID,则可以使用相应的帐户数据打印出问候消息,否则打印错误消息:

accounts = {
    "10": {
        "name": "Mark",
        "balance": "150",
    },
    "11": {
        "name": "John",
        "balance": "190",
    },
    "12": {
        "name": "Bob",
        "balance": "210",    
    }
}

login_id = input("What is your login id?")

try:
    print(f"Hello, {accounts[login_id]['name']}, your balance is {accounts[login_id]['balance']}")
except KeyError:
    print("No valid code entered!")

答案 1 :(得分:2)

在这种情况下,您需要做的是一个字符串“ else if”,而不只是“ if”。

这存在多种语言。 “ else if”出现在if之后,其目的是说“如果preifOUS if的求值不为true,则为current,如果确实为……”

在所有这些操作的最后,您放置了一个“ else”,意思是“如果对先前链接的if语句进行评估,如果不是if”。

在Python中,这是通过“ elif”和“ else”关键字完成的。

const {
  GraphQLObjectType,
  GraphQLNonNull,
  GraphQLString,
  GraphQLID
} = require('graphql');

const {mutationWithClientMutationId} = require('graphql-relay');
const {Post} = require('./Post');

const PostModel = require('../model/Post');

const CreatePostMutation = mutationWithClientMutationId({
  name: "CreatePost",
  inputFields: {
    title: {type: new GraphQLNonNull(GraphQLString)},
    content: {type: new GraphQLNonNull(GraphQLString)}
  },
  outputFields: {
    post: {
      type: Post
    }
  },
  mutateAndGetPayload: args => {
    return new Promise((resolve,reject)=>{
      PostModel.createPost({
        title: args.title,
        content: args.content
      })
      .then(post=>resolve({post}))
      .catch(reject);
    });
  }
});

const RemovePostMutation = mutationWithClientMutationId({
  name: "RemovePost",
  inputFields: {
    id: {type: GraphQLID}
  },
  outputFields: {
    post: {
      type: Post
    }
  },
  mutateAndGetPayload: args => {
    return new Promise((resolve,reject)=>{
      PostModel.removePost({
        id: args.id
      })
      .then(post=>resolve({post}))
      .catch(reject);
    });
  }
});

const Mutation = new GraphQLObjectType({
  name: "Mutation",
  description: "kjhkjhkjhkjh",
  fields: {
    createPost: CreatePostMutation,
    removePost: RemovePostMutation
  }
});

module.exports = Mutation;