The place where the Information Matters

Python functions and useful syntax with examples

A great information for the beginners of Python coders.

0

Hello, Everyone

It is always better to study the coding from the basic kinds of stuff. Something like A B C D of the programming. I have compiled the various information on Python scripting from the very basic level. If you are expert in the Python, this info might sound boring to you. But if you are a beginner in Python scripting, and if you never coded before, you are going to love this.

  • To run a python file (.py extension) from a particular directory

Name of the file: Newfile.py Location: C:/My Documents

Code: C:/My Documents/Newfile.py

  • To print a text using python

Code: print (“Hello, World”)

Output: Hello, World

  • To exit from the python command line

Code: exit()

  • Python indentation (Example)

Code: if 2 > 1:

    print(“Two is greater than one!”)

Output: Two is greater than one!

  • To add a comment in python code just add a #sign at the beginning of the code OR use Docstrings (triple quotes)

Example: #print (“hello world”)

“””We are at the end of the course”””

  • Creating variables

Example:

x=10

y=”Mike”

print (x)

print (y)

Output:  10

Mike

  • Printing variables

Use print statement to display the variables, use + sign to concatenate the variables

Example: x= “Knowledge is “

  y=”Power”

  z= x+y

  print (z)

Output: Knowledge is Power

Example: x=”Mike”

  print (“My name is ” + x)

Output: My name is Mike

Example: x=8

  y=15

  print (x+y)

Output: 23

  • Verifying the type of any object use type() function

Example: x=1

  y=3.1416

  z=3G

Command: print(type(x)) Output: <class ‘int’>

Command: print(type(y)) Output:<class ‘float’>

Command: print(type(z)) Output:<class ‘str’>

  • To cast a variable to an object (Equivalent to the concept of to_date or to_char function in SQL)

x = int(1)   # x will be 1

y = int(2.8) # y will be 2

z = int(“3”) # z will be 3

x = float(1)     # x will be 1.0

y = float(2.8)   # y will be 2.8

z = float(“3”)   # z will be 3.0

w = float(“4.2”) # w will be 4.2

x = str(“s1”) # x will be ‘s1’

y = str(2)    # y will be ‘2’

z = str(3.0)  # z will be ‘3.0’

  • To quote a string in Python, we can use both single quote (‘ ‘) or double quote (” “)
  • The location of objects in Python is counted starting for 0 (i.e 0,1,2….) not from 1.
  • To get the character at a particular position

Code: a=”Howareyou”

   print (a[3])

Output: a    #Remember, the sequence starts at 0, not 1

  • To get the characters from one position to another

Code: a=”Howareyou”

   print (a[3:5])

Output: are

  • To remove the whitespaces from the beginning or the end of a string (equivalent to TRIM function of SQL)

Code: a = ” I am Sam “

   print(a.strip())

Output: “I am Sam”

  • To get the length of a string

a=”My World”

       print(len(a))

Output: 8

  • To get the result in all lower case:

a = “Summer Of 69”

print(a.lower())

Output: “summer of 69”

  • To get the result in all upper case:

a=”Summer of 69″

print(a.upper())

Output: “SUMMER OF 69”

  • To replace one string with another:

a= “Summer of 69”

print(a.replace(“m”,”w”))  #replaces all “m” with “w”

Output: “Suwwer of 69”

  • To split the string into substring if there is a common separator:

a=”10,20,30,40″

print (a.split(“,”) #comma is the separator

Output: ’10’,’20’,’30’,’40’

  • Command line input:

print(“How old are you?”)

x=input()

print (“My age is “+x)

Output: “My age is 20” #20 is input value

 

  • The concept of List: A list is a collection which is ordered and changeable. In Python, lists are written with square[] brackets.

create a list: newlist = [“Apple”,”Samsung”,”Google”]

print (newlist)

  • Change one of the item in the list to another: 

newlist = [“Apple”,”Samsung”,”Google”]

newlist[1]=”Motorola” #replaces the second item as python list starts from 0

print (newlist)

Output: [“Apple”,”Motorola”,”Google”]

  • Another way to create a list: Using list() constructor

mynewlist = list((“Nokia”,”Cricket”,”ZTE”)) #double round bracket

  • To append an item into a list:

newlist = [“Apple”,”Samsung”,”Google”]

newlist.append (“LG”)

Output: [“Apple”,”Samsung”,”Google”,”LG”]

  • To remove an item from a list:

newlist = [“Apple”,”Samsung”,”Google”,”LG”]

newlist.remove(“LG”)

print (newlist)

Output: [“Apple”,”Samsung”,”Google”]

  • To return the number of items in a list:

newlist = [“Apple”,”Samsung”,”Google”,”LG”]

print(len(newlist))

Output: 4

 

List Methods:

oldlist = list((“Nokia”,”Cricket”,”ZTE”))

print (oldlist)

Output: [‘Nokia’, ‘Cricket’, ‘ZTE’]

  • To remove a object from a list

oldlist.remove(“ZTE”)

Output: [‘Nokia’, ‘Cricket’]

  • To get the number of items in a list

[‘Nokia’, ‘Cricket’, ‘ZTE’] — current list

print(len(oldlist))

Output: 3

  • To clear the elements from the list

oldlist.clear()

  • To copy a list and its element

oldlist.copy()

  • To get a count of a particular item in a list

oldlist.count(‘ZTE’)

print (“Total number of ZTE phone “, count)

Output: Total number of ZTE phone  1

  • To add a newlist at the end of current list

oldlist = list((“Nokia”,”Cricket”,”ZTE”))

oldlist1 = [“Philips”,”LG”,”Sanyo”]

oldlist.extend(oldlist1)

print (oldlist)

Output: [‘Nokia’, ‘Cricket’, ‘ZTE’, ‘Philips’, ‘Panasonic’, ‘LG’, ‘Sanyo’]

  • To get the index of the first element with the specified value

oldlist= [‘Nokia’, ‘Cricket’, ‘ZTE’, ‘Philips’, ‘Panasonic’, ‘LG’, ‘Sanyo’]

index = oldlist.index(“LG”)

print (“The index of LG is”, index)

Output: The index of LG is 4

  • To add an element on a list at a specified position:

oldlist.insert(4, “Panasonic”)

print (oldlist)

Output: [‘Nokia’, ‘Cricket’, ‘ZTE’, ‘Philips’, ‘Panasonic’, ‘LG’, ‘Sanyo’]

  • To remove an element from a specified position

oldlist.pop(3)

print(oldlist)

Output: [‘Nokia’, ‘Cricket’, ‘ZTE’, ‘LG’, ‘Sanyo’]

  • To remove the first item with the specified value:

oldlist.remove(“LG”)

print (oldlist)

Output: [‘Nokia’, ‘Cricket’, ‘ZTE’, ‘Sanyo’]

  • To reverse the order of the list:

oldlist.reverse()

print (oldlist)

Output: [‘Sanyo’, ‘ZTE’, ‘Cricket’, ‘Nokia’]

  • To sort the elements of the list:

oldlist.sort()

print(oldlist)

Output: [‘Cricket’, ‘Nokia’, ‘Sanyo’, ‘ZTE’]

 

Python Tuples:

A tuple is a collection which is ordered and unchangeable. In Python, tuples are written with round brackets.

  • Tuple example:

newtuple  = (“Red”,”Green”,”Blue”)

print (newtuple)

  • To return the element of an tuple from a specific position:

print(newtuple[2])

Output: Blue

  • Another way to create a tuple is via tuple() constructor

newtuple = tuple((“Red”,”Green”,”Blue”))

print (newtuple)

  • To get the number of items in a tuple:

newtuple = tuple((“Red”,”Green”,”Blue”))

print(len(newtuple))

 

Python Sets

A set is a collection which is unordered and unindexed. In Python, sets are written with curly brackets.

  • Create a set

newset = {“Red”,”Green”,”Blue”}

print(newset)

  • Another way to create a set is using set() constructor

newset = set ((“Red”,”Green”,”Blue”))

print (newset)

  • To add an element in a set

newset = set ((“Red”,”Green”,”Blue”))

newset.add (“Yellow”)

print (newset)

Output: (“Red”,”Green”,”Blue”,”Yellow”)

  • To remove an element from a set

newset = set ((“Red”,”Green”,”Blue”,”Yellow”))

newset.remove (“Yellow”)

print (newset)

Output: (“Red”,”Green”,”Blue”)

  • To get the number of elements in the set

newset = set ((“Red”,”Green”,”Blue”,”Yellow”))

print(len(newset))

Output: 4

Python Dictionary

  • Creating a dictionary

mydict = {
“A”: “Apple”,
“B”: “Ball”,
“C”: “Cat”
}
print(mydict)

Output: {‘A’: ‘Apple’, ‘B’: ‘Ball’, ‘C’: ‘Cat’}

  • Change the definition in the dictionary:

mydict = {
“A”: “Apple”,
“B”: “Ball”,
“C”: “Cat”
}

mydict[“A”] = “Almond”
print(mydict)

Output: {‘A’: ‘Almond’, ‘B’: ‘Ball’, ‘C’: ‘Cat’}

  • Another way to create dictionary is using dict()

mydict = dict(

A = “Apple”,

B =  “Ball”,

C =  “Cat”

)

print(mydict)

Output: {‘A’: ‘Apple’, ‘B’: ‘Ball’, ‘C’: ‘Cat’}

  • Adding a element to the dictionary

mydict = dict(

A = “Apple”,

B =  “Ball”,

C =  “Cat”

)

mydict [“D”] = “Dog”

print(mydict)

Output: {‘A’: ‘Apple’, ‘B’: ‘Ball’, ‘C’: ‘Cat’, ‘D’: ‘Dog’}

  • Removing items from a list

mydict = dict(

A = “Apple”,

B =  “Ball”,

C =  “Cat”

)

del (mydict [“C”] )

print(mydict)

Output: {‘A’: ‘Apple’, ‘B’: ‘Ball’}

  • To get the number of items in a dictionary

mydict = dict(

A = “Apple”,

B =  “Ball”,

C =  “Cat”

)

print(len(mydict))

Output: 3

Disclaimer:

This article was collected and published by Mr. Bijaya Subedi. Bijaya is currently working as Lead Software Test Analyst in the Richmond, VA based financial company. Some of the information in this article are direct copy paste from some other sources. This is article is solely written for the information purpose and has no commercial motives.

Source: www.w3schools.com

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.