You are reading the article 7 Different Types Of Operators In Python updated in November 2023 on the website Hatcungthantuong.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested December 2023 7 Different Types Of Operators In Python
Introduction to Python OperatorsPython operators are special symbols or reserved keywords that execute operations on one or more operands (values or variables). Operators are essential to programming, allowing developers to manipulate data and control program flow. Python has many operators that perform various operations such as arithmetic, comparison, logic, assignment, identity, membership, and bitwise operations.
Operators can operate on different types of data, such as numbers, strings, lists, tuples, and dictionaries, depending on the operator type and the operands’ data type. For example, the addition operator (+) can add two numbers, concatenate two strings, or merge two lists.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
Key Highlights
Python operators are the symbols that perform specific operations in between the operands. These operators are usually involved in performing the operations such as logical, arithmetic, comparison, etc.
The Python interpreter follows a particular order while executing these operators. The operator precedence in Python determines how operators are evaluated in an expression.
Understanding Python operators is critical for developing Python programs. Using operators, developers can write code that performs complex operations quickly and efficiently, allowing them to create more powerful and effective programs.
Types of Python OperatorsPython Operators are a fundamental programming part that allows developers to manipulate data and control program flow. Python has several types of operators that can be used to perform different operations.
Python’s most common types of operators include
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators.
Understanding the different types of Python operators and how to use them effectively is critical for developing Python programs that can perform complex operations on data.
Python offers a diverse set of operators that serve various purposes.
1. Arithmetic OperatorArithmetic operators are used to perform mathematical operations.
Operator Description Syntax Output
+ Addition a+b Returns the sum of the operands
– Subtraction a-b Returns Difference of the operands
/ Division a/b Returns Quotient of the operands
* Multiplication a*b Returns product of the operands
** Exponentiation a**b returns exponent of a raised to the power b
% Modulus a%b returns the remainder of the division
// Floor division a//b returns a real value and ignores the decimal part
Consider an example program for carrying out the arithmetic operations explained above.
1. Addition (+)Adds two values to obtain the sum.
Example:
Xa = int(input('Enter First number: ')) Xb = int(input('Enter Second number: ')) add = Xa + Xb print('Sum of the numbers is',Xa ,'and' ,Xb ,'is :',add)Output:
2. Subtraction (–)This operator subtracts or provides the difference between two operands.
Example:
Xa = int(input('Enter First number: ')) Xb = int(input('Enter Second number: ')) diff = Xa - Xb print('Difference of the numbers is ',Xa ,'and' ,Xb ,'is :',diff)Output:
3. Multiplication (*)This operator multiplies two operands and provides the results.
Xa = int(input('Enter First number: ')) Xb = int(input('Enter Second number: ')) mul = Xa * Xb print('Product of the numbers is ' ,Xa ,'and' ,Xb ,'is :',mul)Output:
4. Division (/)This operator involves dividing two operands.
Example:
Xa = int(input('Enter First number: ')) Xb = int(input('Enter Second number: ')) div = Xa / Xb print('Division of the numbers is ',Xa ,'and' ,Xb ,'is :',div)Output:
5. Exponentiation (**)The exponentiation operator is nothing but the power, where the representation of the operands is in the form of ab or Xa ** Xb. It performs the multiplication operation.
Example:
Xa = int(input('Enter First number: ')) Xb = int(input('Enter Second number: ')) power = Xa ** Xb print('Exponent of the numbers is ',Xa ,'and' ,Xb ,'is :',power)Output:
6. Floor division (//)This operator rounds off the decimals obtained in the division operation.
Example:
Xa = int(input('Enter First number: ')) Xb = int(input('Enter Second number: ')) floor_div = Xa print('Floor Division of the numbers is ',Xa ,'and' ,Xb ,'is :',floor_div)Output:
7. Modulus (%)The modulus operator obtains the remainder after dividing the operands.
Example:
Xa = int(input('Enter First number: ')) Xb = int(input('Enter Second number: ')) modulus = Xa % Xb print('Modulus of the numbers is ',Xa ,'and' ,Xb ,'is :',modulus)Output:
Overall Example:
Code:
Xa = int(input('Enter First number: ')) Xb = int(input('Enter Second number: ')) add = Xa + Xb diff = Xa - Xb mul = Xa * Xb div = Xa / Xb floor_div = Xa power = Xa ** Xb modulus = Xa % Xb print('Sum of the numbers is',Xa ,'and' ,Xb ,'is :',add) print('Difference of the numbers is ',Xa ,'and' ,Xb ,'is :',diff) print('Product of the numbers is ' ,Xa ,'and' ,Xb ,'is :',mul) print('Division of the numbers is ',Xa ,'and' ,Xb ,'is :',div) print('Floor Division of the numbers is ',Xa ,'and' ,Xb ,'is :',floor_div) print('Exponent of the numbers is ',Xa ,'and' ,Xb ,'is :',power) print('Modulus of the numbers is ',Xa ,'and' ,Xb ,'is :',modulus)Output:
2. Bitwise OperatorsIn Python bitwise operator is usually used to perform operations on the binary representation for the integer values. The bitwise operator works on bits and conducts the operations bit by bit. Refers to the operators working on a bit, i.e., they treat the operand as a string of bits; for example, in bitwise operations, 5 will be considered 0101.
The box below provides the bitwise operators in Python
Operator
Description Syntax
Output
& Binary AND a&b The bit is copied to the result only if present in both operands.
| Binary OR This function copies a bit if present in either of the operands.
^ Binary XOR a^b Copies the bit if it is set in one operand but not both.
~ Binary One’s Complement a~b Unary operation of flipping bits.
<< Binary Left Shift a<<b The left operand value is moved left by the number of bits specified by the right operand.
>> Binary Right Shift The value of the left operand is shifted to the right by the number of bits indicated by the right operand.
The below example shows the bitwise operator as follows. In the below example, we have defined all the bitwise operators as follows.
1. Bitwise AND (&)The bitwise AND operator performs the logical AND operation on the values given and returns the value.
Example:
Xa = int(input('Enter First number: ')) Xb = int(input('Enter Second number: ')) res = Xa & Xb print ("Xa & Xb : ", res)Output:
The bitwise OR operator performs logical OR operation on the given input values.
Example:
Xa = int(input('Enter First number: ')) Xb = int(input('Enter Second number: '))Output:
3. Bitwise xor (^)The bitwise xor operator performs the logical XOR operation on the corresponding bits on the input values.
Example:
Xa = int(input('Enter First number: ')) Xb = int(input('Enter Second number: ')) res = Xa ^ Xb print ("Xa ^ Xb : ", res)Output:
4. Bitwise 1’s complement (~)The bitwise 1’s complement operator returns the result of the bitwise negation of a value where each bit is inverted.
Example:
X = int(input('Enter number: ')) res = ~X print ("X : ", res)Output:
5. Bitwise left-shift (<<)The bitwise left-shift operator shifts the bits for a value by a given number of places to the left-hand side by adding 0s to new positions.
Xa = int(input('Enter First number: ')) Xb = int(input('Enter Second number: ')) res = Xa << Xb print ("Xa << Xb : ", res)Output:
The bitwise right-shift operator involves shifting the bits for an input value by a given number of places right; during this, some bits usually get lost.
Example:
Xa = int(input('Enter First number: ')) Xb = int(input('Enter Second number: '))Output:
Overall Example
Code:
first_operand = 10 second_operand = 15 res = first_operand & second_operand print ("first_operand & second_operand : ", res) res = first_operand ^ second_operand print ("first_operand ^ second_operand : ", res) res = ~first_operand; print ("~first_operand : ", res) res = first_operand << 5; print ("first_operand << 5 : ", res)Output:
3. Membership OperatorsRefers to the operators used in the validation of membership of operand test in a sequence, such as strings, lists, or tuples. There are two types of membership operators in Python.
Operator
SyntaxOutput
in if (a in x): This statement is considered true if it locates a variable in the designated sequence and false if it does not. not in If ( b not in x ): This statement will be true if it fails to locate a variable in the designated sequence and false if it does locate it.The below example shows the membership operator as follows.
Code:
first_operand = 29 second_operand = 23 list = [11, 15, 19, 23, 27] if (first_operand not in list): print("first_operand is NOT present in given list") else: print("first_operand is present in given list") if (second_operand in list): print("second_operand is present in given list") else: print("second_operand is NOT present in given list")Output:
4. Identity OperatorsIn Python, the identity operator is used to compare the memory locations of two objects and to return the Boolean value that depends on whether they refer to the same object. There are two types of identity operators in Python.
Operator Syntax Output
is x is y returns True if the type of the value in y points to the same type in the x.
is not x is not y returns True if the type of the value in y points to a different type than the value in the x
The below example shows the identity operator as follows.
Code:
first_operand = 10 second_operand = 20 third_operand = first_operand print(first_operand is not second_operand) print(first_operand is third_operand)Output:
5. Comparison OperatorsA comparison operator is used to compare the values of two operands, and after comparing the value, it will return a true or false Boolean value. It is also known as Relational operators.
Operator Syntax Output
== (a == b) If the values of a and b are equal, then the condition becomes true.
!= (a != b) If the values of a and b are not equal, then the condition becomes true.
If the values of a and b are not equal, then the condition becomes true.
> If the value of a is greater than that of b, then the condition becomes true.
< (a < b) If the value of a is less than that of b, then the condition becomes true.
>= If the value of a is greater than or equal to that of b, then the condition becomes true.
<= (a <= b) If the value of b is less than or equal to that of b, then the condition becomes true.
The below example shows the comparison operator as follows.
Code:
x = 30 y = 35Output:
2. Less than (<)Code:
x = 30 y = 35 print('x < y is', x<y)Output:
3. Equal to (==)Code:
Xa = int(input('Enter First number: ')) Xb = int(input('Enter Second number: ')) print("Xa == Xb : ", Xa == Xb)Output:
4. Not equal to (!=)Code:
x = 30 y = 35 print('x != y is', x!=y)Output:
Code:
x = 30 y = 35Output:
6. Less than or equal to (<=):Code:
x = 30 y = 35 print('x <= y is', x<=y)Output:
Overall Code
Code:
first_operand = 15 second_operand = 25 print("first_operand == second_operand : ", first_operand == second_operand) print("first_operand != second_operand : ", first_operand != second_operand) print("first_operand < second_operand : ", first_operand < second_operand) print("first_operand <= second_operand : ", first_operand <= second_operand)Output:
6. Assignment OperatorsWhen working with Python, you can use assignment operators to assign variable values. Following are the types of assignment operators in Python.
Operator Description Syntax Output
= Equal to c = a + b assigns a value of a + b into c
+= Add AND c += a is equivalent to c = c + a
-= Subtract AND c -= a is equivalent to c = c – a
*= Multiply AND c *= a is equivalent to c = c * a
/= Divide AND c /= a is equivalent to c = c / ac /= a is equivalent to c = c / a
%= Modulus AND c %= a is equivalent to c = c % a
**= Exponent AND c **= a is equivalent to c = c ** a
//= Floor Division c is equivalent to c = c
The below example shows the assignment operator as follows.
Code:
first_operand = 10 first_operand += 5 print ("first_operand += 5 : ", first_operand) first_operand -= 5 print ("first_operand -= 5 : ", first_operand) first_operand *= 5 print ("first_operand *= 5 : ", first_operand) first_operand /= 5 print ("first_operand /= 5 : ",first_operand) first_operand %= 3 print ("first_operand %= 3 : ", first_operand) first_operand **= 2 print ("first_operand **= 2 : ", first_operand) first_operand print ("first_operandOutput:
7. Logical OperatorsThese operators are used to perform similar operations as logical gates; there are 3 types of logical operators in Python.
Operator Description Syntax Output
and Logical AND a and b a condition is true if both a and b are true
or Logical OR a or b a condition is true if either a and b are true
not Logical NOT not a Complement the operand
The below example shows the logical operator as follows.
Code:
first_operand = True second_operand = False print(first_operand and second_operand) print(first_operand or second_operand) print(not first_operand)Output:
Python Operators PrecedenceIn Python, operators are evaluated in a specific order of precedence when used in an expression. This order determines their sequence of evaluation. The order of precedence ensures that expressions are evaluated correctly, following the standard mathematical rules. In cases where multiple operators have the same precedence, the order of evaluation follows the associativity of the operator. For example, some operators, such as addition and multiplication, are left-associative, meaning they are evaluated from left to right. Others, such as exponentiation, are right-associative, meaning they are evaluated from right to left. The below table shows operator precedence as follows.
Operator Description
** Exponentiation
‘~ + -’ Bitwise NOT, Unary Plus and Minus
<‘* / % Multiplication, division, modulus, and floor division
‘+ -’ Addition and subtraction
Bitwise shift right and left
& Bitwise AND
^ Bitwise XOR
and Logical and
not Logical not
or Logical or
Comparison Operators
= %= /= Assignment Operators
Is, is not Identity Operators
in not in Membership Operators
not or and Logical Operators
Conclusion Frequently Asked Questions(FAQs)Q2. What is operator precedence? Which operator has the highest precedence?
Ans: Operator precedence is an order which is predefined and followed by the interpreter while executing multiple operations at the same time. Among all the operators (), parentheses have the highest precedence.
Q3. Is the boolean value true if null?
Ans: The null value represents that the specified variable doesn’t have anything in it. Hence it is neither true nor false.
Recommended ArticlesWe hope that this EDUCBA information on “Python Operators” was beneficial to you. You can view EDUCBA’s recommended articles for more information.
You're reading 7 Different Types Of Operators In Python
The Different Types Of Company Directors
Company directors (or board members) are typically nominated by a nominating committee, but they can also be nominated by a company’s shareholders.
What’s the difference between executive and non-executive directors?Company directors – board members – fall into two major categories: executive directors and non-executive directors.
The big difference is that non-executive directors do not participate in the day-to-day operations of the organisation.
“Non-executives (or NEDs) have been described as ‘critical friends’ to the CEO and the executive directors,” says David W Duffy, CEO of the Corporate Governance Institute. “They are recruited by a board of directors to offer expertise from an ‘outsider’s’ perspective.”
All the members of a board are typically nominated by a nominating committee, but they can also be nominated by shareholders.
Aside from executive and non-executive directors, there are other categories into which company directors may fall. A de facto director, shadow director, nominee director, and alternate director are all examples of this.
A de facto director has the same responsibilities toward the company as a regular director.
Stay compliant, stay competitiveBuild a better future with the Diploma in Corporate Governance.
Download brochure
Book a call
Stay compliant, stay competitive
Build a better future with the Diploma in Corporate Governance.
Download brochure
Book a call
What are de facto directors?
Although not officially appointed to the board, de facto directors assume the role of directors. For example, they sign contracts, make decisions, and appear to third parties as a director on behalf of the company.
A de facto director has the same responsibilities toward the company as a regular director.
Companies should be careful and diligent when appointing shadow directors.
Shadow directors are determined by their influence over the company’s operations.
Companies should be diligent when appointing shadow directors and ensure that all legal requirements are met.
A breach of directors’ responsibilities can result in harsh penalties, and the lack of a formal appointment does not necessarily protect a shadow director.
The appointment of a nominee director can occur for many reasons.
What is a nominee director?
Nominee directors represent the interests of stakeholders or stakeholder groups (nominators) on a company’s board. Nominators appoint them to safeguard their interests.
However, regardless of its appointment by a specific stakeholder, a nominee director is not relieved of his general duties as a director of the company.
The appointment of a nominee director can occur for many reasons, including:
Nominee directors may be appointed under the Articles of Association (AoA). Often, partners in a joint venture can appoint their nominees to the board of directors.
If a financial institution gives a substantial loan to a company, its nominee directors are generally appointed to the board of directors to ensure the lenders’ interest is protected.
When a party invests heavily (in the form of shares or otherwise) in the company, the investor is entitled to nominate a director to the board of the investee.
A stakeholder may be granted such a right through a contractual arrangement between a company and themselves.
In cases where the statute specifically provides for the appointment of nominee directors to the board.
In the absence of the principal director, the alternate director has the same power as the principal director.
What is an alternate director?
When another director cannot attend a board meeting, an alternate director may be appointed in their place.
In the absence of the principal director, the alternate director has the same power as the principal director.
These types of company directors should receive all meeting and committee notes that the principal director would receive.
They should be able to fulfil all their duties while the principal director is away.
In the same way as any regular director, the alternate director is personally responsible for their actions.
If you have an interest in becoming a company director, you can download this brochure to learn more about the Diploma in Corporate Governance.
Types Of Funds In India
Accounts play a key role in a country’s economic management. The Consolidated Fund of India (Article 266), the Contingency Fund of India (Article 267), and the Public Accounts of India (Article 266(2)) are the three different forms of central government finances that are mentioned in the Indian Constitution.
What is Government Fund?Government financing is a formal donation made by a federal, state, or local government body in honor of a noble effort.
In essence, it serves as a transfer payment. Grants do not include technical help or other types of financial aid like loans, loan guarantees, discounted interest rates, direct appropriations, or revenue sharing.
In some cases, such as when a discovery results in a patent that brings in money, there may also be revenue-sharing agreements with the government.
Government funding refers to any circumstance in which a business or initiative receives all or some of its financial support from a government.
The government does more than just give these organizations money, though.
A company that has been awarded a government contract for work usually subcontracts out a portion of the work to other businesses.
For the purposes of the specific subcontract, these businesses are regarded as beneficiaries of government funding and, as such, are governed by all laws and regulations that may be in force.
Governments can also raise money through loans, which can be used to directly or indirectly subsidize borrowing from other sources.
Normal loan terms call for interest on top of full payback. For higher education, government loans, particularly those from the federal government, are frequently utilized.
Frequently, until the beneficiary completes their education, interest charges and repayment requirements are put off. Small business finance is another traditional category of government credit and is normally managed by the Small Business Administration.
The Indian government’s finances are separated into three categories, which are listed below −
Consolidated FundThe most crucial account in the government is the Consolidated Fund of India. Except for extraordinary items, the government’s receipts and expenditures are included in the consolidated fund.
As stated in Article 266 (1) of the Indian Constitution, this fund was established. The Consolidated Fund of India is the repository for all of the government’s direct and indirect tax collections, as well as borrowing costs and repayments of government loans.
Except for unusual expenses, which are covered by the contingency fund or the public account, all government spending comes from this fund. A crucial restriction is that the parliament must approve all withdrawals from this fund.
It is divided into the following five sections −
Charges for expenses made against consolidated funds
Income account (receipts)
Revenue account (disbursements)
Capital statement (receipts)
Capital statement (disbursements)
Charged Expenditures on Consolidated FundNon-votable means that no vote is required to approve expenditures charged to the Consolidated Fund of India. These costs should be covered by the range of pay and allowances for −
The Chief Executive
A speaker
The Lok Sabha’s deputy speaker
Judges of the Supreme Court’s salaries and benefits
Judges of the Supreme Court and tribunals’ pensions
Contingency FundThe Indian Constitution’s Article 267(1) makes provision for this fund.
It has a 500 crore rupee corpus. It has the characteristics of an impress (money maintained for a specific purpose).
On behalf of the Indian President, the Secretary of the Finance Ministry is in charge of this fund.
Unexpected or unforeseen expenses are covered by this fund.Article 267 permits each state to establish its own contingency fund.
Public Account of IndiaArticle 266(2) of the Constitution establishes the following: The Public Account of India should be the source of all additional public funds received by or on behalf of the Indian government (except for those that are attributed to the Consolidated Fund of India). The following ingredients go towards making this −
Bank savings accounts are available for several ministries and departments.
The national defense fund is comparable to a modest national savings pool.
National Savings and Investments Corp. (money obtained from disinvestment)
The National Catastrophe and Contingency Fund is known as NCCF (for disaster management).
Insurance for communications, provident funds, and other things.
ConclusionThe Indian Parliament must approve both the expenditure and the withdrawal of the corresponding amount from the Consolidated Fund in order to maintain the Contingency Fund’s corpus. Similar to this, every government creates a contingency fund in accordance with Article 267(2) of the Constitution. Article 266 of the Indian Constitution establishes the Public Accounts (2).
Frequently Asked QuestionsQ1. Who controls government money in India?
Ans. The highest governing body is the Ministry of Finance.
Q2. Who is the owner of the India Contingency Fund?
Ans. The Fund is held on behalf of the Indian President by the Secretary to the Government of India, Ministry of Finance, Department of Economic Affairs.
Q3. Who gets salary from Consolidated Fund of India?
Ans. The President’s salary and benefits, the Speaker and Deputy Speaker of the Lok Sabha, the Chairman and Vice Chairman of the Rajya Sabha, Judges of the Supreme Court and High Court get salaries and allowances, while CAG and Lok Pal justices receive salaries and allowances as well.
Q4. Who prepares the budget in India?
Ans. The budget is created by the Ministry of Finance.
Different Examples Of Filter In Excel Vba
VBA Filter in Excel
It is very easy to apply the filter through just by pressing Alt + D + F + F simultaneously or Shift + Ctrl + L together. We can even go to the Data menu tab and select the Filter option there. But what if I say there is a much cooler way to use Filter using VBA Codes. Although applying the filter in any data is very easy manually but if we have a huge set of data where we need to apply the filter. Doing manually will take huge time to execute but doing this using Filter in Excel VBA code, we can make it much easier.
Watch our Demo Courses and Videos
Valuation, Hadoop, Excel, Mobile Apps, Web Development & many more.
Syntax of VBA Filter:
Where, Range = This is the range of cells where we need to apply Auto Filter. This can be a single cell or range of cells in a row.
Field: This is a sequence number of the column number from there our range is getting started.
Criteria: Here we can quote our criteria which we want to filter from the selected field.
Operator: This is optional if we have only one criteria. But for Criteria2 we use xlAnd, xlOr, xlBottom10Items, xlTop10Items, xlTop10Percent, xlBottom10Percent such keys to filter the data.
How to Apply Filter using VBA (Examples)Below are the different examples of Filter in Excel VBA:
You can download this VBA Filter Excel Template here – VBA Filter Excel Template
Example #1We have some sales data in Sheet1 as shown below. As we can see, we have the data in multiple columns which is perfect to show how VBA Filter works. For this, follow the below steps:
Step 2: Now write the subprocedure for VBA Filter.
Code:
Sub VBA_Filter()
Step 3: Select the worksheet which has the data. Here our data is in Sheet1.
Code:
Sub VBA_Filter()
Worksheets(“Sheet1”).
End Sub
Step 4: And after select the column as Range which we want to filer followed by AutoFilter function.
Code:
Sub VBA_Filter()
Worksheets(“Sheet1”).Range(“G1”).AutoFilter
End Sub
Step 5: Now run the code. We will see the complete row got the filter dropdown. Even if we select a cell, auto filter will be applied to the complete row.
Example #2If we use the proper syntax of VBA Filter, we can filter the data as we do manually. Let’s filter the data with the Owner’s name as Ben and see what we get. For this, follow the below steps:
Step 1: Defining the subprocedure for VBA Filter.
Code:
Sub VBA_Filter2()
End Sub
Step 2: Select the worksheet which has the data. Here again, the sheet is Sheet1. And then select the column name as Range which we want to filter. Here the Owner name column is at G1 position.
Code:
Sub VBA_Filter2()
Worksheets(“Sheet1”).Range(“G1”).
End Sub
Step 3: Now we will use the AutoFilter command to apply the filter. Then select the Field number which is at 7th position and Criteria as Ben.
Code:
Sub VBA_Filter2()
Worksheets(“Sheet1”).Range(“G1″).AutoFilter Field:=7, Criteria1:=”Ben”
End Sub
Step 4: Compile the code by hitting F5 or the Run button and run it. We will see, the filer is now applied to Row1 at cell G1. And as we can see, the dot in the G1 cell filter shows the data is filtered.
Code:
Sub VBA_Filter2()
Worksheets(“Sheet1”).Range(“A1:J1″).AutoFilter Field:=7, Criteria1:=”Ben”
End Sub
Step 7: What if we choose an Operator here to apply multiple filters in the same selected field? For this, in the same line of code, add Operator xlOR. This will help us to apply more than one criteria.
Code:
Sub VBA_Filter2()
Worksheets(“Sheet1”).Range(“A1:J1″).AutoFilter Field:=7, Criteria1:=”Ben”, Operator:=xlOr,
End Sub
Step 8: Now, at last, select another criterion which is Criteria2. Let’s say that criteria be John.
Code:
Sub VBA_Filter2()
Worksheets(“Sheet1”).Range(“A1:J1″).AutoFilter Field:=7, Criteria1:=”Ben”, Operator:=xlOr, Criteria2:=”John”
End Sub
Step 9: Now run the code again. We will see, in the drop-down option at cell G1, both the owner’s name are filtered. One is BEN and the other is JOHN.
Example #3There is another way to filter the data with more than 1 criteria in different columns. We will use With-End With Loop to execute this. For this, follow the below steps:
Step 1: Write the subprocedure.
Code:
Sub VBA_Filter3()
End Sub
Step 2: Select the Range where we need to apply filter. Here our range is from cell A1:J1.
Sub VBA_Filter3()
With Range(“A1:J1”)
End Sub
Step 3: In the next line of code, use AutoFilter function and select the Fields and Criteria as required. Here Field will be 7 and Criteria will be BEN.
Code:
Sub VBA_Filter3()
.AutoFilter Field:=7, Criteria1:=”Ben”
End Sub
Step 4: In the second line of code, we will select another cell of headers to be filtered. Let’s filter the Quantity column with the values greater than 50 for the Owner’s name BEN.
Code:
Sub VBA_Filter3()
End Sub
Step 5: End the loop with End With.
Code:
Sub VBA_Filter3()
End With
End Sub
Step 6: Run the Code by hitting F5 or the Run button. we will see field number 7 and 9 both got the filtered.
Step 7: And if we check in Column I of header Quantity, we will see, the quantities filtered are greater than 50.
Pros of VBA Filter
It is very easy to apply.
We can filter as many headers as we want.
File with huge data set can easily be filtered using VBA Filter.
VBA Autofilter can speed things up and save time.
Things to Remember
We can select one cell or a line for Range. But the filter will be applied to the complete range of header which has data.
Use with operation, if you want to filter the data with more than 1 column.
The field section in the syntax of VBA Filter can only contain the number which is the sequence of the required column.
Always mention the names into inverted quotes.
Save the file in Macro Enabled Excel format to preserve the applied code.
Recommended ArticlesThis is a guide to VBA Filter. Here we discuss some useful examples of VBA Filter code in Excel along with a downloadable excel template. You can also go through our other suggested articles –
Different Examples Of Contents In Excel Vba
Excel VBA Constants
VBA Constant, which means a value that doesn’t change by any mean. This we have seen a lot of time in mathematics. But the Constant can also be used in VBA coding as well with the same concept when we used in solving regular mathematical problems. In VBA Constant, we fix the value of any variable as per our need and we can use this predefined Constant later whenever we feel to use it.
If we define any value under VBA Constant, it will hold and store that value somewhere which will not be changed. If a person tries to change that value then it will show up the error.
Watch our Demo Courses and Videos
Valuation, Hadoop, Excel, Mobile Apps, Web Development & many more.
Examples of Constants in Excel VBABelow are the different examples of contents in Excel VBA.
You can download this VBA Constants Excel Template here – VBA Constants Excel Template
Excel VBA Constants – Example #1VBA Constants is like defining a variable with DIM. First, we will see an example where we will execute a simple mathematical code as our regular process.
Follow the below steps to use Excel VBA Constants:
Step 1: Go to VBA Insert menu and open a Module first as shown below.
Code:
Sub
VBA_Constants()End Sub
Step 3: Define a variable A as Integer first. This will allow us to consider all whole numbers in it.
Code:
Sub
VBA_Constants()Dim
AAs Integer
End Sub
Step 4: Now assign any value in variable A. Let’s say it as 123. By this, we will store this value under variable A.
Code:
Sub
VBA_Constants()Dim
AAs Integer
A = 123End Sub
Step 5: Now again define a new variable C as Integer.
Code:
Sub
VBA_Constants()Dim
AAs Integer
A = 123Dim
CAs Integer
End Sub
Step 6: Now in a simple mathematical multiplication problem, let’s multiply variable A with 4 and get the output in variable C as shown below.
Code:
Sub
VBA_Constants()Dim
AAs Integer
A = 123Dim
CAs Integer
C = A * 4End Sub
Step 7: Now to print the output, we will use MsgBox as shown below.
Code:
Sub
VBA_Constants()Dim
AAs Integer
A = 123Dim
CAs Integer
C = A * 4 MsgBox CEnd Sub
Now we may end up in a situation where we have to change the value stored in variable A multiple times by keeping the constant value of multiplier as 4. So, if we create a constant where if we fix the value of multiplier which is 4 as we have for other variables then it will reduce our frequent activities.
Step 9: For this, use Const as in Constant with B and give it a variable Double.
Code:
Sub
VBA_Constants()Dim
AAs Integer
A = 123Const
BAs Double
Dim
CAs Integer
C = A * 4 MsgBox CEnd Sub
Step 10: And assign the multiplier 4 to variable B as constant.
Code:
Sub
VBA_Constants()Dim
AAs Integer
A = 123Const
BAs Double
= 4Dim
CAs Integer
C = A * 4 MsgBox CEnd Sub
Step 11: Now change the same variable mathematically, multiply formula with 4 as shown below.
Code:
Sub
VBA_Constants()Dim
AAs Integer
A = 123Const
BAs Double
= 4Dim
CAs Integer
C = A * B MsgBox CEnd Sub
Step 12: Now again compile the code and run it.
We have got the same result in variable C as 492 which is the multiplication output of 123 and 4.
Step 13: For more test, let’s change the value stored in variable A from 123 to let’s say 321 as shown below.
Code:
Sub
VBA_Constants()Dim
AAs Integer
A = 321Const
BAs Double
= 4Dim
CAs Integer
C = A * B MsgBox CEnd Sub
Step 14: Now if we run the code we should be getting the multiplication of 321 and 4 in a message box.
We will see, the message box with the output as 1284, which is the actual multiplication of 321 and 4. This means that value stored in Const variable B is still constant as both the time it has multiplied the variable A with 4.
Excel VBA Constants – Example #2In another example of VBA Constant how fixing all the variables as Constant works. Follow the below steps to use Excel VBA Constants.
Code:
Sub
VBA_Constants2()End Sub
Step 2: Now define a Constant A as String and give it any text as per your choice. Let’s say that text in Constant as shown below.
Code:
Sub
VBA_Constants2()Const
AAs String
= "Constant"End Sub
Step 3: Now in the second line, again define another Constant B as Integer and give it any number as shown below. Let’s say that number is 10.
Code:
Sub
VBA_Constants2()Const
AAs String
= "Constant"Const
BAs Integer
= 10End Sub
Step 4: In a simple way, let’s print a text as “The real constant is 10” with the help of MsgBox as shown below.
Code:
Sub
VBA_Constants2()Const
AAs String
= "Constant"Const
BAs Integer
= 10 MsgBox "The real " & A & " is " & BEnd Sub
The text which we have written above can be anything.
Step 5: Now compile the code and run it, if found no error. We will get the message box as “The real Constant is 10” which we set above.
As our values are constant for A and B, so we can use these anywhere and anytime. And each time when we would call them values of Constant A and B, we will get the same values stored in this subcategory.
Pros of Excel VBA Constants
This saves a huge amount of time for fixing one or more variables as Constant.
The number of lines of code gets reduced.
We just need to enter the values in defined Constants once, and then whenever we will call that constant, the value stored in it will come up.
Cons of Excel VBA Constants
It is not always used as sometimes we need to come back multiple times to change the values stored in Constants if we are using these defined constants in different Subcategories or Class.
Things to Remember
Results obtained from Constants and Variables are the same. The difference is once Constants are defined, it can be used anywhere multiple times. But Variables are defined for each subcategory.
If there is a change in values which we call and stored constants then we may end up getting an error. So, it is better to check the values first which are fixed as constant.
Saving the file as a macro-enabled excel format helps us to retain the code for the future.
It is always recommended to use Constant when we are working on creating Class objects. Constant is shorter as compared to Variables, so it is a huge set of codes it will take lesser space.
Recommended ArticlesThis is a guide to VBA Constants. Here we discuss the different examples of Constants in Excel VBA along with some practical examples and downloadable excel template. You can also go through our other suggested articles –
Working Of Json.dumps() Function In Python
Introduction to Python json.dumps
JSON (JavaScript Object Notation) is a text-based file format used for storing and transferring data. It is a widely supported format in various programming languages. In Python, JSON is supported through the built-in json package. To utilize JSON in Python, the json package needs to be imported. This package provides functionalities to convert Python objects into JSON string representations. The json.dumps() function is specifically used to convert a Python dictionary object into a JSON string.
Start Your Free Software Development Course
The syntax is as follows:
json.dumps(python_dictionary_object)where python_dictionary_object is the python object that is to be converted to json string representation.
Working of json.dumps() Function in Python
The executable file made of text in a programming language that can be used to store the date and transfer the data is called JavaScript Object Notation, also called JSON.
This JSON is supported using a built-in package called json, and to be able to use this feature in Python, the json package must be imported.
Whenever an object in Python is converted to json string, we use a python function called json. dumps() function.
A JSON string representation of the Python dictionary object is returned by using json.dumps() function.
Examples of Python json.dumpsFollowing are the examples as given below:
Example #1Python program to convert the given Python dictionary object into json string representation:
Code:
#a package called json is imported to make use of json.dumps() function import json #creating a dictionary object in python which is to be converted into json string representation pythondictionary ={1:'Learning', 2:'is', 3:'fun'} # json.dumps() function is used to convert the given python dictionary object into json string representation jsonstring = json.dumps(pythondictionary) #displaying the json string representation of the given python dictionary object print 'n' print('The json string representation of the given python dictionary object is:') print 'n' print(jsonstring)Output:
In the above program, a package called json is imported to make use of json.dumps() function to convert the given python dictionary object into json string representation. Then a dictionary object is created in python to convert it into json string representation. Then this function is used to convert the created python dictionary object onto json string representation. Then the converted json string representation is displayed as the output on the screen.
Example #2Python program to convert the given Python dictionary object into json string representation:
#a package called json is imported to make use of json.dumps() function import json #creating a dictionary object in python which is to be converted into json string representation pythondictionary = {1:'India', 2:'is', 3:'my', 4:'nation'} # json.dumps() function is used to convert the given python dictionary object into json string representation jsonstring = json.dumps(pythondictionary) #displaying the json string representation of the given python dictionary object print 'n' print('The json string representation of the given python dictionary object is:') print 'n' print(jsonstring)Output:
The mentioned program imports the json package to utilize the json.dumps() function is used to convert a given Python dictionary object into a JSON string representation. After importing the json package, a dictionary object is created in Python. This dictionary object is created to convert it into a JSON string representation.
Example #3Python program to convert the given Python dictionary object into json string representation:
Code:
#a package called json is imported to make use of json.dumps() function import json #creating a dictionary object in python which is to be converted into json string representation pythondictionary = {1:'Python', 2:'is', 3:'interesting'} # json.dumps() function is used to convert the given python dictionary object into json string representation jsonstring = json.dumps(pythondictionary) #displaying the json string representation of the given python dictionary object print 'n' print('The json string representation of the given python dictionary object is:') print 'n' print(jsonstring)Output:
The above program imports the json package to utilize the json.dumps() function converts a given Python dictionary object into a JSON string representation. Following the import, a dictionary object is created. This dictionary object is then converted into a JSON string representation using the json.dumps() function.
Example #4Python program to convert the given Python dictionary object into json string representation:
Code:
#a package called json is imported to make use of json.dumps() function import json #creating a dictionary object in python which is to be converted into json string representation pythondictionary = {1:'EDUCBA', 2:'for', 3:'learning'} # json.dumps() function is used to convert the given python dictionary object into json string representation jsonstring = json.dumps(pythondictionary) #displaying the json string representation of the given python dictionary object print 'n' print('The json string representation of the given python dictionary object is:') print 'n' print(jsonstring)Output:
The json package is imported to utilize the json in the mentioned program.dumps() function for converting a given Python dictionary object into a JSON string representation. Next, a dictionary object is created in Python to be converted into a JSON string representation. The json.dumps() function then converts the created Python dictionary object into a JSON string.
Recommended ArticlesWe hope that this EDUCBA information on “Python json.dumps” was beneficial to you. You can view EDUCBA’s recommended articles for more information.
Update the detailed information about 7 Different Types Of Operators In Python on the Hatcungthantuong.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!