Python operator https://www.skillvertex.com/blog Thu, 11 Apr 2024 12:01:34 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.1 https://www.skillvertex.com/blog/wp-content/uploads/2024/01/favicon.png Python operator https://www.skillvertex.com/blog 32 32 Precedence and Associativity of Operators in Python https://www.skillvertex.com/blog/precedence-and-associativity-of-operators-in-python/ https://www.skillvertex.com/blog/precedence-and-associativity-of-operators-in-python/#respond Thu, 11 Apr 2024 12:01:34 +0000 https://www.skillvertex.com/blog/?p=7005 Read more]]>

Table of Contents

The arithmetic operator will take precedence over the logical operator. Initially, python will check the arithmetic operators. Relational operators will be checked next. At the end, logical operators will be evaluated.

Therefore, if multiple operators are present in an expression, then the higher precedence will be checked first. However, the associativity will be given more importance while considering the order of evaluation in the operator. Let us look into this article to learn more about the precedence and Associativity of operators in Python.

What is Operator Precedence in Python?

In Python, an expression is of variables, operators, and values. The Python interpreter will come across an expression that has various operations and that will be evaluated with the ordered hierarchy. This process is defined as operator precedence.

The table below has provided all the operators from the highest precedence to the lowest precedence.

PrecedenceOperatorsDescriptionAssociativity
1()ParenthesesLeft to right
2x[index], x[index:index]Subscription, slicingLeft to right
3await xAwait expressionN/A
4**ExponentiationRight to left
5+x, -x, ~xPositive, negative, bitwise NOTRight to left
6*, @, /, //, %Multiplication, matrix, division, floor division, remainderLeft to right
7+Addition and subtractionLeft to right
8<<, >>ShiftsLeft to right
9&Bitwise ANDLeft to right
10^Bitwise XORLeft to right
11|Bitwise ORLeft to right
12in, not in, is, is not, <, <=, >, >=, !=, ==Comparisons, membership tests, identity testsLeft to Right
13not xBoolean NOTRight to left
14andBoolean ANDLeft to right
15orBoolean ORLeft to right
16if-elseConditional expressionRight to left
17lambdaLambda expressionN/A
18:=Assignment expression (walrus operator)Right to left

Precedence of Python Operators

It is commonly used in the expression that has more than one operator with different precedence for identifying which operator will be required to do first.

Example

10 + 20 * 30

output

10 + 20 * 30 is calculated as 10 + (20 * 30)
and not as (10 + 20) * 30

Python code for the above example

# Precedence of ‘+’ & ‘*’

expr =10+20*30

print(expr)

Output

610

Precedence of logical operators in Python

The if block will be run in the code provided below even though the age is 0. The precedence of logicaland” will be greater than the logical “or“.

# Precedence of ‘or’ & ‘and’

name =”Alex”

age =0

ifname ==”Alex”orname ==”John”andage >=2:

    print(“Hello! Welcome.”)

else:

    print(“Good Bye!!”)

Output

Hello! Welcome.

Another way to execute the ‘else‘ block is the use of parenthesis (). It will be considered as their precedence and the highest among all the operators.

# Precedence of 'or' & 'and'
name = "John"
age = 0
 
if (name == " John" or name == " Albert") and age >= 2:
    print("Hello! Welcome.")
else:
    print("Good Bye!!")

Output

Good Bye!!

Associativity of the Python Operators

The expression has two or more operators with the same precedence, and then the operator associativity will determine it as either to be left or reft or from right to left.

Example

‘*’ and ‘ /’ consist of the same precedence and the associativity will be from Left to Right in the code below.

# Left-associative operators
a = 10 + 5 - 2  # Addition and subtraction are left-associative
print(a)  # Output: 13

b = 2 * 3 / 2  # Multiplication and division are left-associative
print(b)  # Output: 3.0

# Right-associative operators (only one example in Python, exponentiation)
c = 2 ** 3 ** 2  # Exponentiation is right-associative
print(c) 

Output

13
3.0
512

Operators’ Precedence and Associativity in Python

In Python, Operators’ precedence and Associativity are considered the two important characteristics of operators that will be used to check the order of subexpression in the absence of brackets.

Example

100 + 200 / 10 - 3 * 10

100 + 200 / 10 - 3 * 10 is calculated as 100 + (200 / 10) - (3 * 10)
and not as (100 + 200) / (10 - 3) * 10

Python code for the example above

expression = 100 + 200 / 10 - 3 * 10
print(expression)

Output

90.0

What are non-associative operators?

In Python, most of the operators have associativity and this indicates that it can be used to evaluate from left to right or right to left and have the same precedence.

Therefore, few operators are considered as non- associative and this means that they cannot be chained together.

a = 5
b = 10
c = 15
 
a = b = (a < b) += (b < c)

Output

a = b= (a < b) += (b < c)
                   ^^
SyntaxError: invalid syntax

Conclusion

To conclude, this article has listed about the operator precedence and associativity in Python. Moreover, several examples are also provided for a better understanding of the operator’s precedence. This can allow the students to improve their knowledge and skills regarding the topic.

Precedence and Associativity of Operators in Python- FAQs

Q1. Is Python right associative?

Ans. The associativity will be either from left to right or right to left.

Q2. What is precedence in Python?

Ans. It denotes the order of precedence. Python has divided the operators into several categories such as Arithmetic operators and assignment operators.

Q3. What is the highest precedence?

Ans. Parentheses will have the highest precedence. Higher precedence operators will be performed before the lower precedence operations.

Hridhya Manoj

Hello, I’m Hridhya Manoj. I’m passionate about technology and its ever-evolving landscape. With a deep love for writing and a curious mind, I enjoy translating complex concepts into understandable, engaging content. Let’s explore the world of tech together

]]>
https://www.skillvertex.com/blog/precedence-and-associativity-of-operators-in-python/feed/ 0
Python Bitwise Operator https://www.skillvertex.com/blog/python-bitwise-operator/ https://www.skillvertex.com/blog/python-bitwise-operator/#respond Thu, 11 Apr 2024 12:01:03 +0000 https://www.skillvertex.com/blog/?p=6985 Read more]]>

Table of Contents

Python Bitwise operators are mostly used with integer-type objects. Hence, Bitwise operation will be executed through bitwise calculations on integers. Read this article to learn more about the Python Bitwise operator.

What is Python Bitwise Operator

Python Bitwise operators will work with integers. Whereas, they will consider the object as a string instead of treating it as a whole. Thus, different operations will be done on each bit in a string.

Moreover, Python has six bitwise operators such as &, |, ^, ~, << and >>. Each of these operators is mostly binary. This means they can work on the two operands. Each operand is referred to as a binary digit(bit) ie, 1 and 0.

Let us take a look at the table of the different operators of Bitwise

What is Bitwise And Operator?

The Bitwise AND operator works similarly to the logical AND operator. This will provide the result as true, if both the operands will come as 1. The combinations are given below

0 & 0 is 0
1 & 0 is 0
0 & 1 is 0
1 & 1 is 1
OPERATORNAMEDESCRIPTIONSYNTAX
&Bitwise ANDBit wise operator has result bit 1, if both operand bits are 1; or results bit 0.x & y
~Bitwise NOTBitwise NOT operator will invert the individual bits~x
|Bitwise OrThis operator will give the result bit as 1 only if the operand bit is 1 or it will give 0x | y

^Bitwise XORThis operator will provide results bit 1 only if any of the operand bit is 1 , or else it will result bit in 0.x ^ y
<<Bitwise Left shiftThe left operand value will be moved toward’s the right by checking the number of bits.x<<
>>Bitwise Right shiftThe left operand value will be moved toward’s the right by checking the number of bits.

Example

a = 10 = 1010 (Binary)
b = 4 =  0100 (Binary)

a & b = 1010
         &
        0100
      = 0000
      = 0 (Decimal)

What is Bitwise OR Operator?

This symbol “|”  is referred to as Pipe and is also known as Bitwise OR Operator. Only if the bit operand is 1, then it will result in 1, or else it is 0

0 | 0 is 0
0 | 1 is 1
1 | 0 is 1
1 | 1 is 1

Example

a = 10 = 1010 (Binary)
b = 4 =  0100 (Binary)

a | b = 1010
         |
        0100
      = 1110
      = 14 (Decimal)

What is Bitwise NOT operator?

This bitwise operator is referred to as the binary equivalent of logical NOT operators. It will flip each bit, so, 1 will be replaced by 0 and 0 by 1. Hence, it will return the complement of the original number.

Moreover, python will use 2’s complement method. For example, positive integers can be achieved by reversing the bits. In contrast, negative numbers, -x will be written with the bit pattern for (x-1) along all the bits complemented ( switched from 1 to 0 or 0 to 1).

-1 is complement(1 - 1) = complement(0) = "11111111"
-10 is complement(10 - 1) = complement(9) = complement("00001001") = "11110110".

Example

a = 10 = 1010 (Binary)

In computers we usually represent numbers using 32 bits,
so binary representation of 10 is (....0000 1010)[32 bits]

~a is basically 1's complement of a 
i.e ~a should be ~10 = ~(....0000 1010) = (....1111 0101) = intermediate-result

Since bitwise negation inverts the sign bit,
we now have a negative number. And we represent a negative number
using 2's complement.

2's complement of intermediate-result is:
intermediate-res =  0101      //....1111 0101
      
                     1010      //....0000 1010 -(1's complement)

                         +1    
                 -----------
                   =  1011      //....0000 1011
                  -----------
                   =   -11 (Decimal)
                   
thus ~a = -11

What is Bitwise XOR Operator?

The full form of XOR is the exclusive OR. So, the result that is provided by the OR operator on two bits is 1, or else one of the bits is 1.

0 ^ 0 is 0
0 ^ 1 is 1
1 ^ 0 is 1
1 ^ 1 is 0

Example

a = 10 = 1010 (Binary)
b = 4 =  0100 (Binary)

a ^ b = 1010
         ^
        0100
      = 1110
      = 14 (Decimal)

Python Program on the bitwise operator will be given below

# Python program to show
# bitwise operators
 
a = 10
b = 4
 
# Print bitwise AND operation
print("a & b =", a & b)
 
# Print bitwise OR operation
print("a | b =", a | b)
 
# Print bitwise NOT operation
print("~a =", ~a)
 
# print bitwise XOR operation
print("a ^ b =", a ^ b)

Output

a & b = 0
a | b = 14
~a = -11
a ^ b = 14

What is a Shift Operator?

This Shift operator functions to shift the bits of a number left or right and then multiply or divide the number by two respectively. This operator is mainly used to multiply or divide a number by two.

Bitwise right shift

This operator is used to shift the bits of the number to the right and will fill 0 on the voids left as the result. Therefore, a similar effect can be achieved by dividing the number with some power of two.

Example

Example 1:
a = 10 = 0000 1010 (Binary)
a >> 1 = 0000 0101 = 5

Example 2:
a = -10 = 1111 0110 (Binary)
a >> 1 = 1111 1011 = -5 

Bitwise left shift

This operator will be used to shift the bits to the number to the left and that will fill 0 on voids right as the end result. Whereas, a similar effect can be achieved through multiplying the number with some power of two.

Example

Example 1:
a = 5 = 0000 0101 (Binary)
a << 1 = 0000 1010 = 10
a << 2 = 0001 0100 = 20 

Example 2:
b = -10 = 1111 0110 (Binary)
b << 1 = 1110 1100 = -20
b << 2 = 1101 1000 = -40 

Python program is illustrated below to show the shift operators.

# Python program to show
# shift operators
 
a = 10
b = -10
 
# print bitwise right shift operator
print("a >> 1 =", a >> 1)
print("b >> 1 =", b >> 1)
 
a = 5
b = -10
 
# print bitwise left shift operator
print("a << 1 =", a << 1)
print("b << 1 =", b << 1)

Output

a >> 1 = 5
b >> 1 = -5
a << 1 = 10
b << 1 = -20

What is Bitwise Operator Overloading?

Bitwise Operator Overloading is referred to as the extended meaning that is beyond the predefined operational meaning. For instance, operator
+ mostly functions to add the two integers and even join the two strings and combine the two lists.

Moreover, this can be gained a the + will be overloaded with the int class and str class. Operator Overloading consists of the same built-in operator or can work to demonstrate the different behavior of objects in the different classes.

An example to show the Bitwise Operator Overloading is given below

# Python program to demonstrate
# operator overloading
 
 
class Geek():
    def __init__(self, value):
        self.value = value
 
    def __and__(self, obj):
        print("And operator overloaded")
        if isinstance(obj, Geek):
            return self.value & obj.value
        else:
            raise ValueError("Must be a object of class  skillvertex")
 
    def __or__(self, obj):
        print("Or operator overloaded")
        if isinstance(obj, Geek):
            return self.value | obj.value
        else:
            raise ValueError("Must be a object of class  skillvertex")
 
    def __xor__(self, obj):
        print("Xor operator overloaded")
        if isinstance(obj, Geek):
            return self.value ^ obj.value
        else:
            raise ValueError("Must be a object of class Skilvertex")
 
    def __lshift__(self, obj):
        print("lshift operator overloaded")
        if isinstance(obj, Geek):
            return self.value << obj.value
        else:
            raise ValueError("Must be a object of class skillvertex")
 
    def __rshift__(self, obj):
        print("rshift operator overloaded")
        if isinstance(obj, Geek):
            return self.value >> obj.value
        else:
            raise ValueError("Must be a object of class  skill vertex")
 
    def __invert__(self):
        print("Invert operator overloaded")
        return ~self.value
 
 
# Driver's code
if __name__ == "__main__":
    a =  skillvertex(10)
    b =  skillvertex(12)
    print(a & b)
    print(a | b)
    print(a ^ b)
    print(a << b)
    print(a >> b)
    print(~a)

Output

And operator overloaded
8
Or operator overloaded
14
Xor operator overloaded
8
lshift operator overloaded
40960
rshift operator overloaded
8
Invert operator overloaded
-11

Conclusion

To conclude, this article will improve your knowledge of the different types of Python Bitwise operators. Those are Bitwise AND operator, Bitwise OR operator, Bitwise NOT operator, and several others are included.

Python Bitwise Operator- FAQs

Q1. What is a bitwise operator in Python?

Ans. The bitwise operator will function to do the bitwise calculations on integers.

Q2. What is == and != in Python?

Ans. These are used to compare the value of the two objects.

Q3. What is a tuple in Python?

Ans. It is a data structure type that works similarly to the list.

Hridhya Manoj

Hello, I’m Hridhya Manoj. I’m passionate about technology and its ever-evolving landscape. With a deep love for writing and a curious mind, I enjoy translating complex concepts into understandable, engaging content. Let’s explore the world of tech together

]]>
https://www.skillvertex.com/blog/python-bitwise-operator/feed/ 0
Assignment Operators in Python https://www.skillvertex.com/blog/assignment-operators-in-python/ https://www.skillvertex.com/blog/assignment-operators-in-python/#respond Thu, 11 Apr 2024 12:00:53 +0000 https://www.skillvertex.com/blog/?p=6970 Read more]]>

Table of Contents

Assignment Operators will work on values and variables. They are the special symbols that hold arithmetic, logical, and bitwise computations. The value which the operator operates is referred to as the Operand.

Read this article about Assignment Operators in Python

What are Assignment Operators?

The assignment operator will function to provide value to variables. The table below is about the different types of Assignment operator

OperatorDescriptionSyntax
+=Add and Assign operator will add right side operand with left side operand, assign to left operand a+=b
= It will assign the value of the right side of the expression to the left side operandx=y+z
-=Subtract AND operator can subtract the right operand from the left operand and then assign it to the left operand: True if both operands are equala -= b  
*=Subtract AND operator can subtract the right operand from the left operand and then assign it to the left operand: True if both operands are equala *= b     
/=Divide AND will divide the left operand with right operand and then assign to the left operanda /= b
%=Divide AND will divide the left operand with the right operand and then assign to the left operanda %= b  
<<=
It functions bitwise left on operands and will assign value to the left operand a <<= b 
>>=
This operator will perform right shift on operands and can assign value to the left operanda >>= b     

^=
This will function the bitwise xOR operands and can assign value to the left operand a ^= b    

|=
This will function Bitwise OR operands and will provide value to the left operand.a |= b    

&=
This operator will perform Bitwise AND on operand and can provide value to the left operanda&=b
**=
Exponent AND operator will evaluate the exponent value with the help of operands an assign value to the left operanda**=b

Here we have listed each of the Assignment operators

1. What is Assign Operator?

This assign operator will provide the value of the right side of the expression to the left operand.

Syntax

x = y + z

Example

# Assigning values using  
# Assignment Operator 
  
a = 3
b = 5
  
c = a + b 
  
# Output 
print(c)

Output

8

2. What is Add and Assign

This Add and Assign operator will function to add the right side operand with the left side operator, and provide the result to the left operand.

Syntax

x += y

Example

a = 3
b = 5
  
# a = a + b 
a += b 
  
# Output 
print(a)

Output

8

3. What is Subtract and assign?

This subtract and assign operator works to subtract the right operand from the left operand and give the result to the left operand.

Syntax

x -= y

Example

a = 3
b = 5
  
# a = a - b 
a -= b 
  
# Output 
print(a)

Output

-2

4. What is Multiply and assign?

This Multiply and assign will function to multiply the right operand with the left operand and will provide the result in the left operand.

Syntax

x *= y

Example

a = 3
b = 5
  
# a = a * b 
a *= b 
  
# Output 
print(a)

Output

15

5. What is Divide and assign Operator?

This functions to divide the left operand and provides results at the left operand.

Syntax

x /= y

Example

a = 3
b = 5
  
# a = a / b
a /= b 
  
# Output 
print(a)

Output

0.6

6. What is Modulus and Assign Operator?

This operator functions using the modulus with the left and the right operand and provides results at the left operand.

Syntax

x %= y

Example

a = 3
b = 5
  
# a = a % b 
a %= b 
  
# Output 
print(a)

Output

3

7. What is Divide ( floor)and Assign Operator?

This operator will divide the left operand with the right operand, and provide the result at the left operand.

Syntax

x //= y

Example

a = 3
b = 5
  
# a = a // b 
a //= b 
  
# Output 
print(a)

Output

0

8. What is Exponent and Assign Operator?

This operator will function to evaluate the exponent and value with the operands and, provide output in the left operand.

Syntax

x **= y

Example

a = 3
b = 5
  
# a = a ** b 
a **= b 
  
# Output 
print(a)

Output

243'

9.What is Bitwise and Assign Operator?

This operator will function Bitwise AND on both the operand and provide the result on the left operand.

Syntax

x &= y

Example

a = 3
b = 5
  
# a = a & b 
a &= b 
  
# Output 
print(a)

Output

1

10. What is Bitwise OR and Assign Operator?

This operand will function Bitwise OR on the operand, and can provide result at the left operand.

Syntax

x |= y

Example

a = 3
b = 5
  
# a = a | b 
a |= b 
  
# Output 
print(a)

Output

7

11. What is Bitwise XOR and Assign Operator?

This operator will function for Bitwise XOR on the operands, and provide result at the left operand.

Syntax

x ^= y

Example

a = 3
b = 5
  
# a = a ^ b 
a ^= b 
  
# Output 
print(a)

Output

6

12. What is Bitwise Right Shift and Assign Operator?

This operator will function by providing the Bitwise shift on the operands and giving the result at the left operand.

Syntax

x >>= y

Example

a = 3
b = 5
  
# a = a >> b 
a >>= b 
  
# Output 
print(a)

Output

0

13. What is Bitwise Left shift and Assign Operator?

This operator will function Bitwise left shift by providing the Bitwise left shift on the operands and giving the result on the left operand.

Syntax

x <<= y

Example

a = 3
b = 5
  
# a = a << b 
a <<= b 
  
# Output 
print(a)

Output

96

Conclusion

To conclude, different types of assignment operators are discussed in this. Beginners can improve their knowledge and understand how to apply the assignment operators through reading this.

Assignment Operators in Python- FAQs

Q1. What is an assignment statement in Python?

Ans. It will calculate the expression list and can provide a single resulting object to each target list from left to right

Q2. What is the compound operator in Python?

Ans. The compound operator will do the operation of a binary operator and will save the result of the operation at the left operand.

Q3. What are the two types of assignment statements

Ans. Simple Assignment Statements and Reference Assignment Statements are the two types of assignment statements.

Hridhya Manoj

Hello, I’m Hridhya Manoj. I’m passionate about technology and its ever-evolving landscape. With a deep love for writing and a curious mind, I enjoy translating complex concepts into understandable, engaging content. Let’s explore the world of tech together

]]>
https://www.skillvertex.com/blog/assignment-operators-in-python/feed/ 0
Python Loop Lists https://www.skillvertex.com/blog/python-loop-lists/ https://www.skillvertex.com/blog/python-loop-lists/#respond Tue, 19 Mar 2024 06:53:21 +0000 https://www.skillvertex.com/blog/?p=8077 Read more]]>

Table of Contents

In Python, it is possible to traverse the items in the list with the help of a loop construct. Check out this article to learn more about Python Loop Lists.

What is Loop Through a List in Python?

In Python, You can loop through the list of items with the operator’s help for a loop.

Example

# Sample list
my_list = [1, 2, 3, 4, 5]

# Loop through the list and print each element
for element in my_list:
    print(element)

Output

1
2
3
4
5

Loop Through the Index Numbers In Python

Loop through the list of items by indicating their index number in Python. You can use the range() and lens() functions to make the suitable iterable.

# Sample list
my_list = ['apple', 'banana', 'orange', 'grape']

# Loop through the index numbers
for index in range(len(my_list)):
    print(f"Index {index}: {my_list[index]}")

Output

Index 0: apple
Index 1: banana
Index 2: orange
Index 3: grape

Using a While Loop in Python

In Python, looping can be done through the list of items with the help of a while loop. The len () function will allow us to determine the length of the list and then start at 0 and loop the way through the list items by referring to their indexes.

Note: It is required to increase the index by 1 after each iteration.

Example

# Initialize a counter
counter = 0

# Define the condition for the while loop
while counter < 5:
    print(f"Current count: {counter}")
    counter += 1  # Increment the counter in each iteration

print("Loop finished!")

Output

Current count: 0
Current count: 1
Current count: 2
Current count: 3
Current count: 4
Loop finished!

Looping Using the List Comprehension

List Comprehension will provide the shortest syntax for looping through lists.

Example

# Sample list
my_list = [1, 2, 3, 4, 5]

# List comprehension to double each element in the list
doubled_list = [2 * element for element in my_list]

# Print the original and doubled lists
print("Original List:", my_list)
print("Doubled List:", doubled_list)

Output

Original List: [1, 2, 3, 4, 5]
Doubled List: [2, 4, 6, 8, 10]

Conclusion

In conclusion, loops in Python are powerful tools for repeating actions on a set of data, such as a list. Using a for loop, we can easily iterate through each element in a list and perform specific tasks. Additionally, the while loop allows us to repeat actions as long as a certain condition is met.

List comprehension provides a concise way to create new lists by transforming elements from existing ones. These concepts empower us to efficiently handle and manipulate data in Python, making it a versatile and accessible language for various programming tasks.

Python Loop Lists- FAQs

Q1.What is a loop list in Python?

Ans. The loop for Python will allow us to iterate over the sequence such as list, tuple, set, dictionary, and string.

Q2.How to iterate over 2 lists in Python?

Ans. You can iterate over the list in several ways such as the zip() function. zip() function will stop when any one of the lists gets exhausted.

Q3. What is a parallel list in Python?

Ans. A parallel list will consist of two different lists. It will be of the same length and carries the matching information depending upon the position.

Hridhya Manoj

Hello, I’m Hridhya Manoj. I’m passionate about technology and its ever-evolving landscape. With a deep love for writing and a curious mind, I enjoy translating complex concepts into understandable, engaging content. Let’s explore the world of tech together

]]>
https://www.skillvertex.com/blog/python-loop-lists/feed/ 0
Python String Concatenation https://www.skillvertex.com/blog/python-string-concatenation/ https://www.skillvertex.com/blog/python-string-concatenation/#respond Tue, 19 Mar 2024 06:50:25 +0000 https://www.skillvertex.com/blog/?p=7584 Read more]]>

Table of Contents

In Python, it is possible to concatenate two different strings, even with the same string to itself multiple times using the + and the * operator. Read this article to learn more about Python String Concatenation.

What is Python String Concatenation?

The + operator is an addition operator and will return the sum of two numbers. Hence, the + symbol will act as a string concatenation operator in Python. Thus, it will function with two string operands and get the end output as the concatenation of the two.

Hence, the characters of the string on the right of the plus symbol will appear at the left of its string. The result of the concatenation will be considered as the new string.

What are the different ways to concatenate strings?

Python String Concatenation will be considered as the method of adding two strings. Check out the different methods to concatenate strings below:

  1. Using + operator
  2. Using join() method
  3. Using % operator
  4. Using format() function
  5. Using “,” (comma)
  6. Using f-string (Literal String Interpolation)

1. String Concatenation using ‘+’ Operator

In Python, when you join two strings using the + sign, it’s called string concatenation. It’s like combining two pieces of text. However, you need to remember that strings, which are sequences of characters, cannot be changed directly. Whereas, if this operator is used on integers, then it will perform the mathematical addition.

Example 1

In this example, var1 and var2 will be stored in another variable such as var3

# Defining strings
var1 = "Hello "
var2 = "Skillvertex"
 
# + Operator is used to combine strings
var3 = var1 + var2
print(var3)

Output

Hello Skillvertex

2. String Concatenation using join() Method

The join() Method will be considered a String Method. Thus, will return the string where the elements of the sequence will be joined by the string operator.

Therefore, it will accept only the list as its argument, and the list size will be anything. The example below illustrates the Python concatenate string with the join() operator.

var1 = "Skill"
var2 = "vertex"
 
# join() method is used to combine the strings
print("".join([var1, var2]))
 
# join() method is used here to combine 
# the string with a separator Space(" ")
var3 = " ".join([var1, var2])
 
print(var3)

Output

Skillvertex
Skillvertex

3. String Concatenation using ‘%’ Operator

The % Operator will work for string formatting. Additionally, it will be used as a string concatenation. This operator is beneficial when you need to concatenate strings and will do simple formatting.

Example

var1 = "Welcome"
var2 = "Skillvertex"
 
# % Operator is used here to combine the string
print("% s % s" % (var1, var2))

Output

Welcome Skillvertex

4. String Concatenation using the format() function

The str, format will be considered as the string formatting method where they provide multiple substitutions and value formatting. Hence, it can concatenate the elements within the string through positional formatting.

Example

var1 = "Hello"
var2 = "Skillvertex"
 
# format function is used here to 
# combine the string
print("{} {}".format(var1, var2))
 
# store the result in another variable 
var3 = "{} {}".format(var1, var2)
 
print(var3)

Output

Hello Skillvertex
Hello Skillvertex

5. String Concatenation using “, ” comma

A comma will be considered as a great alternative to the string concatenation with the + operator. Thus, it is required to use the comma for combining the data types with the single whitespace in between.

var1 = "Skill"
var2 = "Vertex"
var3 = ".com"
 
# using comma to combine data types
# with a single whitespace.
print(var1, var2, var3)

Output

Skillvertex.com

6. String Concatenation using f-string

Using the F-string for the string concatenation will be operated on the Python versions above 3.6 and will be introduced in the PEP 498- Literal String Interpolation.

# Variables
var1 = "Skill"
var2 = "Vertex"
var3 = ".com"

# String concatenation using f-string
result = f"{var1} {var2} {var3}"

# Printing the result
print(result)

Output

Skill Vertex .com

Conclusion

In Python, string concatenation is the process of combining multiple strings into a single string. The + operator is commonly used for this purpose. When concatenating strings, it’s important to remember that strings are immutable, meaning the original strings are not modified; instead, a new string is created.

Additionally, Python offers convenient f-strings (formatted string literals) for concise and readable string concatenation, allowing variables to be easily inserted into strings. This straightforward process of joining strings provides flexibility in constructing meaningful and dynamic text outputs in Python programs.

Python String Concatenation- FAQs

Q1.What symbol is used to concatenate 2 strings in Python?

Ans. The + operator will combine the 2 strings.

Q2. What functions concatenate two strings?

Ans. In C, the strcat() function will operate to concatenate on the two strings.

Q3.How do I concatenate two string columns in Python?

Ans.df[“full_name”] = df[“first_name”] + “+df[“last_name”]
df[“full_name”] = df[[“first_name”,”last_name”]].agg(” “.join, axis=1)
df = df.withColumn( “full_name”, F.concat(“first_name”, F.lit(” “), “last_name”) )

Hridhya Manoj

Hello, I’m Hridhya Manoj. I’m passionate about technology and its ever-evolving landscape. With a deep love for writing and a curious mind, I enjoy translating complex concepts into understandable, engaging content. Let’s explore the world of tech together

]]>
https://www.skillvertex.com/blog/python-string-concatenation/feed/ 0
Python-Nested if Statements https://www.skillvertex.com/blog/python-nested-if-statements/ https://www.skillvertex.com/blog/python-nested-if-statements/#respond Tue, 19 Mar 2024 06:43:51 +0000 https://www.skillvertex.com/blog/?p=7159 Read more]]>

Table of Contents

Python-Nested IF Statements

Python has nested if statements and this refers to the use of conditional if or else statements inside the existing if statement. Read this article to learn more about Python-nested If Statements.

Whereas, In some cases, we need nesting of if statements to make the entire program flow of code in a semantic order and make it easily readable.

Example of Python-Nested IF Statements

However, nested will be used to check for another condition after another condition has come true. Inside the nested if construct, it is possible to use the if …elif..else construct.

Syntax

The syntax of nested if…else…else construct will be provided below:

if expression1:
   statement(s)
   if expression2:
      statement(s)
   elif expression3:
      statement(s)3
   else
      statement(s)
elif expression4:
   statement(s)
else:
   statement(s)

Example

# Nested if...else...else construct example with number 5

# Set the number to 5
number = 5

# Checking conditions using nested if...else...else
if number > 0:
    print("The number is positive.")
elif number < 0:
    print("The number is negative.")
else:
    print("The number is zero.")

Output

The number is positive.

Conclusion

This article will allow the students to improve their skills and knowledge about the Python nested if statements. A nested if statement in programming allows for the evaluation of multiple conditions in a hierarchical manner.

Therefore, it provides a structured way to handle various scenarios by checking conditions sequentially. Each if statement is associated with a block of code, and the program executes the block corresponding to the first true condition encountered.

Python nested IF statements-FAQs

Q1. What is an example of a nested if statement?

Ans.  if ( num > 0 ) // Outer if ( num < 10 ) // Inner if System.

Q2. What is the if Elif ladder in Python?

Ans. The statements will run from the top down.

Q3. How to create a list in Python?

Ans. In Python, it is possible to create a list by entering the list of the items within the square brackets and then separating each item with a comma.

Hridhya Manoj

Hello, I’m Hridhya Manoj. I’m passionate about technology and its ever-evolving landscape. With a deep love for writing and a curious mind, I enjoy translating complex concepts into understandable, engaging content. Let’s explore the world of tech together

]]>
https://www.skillvertex.com/blog/python-nested-if-statements/feed/ 0