Python Tutorial for Beginners to Expert in 30 Days

Spread the love

What is Python:

Python is an interpreted, object-oriented, high-level programming language. It was created by Guido van Rossum and released in 1991. It is easy to learn and efficient with high-level data structures. Python codes are much shorter when compare to C, C++, Java.

Application of Pythons

Web Development
Scientific & Numeric ( Data Science, Machine Learning, AI)
Network Programming
Software & Game Development

How to Install Python?

We need to install python to get started. You can download the latest version of python from https://www.python.org/downloads/.
You can download for windows, mac, Unix and Linux os

How to check Python Version:

You need to execute the below command to know about the version of python.

>>> python –version

Python has different syntax for version 2.7 and 3.7. In this tutorial, we are using python 3.7 version.

Python First Program

I love the first program in python. Use Print function with curly braces to with quotes text to print hello world.

Code:
# This if First Python Program
print(‘Hello, world!’)

  1. Python Get Started
  2. Python Variables and Data Types
  3. Python Identifiers and Reserved Words
  4. Python Comments
  5. Python Operators
  6. Python Casting
  7. Python Strings
  8. Python Conditional Statements
  9. Python Functions
  10. Python For loops
  11. Python Arrays
  12. Python Lists
  13. Python List Comprehension
  14. Python Dictionaries
  15. Python Sets
  16. Python Modules
  17. Python Input/output
  18. Python Errors and Exceptions
  19. Python OOPs
  20. Python Regular Expressions
  21. Python Socket Programming
  22. Migrate from python 2 to Python 3
  23. Python In Built Functions
  24. Python Iterators
  25. Python Modules and Import
  26. Python File Handling
  27. Python and MySQL
  28. Python Programs
  29. Python  fibonacci Number program
  30. Python Abs Program
  31. Python Leap Year Program
  32. Python Factorial Program
  33. Python Prime Number Program
  34. Python Even or Add Number Program
  35. Python Positive or Negative Number Program
  36. Python Simple Calculator Program
  37. Python Program to Convert Decimals
  38. Python Program to celsius to fahrenhei
  39. Python lambda Function Programs
  40. Python mean,median and mode Program
  41. Python Random Number Program
  42. Python Math Functions with Programs
  43. Python statistics with Programs
  44.  Python round Function 
  45.  Python Range Function 
  46. Python Min() and Max() Functions 
  47. Python Zip() Function
  48. Python program to calculate area of traingle

Python Get Started:

We need to install python to get started. You can download the latest version of python from https://www.python.org/downloads/.
You can download for windows, mac, Unix and Linux os

How to check Python Version:

You need to execute the below command to know about the version of python.

>>> python –version

Python has different syntax for version 2.7 and 3.7. In this tutorial, we are using python 3.7 version.

Python First Program

I love the first program in python. Use Print function with curly braces to with quotes text to print hello world.

Code:
# This if First Python Program
print(‘Hello, world!’)

In Python, we can write and execute code in two modes. One is Interactive and second one is Script Mode.

Interactive Mode Programming:

You have to open command prompt then type python to log in interpreter

C:/>python
Python version: 3.63
>>> print “Hello, World!”
Output: Hello, World!

Server Side Mode Programming:

When you run a program from the interpreter, It won’t exist for a long time. It will delete code after exit from it. You have to save file with .py file extension to run.

$python first.py
Output: Hello, World!

Python Variable:

Variables are used to store values. In python, there is no explicit declaration for variables. If you pass an integer value to a variable it will automatically create integer variable same with other formats also.

Example:

a= 1 b=2.5 c="test" print(a) print(b) print(c) print(type(a)) print(type(b)) print(type(c))

Output:
1
2.5
test
<class ‘int’>
<class ‘float’>
<class ‘str’>

Python Data Types:

In python we have mainly 5 data types
• Numbers
• Strings
• Lists
• Tuples
• Dictionaries

Python Numbers:

We have 3 types of numbers in python, if we assign value to them, if will convert to that datatype automatically.
1. Integer
2. Float
3. Complex

Python Integers:

Integer is a Number.  You can define Positive, Negative Integer numbers with decimals

Example:

a= 100 print(a) print(type(a)) a= -100 print(a) print(type(a))

Output:
100
<class ‘int’>
-100
<class ‘int’>

Python Float:

Float number is a fractional value. You can pass positive and negative numbers.

Example:

a= 10.555555 print(a) print(type(a)) a= -10.5758585 print(a) print(type(a))

Output:
10.555555
<class ‘float’>
-10.5758585
<class ‘float’>

Python Complex Numbers:

Complex is a number with equation a+bj . a and b are the real values of graph. J is an imaginary number. We can represent with positive and negative numbers.

Example:

c= 10+5j print(c) print(type(c)) c= -10+5j print(c) print(type(c))

Output:
(10+5j)
<class ‘complex’>
(-10+5j)
<class ‘complex’>

Python Strings:

String is a representation of continuous characters. In Python, You can define by using single quotes and double quotes. You can find substring by using slice operator [:]. The string index is starting from 0. You can concatenate string by using + operator and * used to repeat the strings.

Example:

Str = 'I love python' print(Str) print(Str[0]) print(Str) print(Str[:6]) print(Str[6:]) print(str+str) print(Str+' '+ Str) print(Str *2)

Output:
I love python
I
I love python
I love
Python
Python
I love python I love python
I love pythonI love python

Python Lists:

Python list is versatile sequence data type, you can store integer, float, character in a single list. Same like arrays it index is also zero. You can use slice [:] operator to call subsets. You can concatenate lists by using + operator and repeat by using * operator.

Example:

Str = ['I', 'love', 'python', 'version','3.6'] print(Str) print(Str[0]) print(Str) print(Str[:2]) print(Str[2:]) print(Str+Str) print(Str * 2)

Output:
[‘I’, ‘love’, ‘python’, ‘version’, ‘3.6’]
I
[‘I’, ‘love’, ‘python’, ‘version’, ‘3.6’]
[‘I’, ‘love’]
[‘python’, ‘version’, ‘3.6’]
[‘I’, ‘love’, ‘python’, ‘version’, ‘3.6’, ‘I’, ‘love’, ‘python’, ‘version’, ‘3.6’]
[‘I’, ‘love’, ‘python’, ‘version’, ‘3.6’, ‘I’, ‘love’, ‘python’, ‘version’, ‘3.6’]

Python Tuples:

Python tuples are same like lists. The only difference is it is read only lists. It can’t update. You can define by using Parenthesis operator ()

Example:

Str = ('I', 'love', 'python', 'version','3.6') print(Str) print(Str[0]) print(Str) print(Str[:2]) print(Str[2:]) print(Str+Str) print(Str * 2)

Output:
(‘I’, ‘love’, ‘python’, ‘version’, ‘3.6’)
I
(‘I’, ‘love’, ‘python’, ‘version’, ‘3.6’)
(‘I’, ‘love’)
(‘python’, ‘version’, ‘3.6’)
(‘I’, ‘love’, ‘python’, ‘version’, ‘3.6’, ‘I’, ‘love’, ‘python’, ‘version’, ‘3.6’)
(‘I’, ‘love’, ‘python’, ‘version’, ‘3.6’, ‘I’, ‘love’, ‘python’, ‘version’, ‘3.6’)
If you forcefully try to change values in lists it will produce the following error
Example:
Str[0] =’test’
TypeError: ‘tuple’ object does not support item assignment

Python Dictionaries:

Python dictionaries are unordered data types which come with key and value pairs. We can call values by using keys. The keys can be numbers and strings. Dictionaries are defined by using {}.

Example:

Dictionary = {"name":"python", "version":"3.6"} print(Dictionary) print(Dictionary['name']) print(Dictionary['version'])

Output:
{‘name’: ‘python’, ‘version’: ‘3.6’}
python
3.6

Python Identifiers :

An identifier is a name used to identify the variables, functions, classes, objects, and modules.
You don’t have to use special characters like “@,$,%” in identifiers.

Python Reserved words :

Python has a list of a reserved word for a specific task. We are not allowed those words as identifiers.
Here is the list of words:
1. and
2. exec
3. not
4. assert
5. finally
6. or
7. break
8. for
9. pass
10. class
11. from
12. print
13. continue
14. global
15. raise
16. def
17. if
18. return
19. del
20. import
21. try
22. elif
23. in
24. while
25. else
26. is
27. with
28. except
29. lambda
30. yield
31. true
32. false
33. None

Python Comments:

Single Line Comment:

If you want to comment a single line in python, you have to use # in starting of the sentence.

Example:
#print("hello world")

 

Multiline Comment:

For multiline comments, you have to use triple quotes in starting and ending of the lines

Example:
"""a= 1
b=2
c=a+b
print(c) """

Python Operators:

In C, C++ languages like python also have 7 types of operators

1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators

1. Arithmetic Operators :

Arithmetic Operators are like addition, subtraction, division, multiplication, Modular, and Floor Division.

Example:

a= 5 b= 4 print('a+b =', a+b) print('a-b =', a-b) print('a*b =', a*b) print('a/b =', a/b) print('a%b =', a%b) print('a//b =', a//b)

Output:

a+b = 9
a-b = 1
a*b = 20
a/b = 1.25
a%b = 1
a//b = 1

2. Comparison Operations:

Comparison Operators compare both sides of the values. It will produce true and false results. The operators ==,!=, >, <, <>, <=,>=.

Example:

a= 5
b= 4
print('a==b =', a==b)
print('a!=b =', a!=b)
print('a>b =', a>b)
print('a<b =', a<b)
print('a>=b =', a>=b)
print('a<=b =', a<=b)

Output:

a==b = False
a!=b = True
a>b = True
a<b = False
a>=b = True
a<=b = False

3. Assignment Operators:

These operators are used to assign values to variables. You can do arithmetic operations while assigning variables also.

Example:

a= 5 b= 4 c=0 print('C value', c) c+=a print('C value', c) c*=a print('C value', c) c-=a print('C value', c) c/=a print('C value', c) c%=a print('C value', c) c//=a print('C value', c) c**=a print('C value', c)

Output:

C value 0
C value 5
C value 25
C value 20
C value 4.0
C value 4.0
C value 0.0
C value 0.0

 

Python Logical Operators:

In python we have 3 logical operators are there.  And, Or, Not –  We can use these operators with multiple statement comparisons

And  –  If both the statements true it returns, true value

Or  – if any one of the statement false it returns true value

Not – It is used to reverse the result with true to false or false to true

Example:

a= 5 b= 4 c=7 print('a>b and c>b =', a>b and c>b) print('a>b or c>b =', a>b or c>b) print('not(a>b or c>b) =', not(a>b and c>b))

Output:

a>b and c>b = True

a>b or c>b = True

not(a>b or c>b) = False

 

Python Identity Operators:

We have 2 identity operators in python. We can use them to compare variable values. If the value of variable is equal it returns true value, otherwise it returns false value.

Is  –  Returns true value if the both variables have same object

Is not – Returns true value if the both variables have not same object

Example 1:

a= 5 b= 4 print('a is b', a is b) print('a is not b =', a is not b)

Output:

a is b False

a is not b = True

Example 2:

a= 5 b= 5 print('a is b', a is b) print('a is not b =', a is not b)

Output:

a is b True

a is not b = False

 

Python Membership operators:

Python membership operators are used to test the variables are present in the sequences of tuples, lists, arrays and strings.  We have 2 membership operators.

In –  Returns true value, if the object present in sequence

Not in – Returns true value, if the object not present in sequence

Example 1:

a= 3 b= [2,3,5,8,9] print('a in b', a in b) print('a not in b =', a not in b)

Output:

a in b True

a not in b = False

 

Example 2:

a= 4 b= [2,3,5,8,9] print('a in b', a in b) print('a not in b =', a not in b)

Output:

a in b False

a not in b = True

 

Python Bitwise Operators:

In python we have 6 bitwise operators – &, |, ^, ~, >>, <<.  It performed operation bit by bit between variables.

Example:

a= 5
b= 5
print('a & b =', a & b)
print('a | b =', a | b)
print('a ^ b =', a ^ b)
print('a ~ b =',  a ~ b)
print('a<<b =',  a<<b)
print('a>>b =',  a>>b)

Output:

a & b = 5

a | b = 5

a ^ b = 0

a ~ b = -6

a<<b = 160

a>>b = 0

Python casting :

The process of converting from one datatype to another is called type casting. In python, First we need to know what are the current datatypes and how we can do it.

We have 2 types of type casting

  1. Implicit type conversion
  2. Explicit type conversion

Implicit type conversion : This type of conversion of automatically happen by the python interpreter.  This process doesn’t require any user actions.  we will use type function to know the datatype of variable.

Example 1:

int_number = 1
float_number = 1.542

addition = int_number + float_number

print("addition number", addition)


print("final variable datatype", type(addition))

print("data type of integer variable after addition with float ", type(int_number))

Output:

addition number 2.542
final variable datatype <class 'float'>
data type of integer variable after addition with float <class 'int'>

By Understanding above output, If we do adding with integer number and float number , The Output is float number.  The datatype conversion is automatically happen.

Note :

If we are planning addition with sting to integer or float we will get error

Example 2:

int_number = 154
sting_number = "154"

addition = int_number + sting_number

print("addition number", addition)


print("final variable datatype", type(addition))

Output:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

Explicit Type Conversion: 

In this conversion, we will convert datatypes to explicitly by using datatype function like int(), float() etc.

In example 2 we are facing the error, we will solve by using explicit type conversion

int_number = 154
sting_number = int("154")

addition = int_number + sting_number

print("addition number", addition)


print("final variable datatype", type(addition))

print("data type of string variable after addition with integer ", type(sting_number))

Output:

addition number 308
final variable datatype <class ‘int’>
data type of string variable after addition with integer <class ‘int’>

Float Conversion:

float_number = 154.5
sting_number = float("154")

addition = float_number + sting_number

print("addition number", addition)


print("final variable datatype", type(addition))

print("data type of string variable after addition with float number", type(sting_number))

Output:

addition number 308.5
final variable datatype <class ‘float’>
data type of string variable after addition with integer <class ‘float’>

Sting is a set of characters. you can define with single, double and tipple quotes in python. We have inbuilt string functions to make easy process.

Python String Methods:

a= "Hello python"

print(a)

Output: 

Hello python

 

#code

print(a[0])

Output:

H

slicing of string or subset of string

print("\nSlicing of string")
print(a[0:5])

print(a[5:])

print(a[:-4])

Output:

Slicing of string
Hello
python
Hello py

length of string

print("\nlength of string")

print(len(a))

Output:

length of string
12

Capitalize all characters

print(a.upper())

Output:

HELLO PYTHON

Convert all characters to small characters

print(a.lower())

Output:

hello python

#Return a title cased version of the string

print(a.title())

Output:

Hello Python

Return true if there are only whitespace characters in the string

print(a.isspace())

Output: 

False

#Return the number of non-overlapping occurrences of substring

print(a.count('H'))

Output: 1

#Return an encoded version of the string as a bytes object

print(a.encode(encoding="utf-32", errors="strict"))

Output:

b'\xff\xfe\x00\x00H\x00\x00\x00e\x00\x00\x00l\x00\x00\x00l\x00\x00\x00o\x00\x00\x00 \x00\x00\x00p\x00\x00\x00y\x00\x00\x00t\x00\x00\x00h\x00\x00\x00o\x00\x00\x00n\x00\x00\x00'

#Return True if the string ends with the specified suffix, otherwise return False

print(a.endswith('.'))

Output:

False

#Return true if all characters in the string are alphabetical

print(a.isalpha())

Output:

False

#Return a list of the words in the string, using sep as the delimiter string.

print(a.split(' '))

Output:

['Hello', 'python']

#Return True if string starts with the prefix, otherwise return False.

print(a.startswith('H'))

Output: 

True

#Return True if string ends with the prefix, otherwise return False.

print(a.endswith('.'))

Output: 

False

#Return the lowest index in the string where substring sub is found within the slice

it return ‘0’ if he string found and ‘-1’ not found

print(a.find('Hello'))

Output:

0

# the old sub string to new

print(a.replace('Hello','New'))

Output:

New python

#returns index value

print(a.index('python'))

Output:

6

# adding a sub string to main string

print(a.join('Hi '))

Output:

HHello pythoniHello python

Python For loops:

In python we will use for loops for iterative process. We can iterate  strings, lists, tuples, dictionaries with sequence order.

Syntax:

for variable  in sequence

body

Example :

#python for loop example program values = [5,8,9,7,8,9,10] # iterate over the list for val in values: print(val)

Output:

5
8
9
7
8
9

python for loop program to add 2 with list.

values = [5,8,9,7,8,9,10] #addition all list values with 2 # iterate over the list for val in values: print(val+2)

Output:

7
10
11
9
10
11
12

For loop with range :

Range function: It is used to print the sequence numbers, it has start and stop function, By using this we can print specific range numbers.

Example:

print(list(range(10)))

Output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list(range(2,10)))

Output:

[2, 3, 4, 5, 6, 7, 8, 9]
We will range function in for loop to iterate the sequences

Example:

for i in range(10): print(i)

Output:

0
1
2
3
4
5
6
7
8
9
for i in range(2,10):
    print(i*2)

Output:

4
6
8
10
12
14
16
18

For loop with if function :

We can use if condition in for loop with range function. In this below example i am printing even numbers.

for i in range(0,10):
if i % 2 == 0 :
print('Even number :', i)

Output:

Even number : 0
Even number : 2
Even number : 4
Even number : 6
Even number : 8

For loop with if else :

We will use for loop with if else condition. Here i am providing the even and odd number example.  First it iterates the value in then go with if condition if the condition is true it prints the even number . Then it will goes to else block it print odd number.

Example Program:

for i in range(0,10):
if i % 2 == 0 :
print('Even number :', i)
else:
print('Odd Number :', i)

Output:

Even number : 0
Odd Number : 1
Even number : 2
Odd Number : 3
Even number : 4
Odd Number : 5
Even number : 6
Odd Number : 7
Even number : 8
Odd Number : 9

Python lists:

Python lists are powerful data structures, we can define by using []. We can store numbers, strings, float numbers in this list. We can do append,insert, extend, pop, delete methods using lists.

First we need to learn how create a empty list, string list, float list then we can go further.

How to create a empty list:

We can create a list by using [] operator.

List = [] print("Blank list") print(List)

Output: 

Blank list
[]

How to create a list with values:

Here i am create a list with values and printing that list.

List = [1, 2, 4, 4, 3, 3, 3, 6, 5] print("\nList with the use of Numbers: ") print(List)

Output:

List with the use of Numbers:
[1, 2, 4, 4, 3, 3, 3, 6, 5]

How to create a string list:

Here i am create a list with string values, by specifying string values with quotes and commas

#list with strings List = ["Dog", "fish", "Cat"] print("\nList containing with string values: ") print(List)

Output:

List containing with string values:
['Dog', 'fish', 'Cat']

How to create a float list:

List = [1.5,2.5,3.5,7.8,9.5] print("\nList containing with float values: ") print(List)

Output:

List containing with float values:
[1.5, 2.5, 3.5, 7.8, 9.5]

How to Create a Multi Variable List :

#mutli variable list List = [1,2,'cat',3.5,7.8,9.5] print("\nList containing with multitype values: ") print(List)

Output:

List containing with multi-type values:
[1, 2, 'cat', 3.5, 7.8, 9.5]

List Operations with Append, Pop, Delete, Extend etc.

If you want to change list data, we need to use list operations with desired inbuilt functions.

How to Add Elements to the list:

We can add elements to the list by using append(), extend() and insert functions.

List.append() function:

This function used to append a new value to the list.

Syntax: list.append(‘value’)

#program to understand append function in lists.

List =[1,2,3,4] List.append(5) print("\nList after appending value ") print(List)

Output:

List after appending value
[1, 2, 3, 4, 5]

List.append():

This function used to add a new value for specific index to the list.

Syntax: list.insert(position, value)

List =[1,2,3,4] List.insert(2,5) print("\nList appending value at starting of the list ") print(List)

Output:

List appending value at starting of the list 
[1, 2, 5, 3, 4]

How to remove element from the list:

We can remove list elements by using pop()  and remove() functions.

List.pop() function:

This function help to remove the last element from the list.

List =[1,2,3,4] List.pop() print("\nRemoving last element from list") print(List)

Output:

Removing last element from list
[1, 2, 3]

List.remove():

list.remove() function helps to remove specific item from the list.

List =[1,2,3,4] List.remove(2) print("\nRemoving specific element from list") print(List)

Output:

Removing specific element from list
[1, 3, 4]

#Example 2 on Remove list items

List =[1,2,3,4] del List[0] print("\nRemoving starting element from list") print(List)

Output:

Removing starting element from list
[2,3,4]

How to delete all elements from list.

List.clear()

List.clear() function helps to delete all items from the list,

List =[1,2,3,4] List.clear() print("\nClear the list") print(List)

Output:

Clear the list
[]

How to copy one list to another list ?

List.copy() function:

List.copy() function helps to create a new list by copying all elements from the old list.

del List List = [1, 2, 4, 4, 3, 3, 3, 6, 5] List2 = List.copy() print("\nCopy the list 1 to list 2") print(List2)

Output:

Copy the list 1 to list 2
[1, 2, 4, 4, 3, 3, 3, 6, 5]

How to count specific element from the list ?

List.count():

This function helps to count the specific element from the list.

List = [1, 2, 4, 4, 3, 3, 3, 6, 5] Count = List.count(4) print("\nCounting of number of times that values appears in the list") print(Count)

Output:

Counting of number of times that values appears in the list
2

How to Check index of the list element:

List.index() Function:

list.index() function helps to find the element by using index.

List = [1, 2, 4, 4, 3, 3, 3, 6, 5] index = List.index(4) print("\nTo check Index value of value") print(index)

Output:

To check Index value of value
2

How to Reverse the list elements:

List.reverse():

This function helps to reverse a list.

List = [1, 2, 4, 4, 3, 3, 3, 6, 5] List.reverse() print("\n Reverse of the list", List)

Output:

Reverse of the list
[5, 6, 3, 3, 3, 4, 4, 2, 1]

How to Sort List Elements :

List.sort() function:

This function help us to sort a list using ascending order and descending order.

List = [1, 2, 4, 4, 3, 3, 3, 6, 5] print(List) List.sort() print("\n sorting of the list Ascending") print(List) List.sort(reverse=True) print("\n sorting of the list Descending") print(List)

Output:

sorting of the list Ascending
[1, 2, 3, 3, 3, 4, 4, 5, 6]
sorting of the list Descending
[6, 5, 4, 4, 3, 3, 3, 2, 1]
List = [1, 2, 4, 4, 3, 3, 3, 6, 5] print(List) List2= [4,5,6] List.extend(List2) print("\n Extented list") print(List)

Output:

Extented list
[1, 2, 4, 4, 3, 3, 3, 6, 5, 4, 5, 6]

Python List Comprehension:

In this tutorial, you will learn about python List Comprehension with Examples, You can use this List Comprehension for Data Science and machine learning developments.

Def : It’s a process of creating new lists by using old lists with condition statements

Syntax : [ expression for loop if conditionals]

List Comprehension Advantages :

  • Less Code – single line statement.
  • Fast code execution when compare to function and map functions
  • Special uses cases in machine learning and data science projects

#python example programs on list comprehension

#Print odd and even numbers using list comprehensive method list = [1,2,3,4,5,6,7,8,9,10] even_numbers = [i for i in range(10) if(i%2==0) ] print(even_numbers) odd_numbers = [i for i in range(10) if(i%2!=0) ] print(odd_numbers)

Output:

[0, 2, 4, 6, 8]
[1, 3, 5, 7, 9]



#multiplication using list comprehension

multiplication = [5*i for i in list ] print(multiplication)

Output:

[5, 10, 15, 20, 25, 30, 35, 40, 45, 50]

#functions in list comprehension

list = ["Hello Python", '3','Hi','5'] is_digit = [i for i in list if i.isdigit() ] print(is_digit)

Output:

['3', '5']
list = ["Hello Python"] lower = [i.lower() for i in list] print(lower)

Output:

['hello python']

To Uppercase :

list = ["Hello Python"] upper = [i.upper() for i in list] print(upper)

Output:

['HELLO PYTHON']

Python Dictionaries:

It is unordered data structure with key and values. It defined with curley braces. We can create, edit, update and delete the values. We can store integer, float, strings and complex numbers.

How to Create a Empty Dictionary:

Create an empty dictionary with {} braces.

sample={} print(sample)

Output:

{}

How to Create a Dictionary:

We can also create a dictionary with dict function in python with 3 ways. Here are those.

Example 1:

sample=dict({'a':10,'b':20}) print(sample)

Output:

{'a': 10, 'b': 20}

Example 2:

sample=dict(a=10,b=20) print(sample)

Output:

{'a': 10, 'b': 20}

Example 3:

sample=dict([('a',10),('b',20)]) print(sample)

Output:

{'a': 10, 'b': 20}

How to Create of dictionary with Integer numbers:

We can create integer dictionaries by simply passing integer values to it.

int_dic={'a':10,'b':20,'c':30,'d':40} print(int_dic)

Output:

{'a': 10, 'b': 20, 'c': 30, 'd': 40}

How to Create of dictionary with Float numbers:

We can create float  dictionaries by simply passing float values to it.

float_dic={'a':10.5,'b':20.6,'c':30,'d':40} print(float _dic)

Output:

{'a': 10.5, 'b': 20.6, 'c': 30, 'd': 40}

Mixed Datatypes Dictionary:

We can create dictionary with float, integer and strings.

Example Program code:

student={'age':20,'sex':'male','height':6.5} print(student)

Output:

{'age': 20, 'sex': 'male', 'height': 6.5}

Nested dictionary:

We can create a nested dictionary a dictionary with in the dictionary.

nested = {'a':{'age': 20, 'sex': 'male', 'height': 6.5}, 'b': {'age': 21, 'sex': 'male', 'height': 6.5} } print(nested) print(nested['b']['age'])

Output:

{'a': {'age': 20, 'sex': 'male', 'height': 6.5}, 'b': {'age': 21, 'sex': 'male', 'height': 6.5}}

21

How to accessing elements from dictionary:

We can access elements from dictionaries by using key for value.

Example Program code:

student={'age':20,'sex':'male','height':6.5} print(student['sex'])

Output:

Male

How to add elements to dictionary:

We can add easily elements to dictionary by specifying key and value.

Example Program code:

student={'age':20,'sex':'male','height':6.5} print(student) student['salary'] =20000 print(student)

Output:

{'age': 20, 'sex': 'male', 'height': 6.5}

{'age': 20, 'sex': 'male', 'height': 6.5, 'salary': 20000}

How to edit or Update elements to dictionary:

We can edit or update the values same like adding values with specifying key and values.

Example Program code:

student={'age':20,'sex':'male','height':6.5} print(student) student['age'] =21 print(student)

Output:

{'age': 20, 'sex': 'male', 'height': 6.5}

{'age': 21, 'sex': 'male', 'height': 6.5}

How to delete elements from dictionary

We can delete elements from dictionaries using del command or pop .

Example program code:

student={'age':20,'sex':'male','height':6.5} print(student) del student['age'] print(student)

Output:

{'age': 20, 'sex': 'male', 'height': 6.5}

{'sex': 'male', 'height': 6.5}

By using pop function

We can delete dictionary elements by using pop. We can call with below syntax

Syntax:  dictionary. pop(indexvalue)

Example program code:

student={'age':20,'sex':'male','height':6.5} print(student) student.pop('sex') print(student)

Output:

{'age': 20, 'sex': 'male', 'height': 6.5}

{'age': 20, 'height': 6.5}

By using popitem function.

This function automatically removes the last item from the dictionary.

Syntax: Dictionary.popitem()

Example program code:

student={'age':20,'sex':'male','height':6.5} print(student) student.popitem() print(student)

Output:

{'age': 20, 'sex': 'male', 'height': 6.5}

{'age': 20, 'sex': 'male'}

How to check the length of the dictionary:

We can check the length of the dictionary by using len() function.

Example program code:

student={'age':20,'sex':'male','height':6.5} print(len(student))

Output:

3

Python Sets:

In this tutorial, you will learn about python sets with examples.

What is Sets In python:

A set object is an unordered collection of distinct hashable objects. We can use this remove duplicates and check membership. It is mutable, we can add or remove items from set.

By using sets, We can able to do mathematical operations like union, intersection, difference, and symmetric difference

How to Create Sets in python:

You can create sets by placing elements in curly braces. You can add interger, float, strings. But it’s not allow mutable elements like in list, set and dictionary as elements.

Note: We need call with  set object with set()functions, Otherwise it will consider as a dictionary in python.

data = {} print(type(data)) data=set(data) print(type(data)) data={1,2,3,4,4,5,6} print(type(data))

Output:

<class 'dict'>
<class 'set'>
<class 'set'>

Python Sets Program Examples :

#program on integer and string data:

Numeric_data={1,2,3,4,4,5,6} string_data={'ravi','raju','venkat','ravi'} print(set(Numeric_data)) print(set(string_data))

Output:

{1, 2, 3, 4, 5, 6}
{'ravi', 'raju', 'venkat'}

How to change elements in sets:

You can change elements in sets by using add(), update() and remove () functions

#python set program to add, change, remove elements from sets

numeric_data={1,2,3,4,4,5,6} string_data={'ravi','raju','venkat','ravi'} print(set(numeric_data)) print(set(string_data)) print("after Adding data") #adding elements to sets string_data.add('david') print(numeric_data) #updating elements to sets numeric_data.update([7,8]) print("after Update data") print(string_data) #remove elements from sets numeric_data.remove(7) string_data.remove('david') print("after remove data") print(numeric_data) print(string_data)

Output:

{1, 2, 3, 4, 5, 6}
{'ravi', 'raju', 'venkat'}
after Adding  data
{1, 2, 3, 4, 5, 6}
after Update data
{'ravi', 'raju', 'venkat', 'david'}
after remove data
{1, 2, 3, 4, 5, 6, 8}
{'ravi', 'raju', 'venkat'}

Python Inbuilt Functions:

Python has 69 built-in functions to make it easy programming. No need to write code again for these scenarios.

Here are the list of functions

S.no Built-in Functions Function Description
1 __import__() This function is used to import modules
2 abs() This function returns absolute value if it’s integer or float number , if it’s complex number it returns magnitude
3 all() This function returns True if all items in an iterable object are true
4 any() This function returns True if any item in an iterable object is true
5 ascii() The function returns a readable version of any object like Strings, Tuples, Lists, etc and It will replace any non-ascii characters with escape characters
6 bin() This function returns binary value of number
7 bool() This function returns true if the value is there and it returns false if the value is zero or none
8 breakpoint() This function drops you into the debugger
9 bytearray() This function returns an array of objects
10 bytes() This function returns bytes object
11 callable() This function returns if specific object is callable otherwise it will return False
12 chr() This function returns a character from specified character code
13 classmethod() This function converts a method to classmethod
14 compile() This function will compile sourse into code and Code objects can be executed by exec() or eval()
15 complex() This function returns complex value with real and imaginary values
16 delattr() This function deletes the named attribute and provides an object allows it
17 dict() This function returns a dictionary
18 dir() This function returns a specific list of object properties and methods
19 divmod() This function returns a quotient and the remainder values
20 enumerate() This function returns an enumerate object
21 eval() This function evaluates and executes an expression
22 exec() This function execute a specific code
23 filter() This function returns filter items from an iterative object
24 float() This function returns a float value
25 format() This function formats a specific value
26 frozenset() This function returns a frozenset object
27 getattr() This function Returns a value of the specified attribute (property or method)
28 globals() This function Returns a dictionary representing the current global symbol table
29 hasattr() This function takes arguments as objects and strings, Returns True if the specified object has the specified attribute
30 hash() This function returns a hash value for specific object
31 help() This function executes and built-in help system
32 hex() This function returns hexadecimal value
33 id() This function returns the id of an object
34 input() This function will collect the data from user inputs and save it
35 int() This function returns integar value
36 isinstance() This function true if the specified object is an instance of a specified object is true otherwise False
37 issubclass() This function true if the specified class is a subclass of a specified object otherwise False
38 iter() This function returns iterator object
39 len() This fucntion return  length of an object
40 list() This function returns a list
41 locals() This function returns updated dictionary of the current local symbol table
42 map() This function specified iterator with the specified function applied to each item
43 max() This function returns largest value from iterative object
44 memoryview() This function returns a memory view of an object created from the given argument.
45 min() This function returns smallest value from iterative object
46 next() This function returns a next item from iterator
47 object() This function returns a object value
48 oct() This function returns a octal value from number
49 open() This function opens a files and returns a file object
50 ord() This function return Unicode of the specified character from interger
51 pow() This function returns the value of a to the power of b
52 print() This function prints data to standard ouput devices
53 property() This function returns a property attribute
54 range() This function returns a sequence of number starting from 0 and then it incremented by 1
55 repr() This function return a string containing a printable representation of an object
56 reversed() This function returns a reverse iterator. Object must be sequence
57 round() This function returnes rounded value
58 set() This function returns sets object
59 setattr() This function sets an attribute (property/method) of an object
60 slice() This function returns a slice object
61 sorted() This function returns a sorted list
62 staticmethod() This function converts a method to staticmethod()
63 str() This function returns a string object
64 sum() This function sum values from iterative object
65 super() This function return a proxy object that delegates method calls to a parent or sibling class of type
66 tuple() This function returns a tuple object
67 type() This function returns dataype of  value
68 vars() This function returns the __dict__ property of an object
69 zip() This function returns an iterator, from two or more iterators

 

Python for Data Science :

Numpy  Tutorial

Pandas Tutorial

admin

admin

Leave a Reply

Your email address will not be published. Required fields are marked *