Python

Introduction of Python:
Python is an interpreted, object oriented, high-level programming language with dynamic semantics.
It has compressed codes. Python syntax are easy compared to other languages.

History:
Python was introduced by Guido Van Rossum in 1989.
First version of Python released in 1991.

  • Features:
    • Easy to learn and implement
    • Open source
    • Broad standard library
    • Cross platform
    • Work on interpreter logic
    • Multi-paradigm language
    • High-level programming
    • Extendable language
    • Expressive programming language
    • GUI programming support
  • Applications of Python:
    • Network programming
    • Data analysis
    • Robotics
    • Website and App developments
    • Desktop application developments
    • Games Development
    • Web scraping
    • Data visualization
    • Scientific calculation
    • Machine learning and AI
    • 3D application development
    • Audio and video software development
  • Variables:

In Python, variable is a referential name of a value, or value address. Variables are containers for storing data values. Variables do not need to be declared with any particular type, and can even change type after they have been set.

E.g.  a= “Nepal”   # is a string type

               b= 50    # is a integer type

If you want to specify the data type of a variable, this can be done with casting.

x = str(3)    # x will be ‘3’
y = int(3)    # y will be 3
z = float(3)  # z will be 3.0

  1. Rules for naming the variables:
    1. Variable starts from alphabets only and can be followed by numbers
    1. It does not contain any space in between
    1. It does not contain any symbols except underscore
    1. Python is case sensitive for variable.
    1. Multi Words Variable Names

Variable names with more than one word can be difficult to read.

There are several techniques you can use to make them more readable:

Camel Case

Each word, except the first, starts with a capital letter: myVariableName = “John”

Pascal Case

Each word starts with a capital letter: MyVariableName = “John”

Snake Case

Each word is separated by an underscore character: my_variable_name = “John”

  • Same values has same cell address:  e.g. a =
    • Many Values to Multiple Variables:

E.g. x, y, z = “Orange”, “Banana”, “Cherry”

  • One Value to Multiple Variables:

x = y = z = “Orange”
print(x)
print(y)
print(z)

  • Unpack a Collection: If you have a collection of values in a list, tuple etc. Python allows to extract the values into variables, is called unpacking.

fruits = [“apple”, “banana”, “cherry”]
x, y, z = fruits
print(x)
print(y)
print(z)

  •  
  • Operators: are the special symbols (character) or set of characters that instruct to perform some operation, calculation.
    • Arithmetic operators: are used to perform mathematical calculation
OperatorSyntaxE.g.Output
+  # additionC= A + BC= 5 + 5.510.5
–   # subtractC= a – bC = 10 – 55
*  # multiplicationC= a * bC = 10 * 550
/  # divideC = a / bC = 5 / 22.5
%  # modulusC = a % bC= 5 % 21
//  # floor (int) divideC = a // bC = 5 // 22
**   # exponent (power)C= a ** bC= 5**225
  • Assignment operators
=A = 10*=A *= 3 Or A = A *  2
+=A = A + 1 Or  A + = 1/=A = A / 2 Or  A / = 2
-=A = A – 2 Or A – = 2%=A = A % 2 Or  A % = 2
//=A = A // 2 Or  A // = 2**=A = A ** 2 Or  A ** = 2
&=A = A & 2 Or  A & = 2|=A = A | 2 Or  A | = 2
^=A = A ^ 2 Or  A ^ = 2>>=A = A >> 2 Or  A >> = 2
<<=A = A << 2 Or  A << = 2  
  • Comparison operators:
==Equal toLess than
<=Less than and equal toGreater than
>=Greater than and equal to!=Not equal to
  • Logical operators:   
OperatorDescriptionExample
andReturns True if both statements are truex < 5 and  x < 10
orReturns True if one of the statements is truex < 5 or x < 4
notReverse the result, returns False if the result is truenot (x < 5 and x < 10)
  • Membership operators
  • Identity operators
  • Is
  • Is not
    • Bitwise operators
      • &   #and
      • |  #or
      • ^  #xor
  1. Built-in Data Types

Python has the following data types built-in by default:

Text typestrX= “Hello ! Nepal”
Numeric typeint, float, complexA=20   B=20.5      a=5x
Sequence typelist, tuple, rangeL=[2,5,10]  T=(5,15) R=range(10)
Mapping typedictD={“name”: “Surendra” “Weight”: 60
Set typesset, frozensetS={“apple”,”banana”} s=frozenset({})
Boolean typeboolA=True    a= False
Binary typesbytes, bytearray, memoryviewA=b”hello” a=bytearray(10) a=memoryview(bytes(5))
  • Python Mutable data types are those whose values can be changed in place whereas Immutable data types are those that can never change their value in place.

color = [“Red”, “Green”, “Blue”]
print(color)
color[0] = “Black”
color[-1] = “White”
print(color)

Mutable data types:

  1. Lists: A list is a data structure in Python that is a mutable (changeable), ordered sequence of elements. Python List stores data in a bracket with comma-separated. It’s one of the most frequently used and very versatile data types used in Python. E.g. :

colorList = [“Red”, “Yellow”, “green”]

print(colorList)

list1 = [‘School’, ‘Students’, 2000];

print(list1)

Python Lists Functions

list.append(elem) – adds a single element to the end of the list. Common error: does not return the new list, just modifies the original.

colorList = [“Red”, “Yellow”, “green”]

print(colorList)

colorList.append(“Black”)

print(colorList)

Output : [‘Red’, ‘Yellow’, ‘green’]

[‘Red’, ‘Yellow’, ‘green’, ‘Black’]

list.insert(index, elem) – inserts the element at the given index, shifting elements to the right.

colorList = [“Red”, “Yellow”, “Green”]

print(colorList)

colorList.insert(2, “Black”)

print(colorList)

Output : [‘Red’, ‘Yellow’, ‘Green’]

[‘Red’, ‘Yellow’, ‘Black’, ‘Green’]

list.extend(list2) adds the elements in list2 to the end of the list. Using + or += on a list is similar to using extend().

list1 = [1, 2, 3]

list2 = [8, 5, 6]

list1.extend(list2)

print(list1)

Output : [1, 2, 3, 8, 5, 6]

list.index(elem) : Searches for the given element from the start of the list and returns its index. Throws a ValueError if the element does not appear

colorList = [“Red”, “Yellow”, “Green”]

print(colorList)

print(colorList.index(“Yellow”))

Output : [‘Red’, ‘Yellow’, ‘Green’]

1

list.remove(elem) :  Searches for the first instance of the given element and removes it (throws ValueError if not found)

colorList = [“Red”, “Yellow”, “Green”]

print(colorList)

colorList.remove(“Yellow”)

print(colorList)

Output : [‘Red’, ‘Yellow’, ‘Green’]

[‘Red’, ‘Green’]

list.sort() : Sorts the list in place (doesn’t return it).

list1 = [3, 2, 1, 5, 7, 6]

print(list1)

list1.sort()

print(list1)

Output : [3, 2, 1, 5, 7, 6]

[1, 2, 3, 5, 6, 7]

list.reverse() : Reverses the list in place (does not return it)

colorList = [“Red”, “Yellow”, “Green”]

print(colorList)

colorList.reverse()

print(colorList)

Output : [‘Red’, ‘Yellow’, ‘Green’]

[‘Green’, ‘Yellow’, ‘Red’]

list.pop(index) : Removes and returns the element at the given index. Returns the rightmost element if index is omitted.

colorList = [“Red”, “Yellow”, “Green”]

print(colorList)

print(colorList.pop(2))

print(colorList)

Output : [‘Red’, ‘Yellow’, ‘Green’]

Green

[‘Red’, ‘Yellow’]

  • Dictionaries:

Python Dictionaries is a collection (or data structure) that is unordered, mutable (changeable), and indexed. In Python, dictionaries are written with curly brackets { }, and they have keys and values.

Python Dictionaries Syntax and Example

The dictionary syntax is very simple in python : dict = {“key” : “value”,…}

student = {

    “name”: “Sam”,

    “Father Name”: “John”,

    “class”: 5,

    “Address”: “171 Street 4A, Bangalore, India”,

}

print(student)

Output : {‘name’: ‘Sam’, ‘Father Name’: ‘John’, ‘class’: 5, ‘Address’: ‘171 Street 4A, Bangalore, India’}

This is the dictionary example. So here item is referred to as keys, not indexes. For dictionaries you can create custom indexes, so to say and so these are key and value.

Access Single Item in Python Dictionaries

You can access an item in the dictionary by using a key.

student = {

    “name”: “Sam”,

    “Father Name”: “John”,

    “class”: 5,

    “Address”: “171 Street 4A, Bangalore, India”,

}

print(student[“name”])

Output: Sam

Change the values in Dictionaries :

Let’s Change the address in a python dictionary. It’s very easy with using the key.

student = {

    “name”: “Sam”,

    “Father Name”: “John”,

    “class”: 5,

    “Address”: “171 Street 4A, Bangalore, India”,

}

student[“Address”] = “14 Street 9C, None”

print(student)

Output : {‘name’: ‘Sam’, ‘Father Name’: ‘John’, ‘class’: 5, ‘Address’: ’14 Street 9C, None’}

Adding new Items :

Just add a new key and it’s value, check this code.

student = {

    “name”: “Sam”,

    “Father Name”: “John”,

    “class”: 5,

    “Address”: “171 Street 4A, Bangalore, India”,

}

student[“contact”] = “0987654321”

print(student)

Output : {‘name’: ‘Sam’, ‘Father Name’: ‘John’, ‘class’: 5, ‘Address’: ‘171 Street 4A, Bangalore, India’, ‘contact’: ‘0987654321’}

Removing Items:

Using del() function in python, you can remove the item from the dictionary. See this example deleting (removed) “Address” item.

student = {

    “name”: “Sam”,

    “Father Name”: “John”,

    “class”: 5,

    “Address”: “171 Street 4A, Bangalore, India”,

}

del(student[“Address”])

print(student)

Output : {‘name’: ‘Sam’, ‘Father Name’: ‘John’, ‘class’: 5}

How to Find the Length of the Dictionary?

len() function returns the size (length) of the dictionary:

student = {

    “name”: “Sam”,

    “Father Name”: “John”,

    “class”: 5,

    “Address”: “171 Street 4A, Bangalore, India”,

}

print(len(student))

Output: 4

  • Sets

Python sets are an unordered collection of items. In a set, all elements (items) are unique (no duplicates) and must be immutable (not changeable) but the set as a whole is mutable. You can create a set by placing all the items inside curly braces { } and separated by comma or by using the built-in function set().

Set can have any number of different types like – integer, float, tuple, strings, etc. One more thing set can’t have mutable elements.

Immutable data types in Python:

  • Integers
    • Floating-Point numbers
    • Booleans
    • Strings
    • Tuples
  • Data Type in Python
    • Numeric Data types: Integers, float, complex
    • Sequence Data types: string, list, tuple
    • Dictionary
    • Set
  •  

ShareSkills: Computer Knowledge

Design a site like this with WordPress.com
Get started