Python Colon Operator

Python Colon Operator(:)

  • The colon(:) symbol is used for multiple purposes in Python
  • As slice operator in list, tuple, and string data type.
  • It is also used in if, while, for, def and class statements.
  • It is used in dictionaries.

 

 


 

Colon With List

01. Example

numberList = [10, 20 ,30 ,40 ,50]
print(numberList[1:3])
print(numberList[:3])
print(numberList[2:])

Output:

[20, 30]
[10, 20, 30]
[30, 40, 50]

 


 

Colon With Tuple

01. Example

numberTuple = [10, 20 ,30 ,40 ,50]
print(numberTuple[1:3])
print(numberTuple[:3])
print(numberTuple[2:])

Output:

(20, 30)
(10, 20, 30)
(30, 40, 50)

 


 

Colon With String

01. Example

string = "zeroones.org"
print(string[0:4])
print(string[4:7])
print(string[:7])
print(string[9:])

Output:

zero
one
zeroone
org

 


 

Colon With Dictionary

01. Example

dictionary = {'0':'zero','1':'one','2':'two','3':'three','4':'four', '5':'five','6':'six','7':'seven','8':'eight','9':'nine'}

print("The Dictionary:n",dictionary)

Output:

The Dictionary:
 {'0': 'zero', '1': 'one', '2': 'two', '3': 'three', '4': 'four', '5': 'five', '6': 'six', '7': 'seven', '8': 'eight', '9': 'nine'}

 


 

Colon With If-Else

01. Example

x=2

if x>10:
    print("Number is greater than 10.")
print('This will always print.')

Output:

This will always print.

 


 

Colon With For Loop

Example:

Find the product of all numbers present in the list.

x=[10,20,30,40,50]
product=1
for element in x:
             product*=element

print(Product is: {}.format(product))

Output:

Product is: 12000000

 


 

Colon With While Loop

01. Example

N=[10,20,30,40,50]
product=1
index=0

while index<len(N):
    product = product*N[index]
    index+=1
print("Product is:{}".format(product))

Output:

Product is:12000000

 


 

Colon With Function

01. Example

def functionCall(x):
    if(x>10):
        print("Number Greater then 10.")
    else:
        print("Number Greater less then 10.")

number = 10
functionCall(number)

Output:

Number Greater less then 10.

 


 

Colon With Class

01. Example

class website:
     domain = "zeroones.org"
     
print(website.domain)

Output:

zeroones.org

 


 

Leave a comment