Category: Python

What is Python

What is Python?

What is Python : Python is an general-purpose, high-level, interpreted, object-oriented programming language. It is designed for both beginners and experienced one. Python is fast-growing and on-demand language.  It was created by Guido Van Rossum in 1991. He started this language as an hobby project during the Christmas holidays.

Why Python?

It has an easy syntax, easy to learn, dynamic, powerful programming language. Anyone can learn it, it is as easy as an school student can learn it. And as powerful as various intelligent systems can be made using this.

Due to its easy syntax, less code and fast development, it gains so much popularity now a days. It gains popularity in almost all countries in the world. It is not a new language, it was introduced in 1991. But because of its user friendly nature till now, it is the first choice of many programmers.

 

PHP-vs-other-languages-pie-chart
languages-pie-chart

As you can see in the chart above, here are very less developers of python in the industry. As python is an fast-growing language, many companies requires python developers. So job scope is also very high for python.

In summary, i will say you, if you are a fresher then i will recommend you to choose python as your first programming language. Because of its easy syntax, fast development and demand

What we will learn?

In this tutorial, we are going to learn python from scratch. It contains tutorial from basic to advance. If you are beginner, follow all the tutorials in the sequence. But if you are experience one, feel free to skip past tutorials. We also offer you to learn python for web development. Check Django section, it contains all tutorials from basic to advance for web development using python.

User benefits

  • All course is divided into parts
  • Each part contains a new topic
  • Each topic contains code, example and resource
  • You an download code from github

So, it is all about introduction part, stay connected to learn more about it. Thanks!!!

Python History

Python History

Hello everyone, in this lecture we are going to discuss about History of python. You may hear a lot about python, also may you want to learn python. Have you ever arise a question in mind that python comes from where? Who found python and when? Today, we talk about all these things.


Journey of Python

  • The idea to make python started in 1980 by Guido van Rossum at Centrum Wiskunde & Informatica (CWI) in the Netherlands
History
Guido Van Rossum
  • Its implementation begins in 1989 during the Christmas holidays
  • At that time python’s main achievement was capable of exception handling and interfacing with the Amoeba operating system
  • Guido Van Rossum takes it as an hobby project, and he aims to make it very easier and powerful programming language
  • The Python community gives a title to Guido Van Rossum, because of his large impact on the implementation of python
  • The title was “Benevolent Dictator For Life (BDFL) “.

Python Naming

  • Some peoples thinks that the name python comes from the snake named “python”.
  • But it is not like that the name python comes from the famous TV show named “Monty Python’s Flying Circus”
  • It was the Rossum’s favourite TV show
History
Python Naming

Versions of python

  • The Guido Van Rossum continue working on python. Finally the first version Python 0.9.0 was released.
  • It includes various programming features like list, classes, functions and another data types, also support exception handling.
  • Python 1.0 was released in January 1994, which adds feature like lambda, map, filter functions etc.
  • Python 2.0  was release in 16 October, 2000. It also contains various features to functional programming and also introduces a Garbage Collector.
  • Python 3.0 was release in 3 October, 2008. It focuses on large library with no duplication of modules.

Current version of python

The current version of python is  Python 3.7 which was introduce on 27 June, 2018. As after the version 3.0 , there is no longer any implementation in version 2.0. As the version 3.0 contains very powerful and attractive features, so version 2.0 is on less demand.

If we talk about another languages, then the new version of that languages contains updations in previous one. And so the previous version no longer used.

But in python, version 2.0 and version 3.0 runs parallel to each other. There is a lot difference in syntax of python 2.0 and python 3.0. Still some organizes works on python version 2.0. Various IDEs allows us to work parallel on python 2.0 and python 3.0 like Jupyter Notebook.

So not get confuse, python 3.7 is latest version of python but still python 2.0 is also in use. If you want to learn version details in more detail, follow the link below:

GO TO PYTHON OFFICIAL WEBSITE


Python inspired from which language?

Various people thinks that that the syntax of python was inspires from Java, which is not true. The first version of python was released on February 20, 1991 and the first version of Java introduced in January 23, 1996. So this statement is totally incorrect that python inspired from Java.

  • But the actual ancestor of python is ABC programming language, which was developed at CWI (at where Guido Van Rossum worked).
  • The ABC itself was influenced by SETL.
  • ABC has the major influence on design of Python language
  • Rossum overcomes the cons of ABC language in python
  • Python takes feature from various programming languages like C, C++, Modula etc.

So it is all about the history, naming and versions of python. Stay connected to learn more about programming languages. Thanks!!!

Python Features

Features of Python

In this module, we will learn about Python Features. The are various features that makes python special language. Here are some basic features of python:

  1. Easy to read
  2. Easy to learn
  3. Simple syntax
  4. Interpreter based
  5. Support Multiple Programming Paradigms
  6. Free and Open Source
  7. Cross Platform
  8. Extensible
  9. Portable
  10. Scalable
  11. Large Community Support
  12. Library Support
  13. Multi domain language
  14. Interactive
  15. Independent Scripts
  16. Database Support
  17. Automatic garbage collection etc.
Features
Python Features

So above are main features of python, there are various another features. For now, let’s explain all above in detail:

1. Easy to read

One of the most interesting feature of python is, it is very easy to read. You can see the python code in further tutorials, there are English like words. The code is very easy to write and read. For example to print something, we just need to write print() command.


2. Easy to learn

Python is an user friendly language, which is very easy to learn. Beginners can choose python as their first choice. They also can grow in future because of its various domains. Unlike C++ python is as easy as an school student can start programming and learn it.


3. Simple Syntax

This python feature makes it very fast programming language. Python’s syntax is very easy to understand and learn. In programming languages, Most of the students gets confuse in curly-braces and semi-colons. Luckily python has not curly-braces, semi-colons or another typical syntax.


4. Interpreter based

Python is an interpreter based language, to understand this feature you must know the working of the compiler and interpreter. I just let you know the basic idea of interpreter and compiler.

Features
Features

We write code into High Level Language, which is totally understandable by us as a human being. But the computer understands only binary language i.e. the language of 0s and 1s. So here, we need an intermediate system which can understand both languages and makes communication easier. Compiler and Interpreter exactly works same i.e. as an translator.

Compiler takes whole source code at once and create an executable file. After that this executable files get executed. Compiling the whole code at once make difficult to error detection.

Where Interpreter does not create an intermediate executable file. It direct converts source code into byte code and execute code line by line. Because it executes code line by line, it makes easy to detect the error location.

If there is an error in compiler based language, the program will not show any output. Where interpreter just stops execution from the line where error occurs, it does not affect above output.


5. Support Multiple Programming Paradigms

A Programming Paradigm is the way of coding. Python support multiple programming paradigms these are:

a. Functional Programming

b. Procedure Oriented Programming(POP)

c. Object Oriented Programming(OOP)

So here in python, we also can take advantages of functional approach and Object Oriented concepts.


6. Free and Open Source

Python is an totally free to download and use. It is available on official website, so anyone can download it for free. It is also an Open Source Language which means that we can copy code from one machine and paste to another machine, and it will work correctly. Its code is also available on official website. Also we can say that it is machine independent.


7. Cross Platform

Python is an Cross Platform language, which means it can be ru on any platform like Windows, Linux, Macintosh etc.


8. Extensible

Python code is extensible, which means it can be embed(use) into another programming language. You don’t need to include extra libraries, just use code freely.


9. Portable

Due to python’s Open Source and Extensible nature, it becomes an portable language. Portability means that we can write code on one platform, one machine and we also can run it on another machine without need to any change.


10. Scalable

Python is used to create large applications, intelligent systems etc. We can scale the applications, code at any level from simple to complex code.


11. Large Community Support

Python has very much community support. There are number of developers in the world which creates code libraries and share with all on the internet. These libraries are beneficial for both beginners and experienced one.

If you have an error during the programming and you cannot resolve it, just share code on internet, a large community is here to solve the problem.


12. Library Support

As we discuss in above discussion, python has large community, number of developers shares there a lot code on daily basis. So, there are number of inbuilt libraries, that you just need to import and use. These libraries are for simple, as well as complex tasks. So by using python you need not to write extra code, just use libraries.


13. Multi domain language

By choosing python, you have various options.We can develop various types of software using python. Some domains of python are:

a. Python for Web Development

b. Machine Learning & Artificial Intelligence

c. Desktop Applications

d. Ethical Hacking etc.


14. Interactive

Python is an very interactive language. We can direct interact with interpreter using the command prompt. You just need to write your code in command prompt, it will direct interact with interpreter and shows you output.


15. Independent Scripts

Python is used to write scripts that can run on various platforms. These scripts are independent i.e. Cross Platform and Open source. Scripts written in python can run in any language or platform like Android, IOS etc. These scripts are some automated scripts.


16. Database Support

Python has a large Database Support. It can directly interact with any database like MySQL, SQLite etc. These databases can be use to store application’s large data.


17. Automatic Garbage Collector

Every programming language has their own garbage collector, which needs to call to free acquired resources. In simple words, we can say that, every variable or process holds memory and another resources like CPU time. The process of freeing resources from the variables(or entities) which are no longer needed is called garbage collection.

In most of the language, programmer need to call garbage collector. But in python collection unused resources is the headache of the interpreter, not the programmer itself.


So, these are the basic features of the python, which makes python so special. Stay connected to learn more about it. Thanks!!!

Learn Python – Introduction, installation and basics

Introduction to Python

Python is an interpreted High Level programming Language. It was created by Guido Van Rossum and first released in 1991. Key Features of python are:

  • It is Easy-to-use
  • It is an portable. extensible, open-source, high-level programming language
  • It doesn’t contain extra semicolons, curly-braces i.e not a complex syntax
  • It supports dynamic typing, built-in tools and library utilities and Automatic Memory Management

Variety of frameworks are available for the python web-designing. Artificial Intelligence, Machine-learning like Django,  Theano, Torch etc.

Interpreter & Python Installation and Set-Up: 

The interpreter reads other Python programs and commands, and executes them.Python programs are compiled automatically before being scanned into the interpreter.  The fact that this process is hidden makes Python faster than a pure interpreter.

How to call up a Python interpreter will vary a bit depending on your platform, but in a system with a terminal interface, all you need to do is type “python” (without the quotation marks) into your command line. Here we use Anaconda 3 distribution for python, which has already installed python. Open its command prompt and write:

conda install python

If Anaconda has already intalled python , then the massage will be:

     # All requested packages already installed.

If you want to install python directly and python idlethen you can go to  https://www.python.org/getit/

Running Python on command prompt:

Once you’re inside the Python interpreter, type in commands at will. 

python
python

quit() is an built-in function which is used to terminate the python script as shown in example above.

Python Variables

 Python variables are directly created at the time of assigning value, in other words there is no need to declare data-type of variable i.e there is dynamic allocation. It is automatically detected by the python interpreter after the value assignment that whether it is of int type or string, data type is checked by the type() function.

Example:

  >>> c = 10
>>> type(c)
<class 'int'>
There are some rules for variables in python:
  • Must begin with a letter (a – z, A – B) or underscore (_), and contain only alpha-numeric characters and underscore(a-z, A-Z, 0-9)
  • Python variable cannot start with a number
  • These are case Sensitive(a, A are different variables)
  • Can be any (reasonable) length
  • Python reserved keywords like pass, if etc. cannot be used as variable name, because these are for the specific purpose.
Tip: Name of a variable  should make sense like for storing age, name of variable must be Age or age. Do not use lengthy name ex. instead of age_of_candidate it should be age.

 

Comments :

Comments are ignored by compiler or interpreter. They are added only for making code easy to read. Python  comments  starts with #. 

Example: #abc

                   >>> abc
                   Traceback (most recent call last):
                   File "<stdin>", line 1, in <module>
                   NameError: name 'abc' is not defined
                   >>> #abc

                   ...

Data Type:

A data type,  is a classification that specifies which type of data value a variable has. A string, for example, is a data type that is used to classify text and an integer is a data type used to classify whole numbers.  There are following five standard data types in python:

  1. Number
  2. String
  3. List
  4. Tuple
  5. Dictionary

Numbers

 There are three numeric types in python:

  1. int (ex: 12, 05)
  2. float  (ex: 12.05, 3.4)
  3. complex (ex: 4j – real part and imaginary part)

Example:

>> a =10
>>> print(type(a))
<class 'int'>
>>> a = 12.05
>>> print(type(a))
<class 'float'>

>> j = 10
>>> a = 4j
>>> print(type(a))
<class 'complex'>
>>>

Python Strings

 Python  String type are used to store characters. These are surrounded by single quotation mark ‘ string ‘ or double quotation mark ” string “.

Example:

>> a = ‘Hello’

>>b=”there”

String elements can be accessed by square brackets, using index values , this process is called indexing of string. It can be in forward direction and backward direction by giving -ve index . Index values are started with 0  position, i.e in string a =”Hello”, position of ‘H’ is- a[0],’ e’ is a[1] and so on. If we  want to access string from backward direction, then a[-1] = ‘o’.

Forward-Indexing: H = a[0], e = a[1], l = a[2], l = a[3], o = a[4]

Backward-Indexing:  H = a[-5], e = a[-4], l = a[-3], l = a[-2], o = a[-1]

Python String Operators:

  • Basic Operators
  1.    Concatenation (+)  : Example –  “Hello” + “World”
  2.    Replication (*) : Example –  “Hello” * 5
  • Membership Operators
  1. in: “in” operator returns true if a character or the entire substring is present in the specified string, otherwise false.
  2. not in:“not in” operator returns true if a character or entire substring does not exist in the specified string, otherwise false.
  • Relational Operator:

All the comparison (relational) operators i.e., (<,><=,>=,==,!=,<>) are also applicable for     strings. The Strings are compared based on the ASCII value or Unicode(i.e., dictionary Order).

  • Identity Operators:
  1. is:  Evaluates to true if the variables on either side of the operator point to the same object and false otherwise.
  2. is not:  Evaluates to false if the variables on either side of the operator point to the same object and true otherwise.

CODE

(base) C:\Users\MyPc>python
Python 3.6.4 |Anaconda custom (64-bit)| (default, Jan 16 2018, 10:22:32) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 10
>>> print(a)
10
>>> quit()

(base) C:\Users\MyPc>python
Python 3.6.4 |Anaconda custom (64-bit)| (default, Jan 16 2018, 10:22:32) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> gfjaegvchzkdgvdh kagvhag
 File "<stdin>", line 1
 gfjaegvchzkdgvdh kagvhag
 ^
SyntaxError: invalid syntax
>>> quit()

(base) C:\Users\MyPc>python
Python 3.6.4 |Anaconda custom (64-bit)| (default, Jan 16 2018, 10:22:32) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> dckjzbkjzvbkhsbvkjdzagbk
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
NameError: name 'dckjzbkjzvbkhsbvkjdzagbk' is not defined
>>> iuagfiua
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
NameError: name 'iuagfiua' is not defined
>>> quit()

(base) C:\Users\MyPc>a= 10
'a' is not recognized as an internal or external command,
operable program or batch file.

(base) C:\Users\MyPc>python
Python 3.6.4 |Anaconda custom (64-bit)| (default, Jan 16 2018, 10:22:32) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 10
>>> print(a)
10
>>> #abc
...
>>> '''aahfakhajnge'''
'aahfakhajnge'
>>> abc
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
NameError: name 'abc' is not defined
>>>
>>> #abc
...
>>> a = 'abcdef'
>>> print(a)
abcdef
>>> print(a[0])
a
>>> print(a[2])
c
>>> len(a)
6
>>> len(a[-5])
1
>>> print(a[-5])
b
>>> a ="hello"
>>> b ='there'
>>> print(len(a))
5
>>> c = 'fhjgkuyfvjyfkuckurfcygtfycyt'
>>> len(c)
28
>>> print(a+b)
hellothere
>>> a = 10
>>> b =20
>>> print(a+b)
30
>>> a = '10'
>>> b = '20'
>>> print(a+b)
1020
>>> a = "Hello There"
>>> print(a[5])

>> print(a[4])
o
>>> print(a[4]+ a[-1])
oe
>>> 't' in a
False
>>> 'ere' in a
True
>>> 'a' is a
False
>>> "Hello There" is a
False
>>> a = 10
>>> b = 10
>>> a is b
True
>>> a ="Hello"
>>> a = "Hello There"
>>> b ="Hello There"
>>> a is b
False
>>> a = 16
>>> b = 16
>>> a is b
True
>>> a = "Hello"
>>> b = "Hello"
>>> a is b
True
>>> "Hello" is b
True
>>> a = 10
>>> b = 10
>>> a>b
False
>>> a >= b
True
>>> a == b
True
>>> a == b
True
>>> a=b
>>> a==b
True
>>> a != b
False
>>> a = "AMAN"
>>> b ="Hello There"
>>> a = a+b
>>> print(a)
AMANHello There
          >>> quit()

(base) C:\Users\MyPc>


Python tutorial

Python tutorial

Python Tutorial :There are so many computer languages in market including Java , PHP , C , C++ etc . Most of the people thinks that programming is very difficult to do. They even thinks it is impossible to learn programming languages by them . But it is not true , i even say everyone can do programming .

Programming vs real life

Let’s take programming language easy and implement / compare these features with real life . Think like you are an object , your parents are your base classes( inheritance) . Your problem in life , where you have to take one decision are the decision making statements (if-else). And your daily routines are the infinite loop (which never ends / repeat after particular sequence). Think in that way programming becomes easy automatically .

inheritance
inheritance

Python tutorial

Every language has their own speciality and features . But if i have to choose one language among all , then it is Python . It has not only easy syntax but also it is very powerful language . If you are fresher , then you must start with python . It is very user friendly , simple , and powerful languages . As a fresher , if you get started with python , then after experience you can have various choices . Like you can go for website development , data-science , Machine learning etc .

Python is best choice not only for the freshers but also for the experienced one . If you have experience , don’t worry python is very wide , you can go for complex applications like Artificial Intelligence , Machine learning etc , Desktop Applications etc .

Because of python’s features most famous companies use python including Google , Instagram , Dropbox , Facebook , Netflix etc .

Python Programming Example

As python has not very complex syntax , the programming problems are also very easy to solve in python . Here are some common programs which are very easy in python than other languages .

1. Program to swap the values of two variables

x= 10
y=20
print("Before:x=",x,"y=",y)
x,y=y,x #Swap values 
print("After:x=",x,"y=",y)

Output

Python Tutorial
Swapping Values

As you can see in the example above , there is a single line for swapping values of variables .

2. Program to reverse string without using a function .

inp = input("===Enter a string to reverse===\n")
for i in range(1,len(inp)+1):
    print(inp[-i])

Output

Python Tutorial
String Reverse

3. Program to print even and odd numbers

inp = int(input("=== Enter a Range ===\n"))
print("*** EVEN NUMBERS ***")
for i in range(inp+1):
    if i%2 == 0:
        print(i)

print("*** ODD NUMBERS ***")
for i in range(inp+1):
    if i%2:
        print(i)

Output

Python Tutorial
Even and Odd Number

4. Program to Check for a leap Year

inp = int(input("=== Enter Year to Check ===\n"))
if inp%4==0:
    if inp%100 == 0:
        if inp%400 == 0:
            print("It is a leep Year")
        else:
            print("It is Not a leep Year")
    else:
        print("It is a leep Year")
else:
    print("It is not a leep Year")

Output

Python Tutorial
Check for a leap Year

5. Infinite loop

Here is very easy to set a infinite loop in python . Just we have to set while to True . If you want to exit from loop , then you can set break statement .  Let’s define infinite loop with previous code .

while True:  #Infinite Loop
    print("Press 0 to exit")
    inp = int(input("=== Enter Year to Check ===\n"))
    if inp == 0:
        break
    else:
        if inp%4==0:
            if inp%100 == 0:
                if inp%400 == 0:
                    print("It is a leep Year")
                else:
                    print("It is Not a leep Year")
            else:
                print("It is a leep Year")
        else:
            print("It is not a leep Year")

Output

Python Tutorial
Infinite loop

There are various other examples which proves , python is an very easy programming language . If you have any questions or any programming problem then you can comment here . Thanks !!!

Python Input Output (I/O)

Python input output is the way communication between the computer or any other information processing system and user.

What is Input / Output ?

The input and output is the way communication between the computer or any other information processing system and user.  As we know communication is a way of interaction with someone. Computer system takes input, process result and display output. Inputs are the singnals or data received by the computer, and output is signal or data produced by the computer.

Python Input Output
fig: Input Output Process

Python Input Output

Every programming language has their own syntax for taking input and producing output. For example you may see in C, there is cin for input and cout for output. Similarly, python has their own predefined functions for the same.Python uses input() function to take input and print() to display output.

Python input output process process allows us to interact with python interpreter (we can say system ). input() takes input , interpreter reads and process (interprets) that output and produces result. This result can be display to the user using print().

Python Input

Python allows us to take input from the user. It offers  two built in functions for taking input from user, these are:

input()

It is used to take input from the user. It evaluates , whatever expression given by the user. After retrieving input parser parses the source code. In simple words we can say input() takes inputed expression from the user. Here is an example of code.

Syntax

input('String to display/ statement')

Example

python input
fig 1: python input

Output

python input
fig 2 :python input

raw_input()

raw_input() function is used to take input from the user. It takes the input from the standard input in the form of a string and reads the data from a line at once. raw_input function returns a string. Hence in case an expression is to be evaluated, then it has to be type casted to its following data type.  In

Syntax

raw_input('statement')

Example

python input
fig 3: python input

Output

python input
fig 4: python input

As you can see above raw_input() takes data as a string , so it concatenate string rather than adding integers. In case of using input data as other data type we need to type casting into that data-type. Suppose here we need integer type of data, so it should be:

x =int( raw_input("Enter number one"))
y = int(raw_input("Enter number two"))
print(x+y)

It will produce result as fig 2 :python input.

Difference between input() and raw_input()

In python version 2.x , the main difference between  input() and raw_input() is that,  input() first takes the raw_input and then convert it into an expression using eval().

In other hand, raw_input() takes  exactly what user typed and then pass it back to string. There is need to type casting (if other type of data needed).

In python version 3.x there is no raw_input . Python 3.x was renamed raw_input to input() and removed the older input().

The main difference is that input() contains the syntactically correct python statements where raw_input() does not.

Python eval()

Python eval() function converts the string data into python expression. Mostly in is used with input(). It converts the user input string  into  python expression and gives result.

Syntax

eval(?arguments?)

Example

eval('10+10')

Output

20

print()

The print() function prints the given object to the standard output device (screen) or to the text stream file.As you can see in above figures, print() statement displays result to the screen. It can take a variable, string or other object as an argument and displays it. Print statement returns none.

Syntax

  • To print single object
print(?arg1)
  • To print multiple objects
print(?arg1, arg2,..., argn)
  • for concatenate srings
print('str1'+'str2')

String formatting using print()

Python allows us to add variables into string using string formatting. Put set of curly braces( {} ) , where you need to add variable data into string. .format() function is used for the same. We pass data as a parameters to the format method.

Syntax

print("String {} {}...{}".format(var1,var2,..varn))

Example

string formatting
string formatting

Output

string formatting
string formatting

So it is more than enough to understand python input output and string formatting. Thanks.

python installation

python installation : To get start with python , we first need to install python. Python has very easy installation and set-up. In this tutorial we will learn:

  1. Python default installation
  2. Customise python installation
  3. Uninstall Python

About python

Python is an interpreted , high-level programming language. It is created by Guido Van Rossum and first release in 1991.Python is an general purpose language. It is very user-friendly language i.e a beginner who does not know anything about programming can easily understand python in very short time. Because it uses English like words

Also it  is  very powerful programming language. A programmer who has good knowledge of any other language, can easily switch into python.Python supports dynamic allocation of memory. There are various functionalities and features of python which makes it famous.

Python application areas

There are various application areas of python . Because it is very easy and powerful language, it is first choice of most beginners. Some of these application areas are:

  • Web-development
  • Desktop applications
  • Artificial Intelligence
  • Scientific areas
  • Business Applications
  • Games etc.

python installation

To get start with python , we first need to install python. Python has very easy installation and set-up. There are following steps to install python

Step 1 :

Go to browser and visit the link below:

https://www.python.org/downloads/

Step 2 :

Choose operating system , on which you are going to install python , whether Windows , Linux etc. Here i am choosing window as shown  in image below, because i am using window system.

python installation
python installation

Step 3 :

After choosing OS , there are some options. You need to download executable installer according to your system. You need to choose whether you are using 32-bit or 62-bit Windows(OS) as shown in image below:

python installation
python installation
  • If you have 32-bit window OS then choose:
Download Windows x86 executable installer
  • Otherwise if you have 64-bit window OS then choose:
Download Windows x86-64 executable installer

After that it will start to download. Once download complete, open it.

Step 4:

There will be two options as shown in image below:

python installation
fig 1: python installation
  1. Install Know
  2. Customize installation

Install Now

  • If you want quick installation , with default settings. Then you can do so by click on Install Know . It will use it’s by default settings. But do not forget to check the checkbox ( as shown in fig 1 ) :
Add Python 3.7 to PATH
  • After that, python will start to download as shown image below:
python installation
python installation
  • Congratulations!!! Python has installed successfully.
python installation
python installation

Customize installation

  • If you want to customize python installation by your own (add/ remove packages ) you can do so.
  • Click on Customize installation on step 4.
  • There will be the following window:
python installation
python installation
  • As you can see in image above , there are various packages that are going to install. You can un-check specific, you don’t want.
  • After that, there will be an windows with Advance settings , you can customize them by your own. You can also set location , for  python installation. To do so click on browse button.
python installation
python installation
  • Click on Install button , installation will be start, as shown in image below:
python installation
python installation
  • Congratulations!!! python installation successfully!!!
python installation
python installation

run python

If you have installed python on your system. Then you need to check  whether it is installed or not. To check it , go to start menu.

python installation
python installation

You can see there are :

  1. IDLE – GUI (Graphical User Interface)
  2. Command Line Interface

 uninstall python

If you want to uninstall python from your computer , then you can do so by following steps:

1 Go to control panel, then uninstall a program:

Control Panel > Uninstall a Program

2. Choose python , from list of programs.  If you are doing same as me then  Python 3.7.0( 64-bit )

3. Right click on it , then there will be an option Uninstall , click on it.

4. It will start to uninstall as shown image below:

"<yoastmark

5. It will take some time , and uninstall will successful with message below:

"<yoastmark

So it is all about python installation and python un-installation. I hope yoy guys enjoyed the post! Thanks!!!

 

Python Cast

What is type Casting(Python Cast)?

Python Cast: Type casting(also known as type conversion) is the process converting the data-type of one variable to another. As we know that there are number of data-types in every programming language. Some languages allows us to change the data-type of an variable, python is one of them. We can change the type to string, integers, float, list etc.

 Which data types we can cast?

  • String( ex: str())
  • Integer( ex: int())
  • Tuple( ex: tuple())
  • List( ex: list())
  • set( ex:set())

Types of Python Type Conversion

Python allows two types of casting:

  1. Implicit Type Conversion
  2. Explicit Type Conversion

Implicit Type Conversion

In implicit type conversion, python automatically recognizes the type of data. In other words we can say that it is done by the python interpreter itself. It does not include any user involvement. Python is an intelligent language, i.e. as a programmer we need not to declare the type of data in advance. According to the value of variable, python automatically casts it. It is called Implicit data type.

Example

Python Cast
Python Cast

Explanation

  • As you can see in example above, first of all a holds value 10.
  • Python automatically recognize it as an int.
  • It automatically recognizes all data-types including str, int, list etc.
  • After that, added with float value, then it automatically convert it to float.

Explicit Type Conversion

In explicit type conversion, a user can change the one type to another, it is called type casting. To do so, there are various predefined functions in python including str(), int(), float(), set(), tuple(), list()

Syntax

typefun(object/variable)
  • str() converts the variable to type string.
  • int() converts the variable to type integer.
  • float() converts the variable to type integer.
  • set() converts the variable to type set.
  • tuple() converts the variable to type tuple.
  • list() converts the variable to type list.

Example

Python Cast
Python Cast

Explanation

  • As you can see in the example above, first of all a holds value 10 which is integer
  • Furthermore, it is casts to the type string and float
  • Same as variable name,which has type string first, after that it is converted to type set, tuple and list
  • You also may notice that elements changes their position in case of set.
  • It is because set contains unordered set of elements.

Note

In Type Casting loss of data may occur because we forces one object or variable of specific data type to change in another

So, it is all about today’s tutorial. Stay connected to learn more about python. Thanks!!!

Python Control Flow Statements

Python Control Flow Statements

Here Python Control Flow Statements are described , to make concept clear , here is:

  1. Description of each statement
  2. Syntax
  3. Flow Chart
  4. Input Program Screenshot
  5. Output Program Screenshot

There comes situations in real life when we need to make some decisions and based on these decisions, we decide what should we do next. Similar situations arises in programming also where we need to make some decisions and based on these decision we will execute the next block of code. All Programming Languages comes with the control-flow statements – if, if-else , working of the statements remains same i.e. to make decisions, but there is change in syntax which  depend upon language.

Python Control flow statements are decision making statements, which decides the flow of the program, python contains following control low statements:

  1. if statement
  2. if..else statements  
  3. nested if statements
  4. if-elif ladder

If Statement

if statement is the most simple decision making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.

Syntax:

if condition:           

         # Statements to execute if

         # condition is true

 

Flow Chart:

Program:

 

If Statement
If Statement Input

As the condition present in the if statement is True. So, the block inside the if statement will exeute , code at 0 indentation level i.e outside if statement will obviously run  and above program prints output as shown below:

If statement
If statement Output

if-else statement

The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But what if we want to do something else if the condition is false. Here comes the else statement. We can use the else statement with if statement to execute a block of code when the condition is false.


Syntax:

if (condition):

   # Executes this block if

   # condition is true

else:

   # Executes this block if

   # condition is false

 

Flow Chart:

if else statement

Program:

if-else input
if-else input

As in the code above, name is not equal to “aman” as there it is “hello” , so the condition will false, and else part will execute, as shown bwlow:

Output:

if-else output
if-else output

nested-if statement

A nested if is an if statement that is the target of another if statement. Nested if statements means an if statement inside another if statement, it makes the hierarchy of if-statements, if upper condition is true only then inner if-statements gets executed otherwise not.In python we can place an if statement inside another if statement. Let’s understand it by take an example:

Syntax:

if (condition1):

  # Executes when condition1 is true

  if (condition2):

     # Executes when condition2 is true

  # if Block is end here

# if Block is end here

Flow Chart:

Nested if flow-chart
Nested if flow-chart

Program:

 

Nested If Input
Nested If Input

As in above code, there are further two if conditions, inside a single if statement, if top-level condition is true , then conditions inside it are checked one-by-one and program produces output according to the condition status i.e. whether it is true or false, In the code above:

  • name == “aman”, first condition is  true then
  • program flow will go to inside it
  • First it check for condition one age >18 , Here in this case this condition is false because age = 10
  • After that program control will go to second condition age<18 which is true, so it will execute the code (Here print statement) inside it
  • if the top-level condition gets False then its else part will execute which prints “Name is not aman” in that case.

Output:

Nested If Output
Nested If Output

 

if-elif-else ladder

If-elif-else is used in case of multiple condition checking. Here, a user can decide among multiple options. The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed. There can be multiple elif statements in a single program.

Syntax:-

if (condition):

   statement

elif (condition):

   statement

.

.

else:

   statement

 

Flow Chart:

f-elif-else Statement
if-elif-else Statement

Example:

if-elif-else Statement Input
if-elif-else Statement Input

In the above example, variable a is checked in each block, one by one. In case, where it founds the condition True it executes the statements of that particular block, here is number 4th (“Vakue of a is 10.5”)

Output:

if el-if else statement Output
if el-if else statement Output

So these are the Control flow statements, used in python. These are most important part of an language. Making decision is always important part whether it is in real life or programming language.

 

-Content Credit : Miss Harpreet Kaur

for loop in python

for loop in python : for loop in python is different from another languages’s for loop. In python for works as iterator function

What is a loop?

Loop contains the number of actions, that repeats repeatedly along a specified time or sometimes as unspecified time. Basically a loop repeats some actions, number of times. Loop goes at every place, whether in real-life, computer-programming, discrete mathematics, science etc.

There are number of examples of loops around us, Let’s take an example of shopping. Suppose you are going to buy something from a mall and there is a large queue.  You have to wait for get product until queue becomes empty (no person before you), this is a loop. There is a condition that you can not get things till there is a queue of peoples.

 

for loop in python

Loops are used in all the programming languages. In every language, there are various situations, in which we need to repeat block of code over and over again . Python also allows us to use loops. There are following types of loops used in python:

  • for in loop
  • while loop
  • do while loop

In this article, we will discuss about for loop in python, the for loop in python is different from another languages’s for loop. In python for works as iterator function. The for loop is most important and widely used in python It is used to access following types:

  • string
  • list
  • tuple
  • set
  • dictionary
  • range() etc.

Python for loop is used to repeat elements of a sequence. Sequence can be a string, list , tuple or dictionary. Below are the steps  of execution of for loop.

for loop in python
for loop in python

Syntax:

As you know earlier, the syntax of python is very different from another languages. Python separates block of code with colon and indentation(spaces), not curly braces( { } ).

for varName in sequence:                       # Loop Definition
   //some action                               # Body of loop

But the similarity is, python loop also has two parts:

1. Loop definition

It is the first and upper part of a loop from which loop begins. It contains for , loop variable, in keyword, sequence and colon

2. Body of loop

The loop body is important part of an loop. It contains group of statements , for execute till condition is true

Example

for i in "Python":
   print(i)

Output

for loop in python
for loop in python

Steps: How for loop works in python

Step 1

First of all, we assign a loop variable to an for loop which iterate over the given sequence:For example:

In example above, here  “i” is the variable, assigned to loop. And “Python” is a string , for which loop iterates. As we know string is a sequence of characters, each character is an element of string.

Step 2

After assigning loop variable to a sequence, the loop variable iterates the each element of sequence. As shown in output above, at first time loop variable “i” stores first element of string i.e. “P”.

Step 3

As you can see in example above, after storing value to loop variable, the body of loop executed.See in output, it prints “P”.

Step 4

Step 1 to 4 repeats till the last element of sequence. As in example above , as word “python” contains 6 characters. So loop will repeats 6 times. When the last element of sequence reached , the condition becomes false and loop exits.

Looping through an array/list in python

We can loop through in array and tuple with similar way, the loop will continue till the last element of list/tuple.

Example

mylist = ['HTML','CSS','Java Script','Python','Django']
for i in mylist:
    print(i)

  Output

Output: python for loop
Output: python for loop

As you can see in the example above, first of all loop variable stores first element of loop i.e. “HTML” , then second and so on till the last element of list.

Looping through an tuple is same as looping through an list in python.

Looping through an dictionary

We can also use for loop to access keys, values and both of an dictionary. As dictionary contains key and value pairs , there is a little bit logic to access both.

1. iterating to dictionary

mydict = {"name":"Aman","company":"Sachtech Solution Pvt. Ltd.","empId":123}

for i in mydict:
    print(i,'=', mydict[i])

Output

for loop in python
for loop in python

2. iterating to dictionay keys using dictName.keys()

mydict = {"name":"Aman","company":"Sachtech Solution Pvt. Ltd.","empId":123}

for i in mydict.keys():
    print(i)

Output

for loop in python
for loop in python

3. iterating to dictionay values using dictName.values()

 

mydict = {"name":"Aman","company":"Sachtech Solution Pvt. Ltd.","empId":123}

for i in mydict.values():
    print(i)

Output

for loop in python
for loop in python

4. iterating to dictionay elements using dictName.items()

mydict = {"name":"Aman","company":"Sachtech Solution Pvt. Ltd.","empId":123}

for i in mydict.items():
    print(i)

Output

for loop in python
for loop in python

range() function

  • Python allows us to use range() function to take a sequence.
  • range() mostly used to iterate over sequence of numbers
  • By default range starts from 0 and increments values by 1
  • range() function takes 3 parameters , minimum value, maximum value, increment size
  • Sequence starts from the minimum value i.e first parameter , and ends at maximum value.
  • By default increment size is 1, we can set our own , by passing third parameter

Syntax

range(min-Value, max-Value , increment size)

Example

## Default range() with increment 1

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

## with custom incrementn i.e 2

print("With increment size 2")
for variable in range(10,20,2):
    print(variable)

Output

for loop in python
for loop in python

Nested for loop

We can use for loop inside for loop or inside while loop. Nested loops enhance the power of any language and accessibility.

Example

print("Star pattern \n")
for i in range(1,6):
    for j in range(1,i+1):
        print('*', end='')
    print(' ')

print(" \n print number of rows \n")
for i in range(1,6):
    for j in range(1,i+1):
        print(i, end='')
    print(' ')

print("  \n print number of columns \n")
for i in range(1,6):
    for j in range(1,i+1):
        print(j, end='')
    print(' ')

Output

python nested for loop
python nested for loop

So, that’s all about for loop in python , i hope you guys understand working of for loop in python. Thanks!!!

Python Function

Python Function

Functions are the key part of most of the  programming languages. Function  is a  group of statements , used to perform a specific task.

In this article we will learn:

  1. What is function?
  2. Advantages of functions
  3. Python function (definition , calling )
  4. Documentation string in function
  5. Return vs print
  6. Function parameters
  7. Parameters vs Arguments
  8. Parameter with default values
  9. Anonymous function (lambda)
  10. Filter function

What is Function?

Functions are the key part of most of the  programming languages. Function  is a  group of statements , used to perform a specific task. It is used to utilize code at more than one place.  We can divide huge problem into small parts called functions or modules.  Suppose in program, there are lines of code which need to repeat more than one time, in that case instead of copy these lines again and again, we can create a function for that and can use it whenever needed (by calling function). In other words we can say function is a block of reusable code , used to perform a specific task.

 

Advantages of Functions:

  1. Clean code: Functions improves the clarity of the code we can say results  a  well structured code.
  2. Decomposition :  It breaks the complex problem into smaller parts (functions, also called modules), which is easy to  understand and read.
  3. Speed and Time:  As we need not to write code again and again so it improves the speed and saves time.
  4. Reusability: We can use a function more than one time in more than one programs by calling it.
  5. Data hiding:  By  using function we can hide extra information.
  6. Reduce Duplicate Code

Python Function:

In python, a function is defined with def keyword. A normal function has three main parts these are:

  1. Function definiation
  2. Body of function
  3. Function calling

In python function is defined using def  keyword, followed by the name of the function , parenthesis and colon(:). The body of the function starts with the indentation (space). Unlike other languages, python does not use curly braces , semicolons etc. Function blocks are separated  by indentation.

A function is a block of code which only runs when it is called.

Syntax:

function
python function

Types of functions in python:

There are two types of functions in python –

  • Built-in
  • User-defined

Built-in functions are the part of the python language example :- len() , print() etc.

User-defined functions are created by the user itself by using def keyword.

 Doc-string in python functions:

Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods. Doc-string is used like a comment to document a specific segment of code.

The docstrings are declared using  “””triple double quotes”””  just below the class, method or function declaration

The docstrings can be accessed using the __doc__ method of the function.

Function Example:

Here is an python function with a documentation string:

function with docstring
function with docstring

Output:

 

function with docstring
function with docstring

Return() vs Print()

Every function returns a value or result. If return is not specified in function than it will return none. It is the last statement of any function, which means end of block. If there is not return statement then function will execute till end of code(i.e till last statement). This value can further use in other operations, or functions. This return value may not visible to the user, but computer can use it in further operations.

Print()  just shows the human user a string representing what is going on inside the computer. The computer cannot make use of that printing. It will not in any way affect a function. Print() is simply there for the human user’s benefit, useful for understanding how a program works.

Example:

 

print vs return
print vs return

Output:

Output: return vs print
Output: return vs print

Function Parameters:

We can pass additional information to a function by using parameters. Parameters are specified after the function name, inside the parentheses.We can pass number of parameters in function, separating by comma. We can also pass parameters with a default value in a function.

Example:

function with parameters
function with parameters

Output:

output: function
output: function

Parameters vs Arguments:

Most people thinks there is no difference between parameters and arguments, but there is. A parameter is a variable in a function definition. Arguments are the data members that we pass in function parameters at the time of function calling.. In other words we can say, parameter is a variable in the declaration of function. Argument is the actual value of this variable that gets passed to function.

parametes vs arguments

Function with default parameters:

We can pass default parameter values with a function.  During calling a function if argument values  passed than function will use these values otherwise it will use default values.

Example:

default parameter values
default parameter values

Output:

output: default parameters
output: default parameters

Anonymous function:

In python, anonymous function is a function, that defined without a name. Normally in python we use def keyword to declare a function. Where anonymous function is defined with the lambda keyword, that is why it is also called lambda functions.Lambda expression has no name that is why it is called anonymous function.

Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions. It basically breakdowns the function.

An anonymous function cannot be a direct call to print because lambda requires an expression

Syntax:

lambda arguments: expression

Example:

Anonymous function
Anonymous function

Output:

output: Anonymous function
output: Anonymous function

Filter function:

In python filter function takes two arguments,  function and sequence. It returns those items of the sequence for which the function is true.

Syntax:

filter(function, sequence)

Example:

In the example below, we are using lambda expression (function) as first parameter of filter function, you can take any normal function also.

filter function
filter function

In above example filter() has two parameters –

1st Parameter – seq (List of numbers)

2nd Parameter – lambda function

In line 4 , we converts the  output into list which is list of even numbers as shown below:

Output:

Output: filter function
Output: filter function

So it is all about the python function, Thanks

 

 

 

 

*args

*args and **kwargs in python

*args allows us to pass a variable number of arguments to a function . it uses asterisk( * ) to iterate number of arguments and then a variable name .There are various type of functional arguments in python including:

  1. Default Arguments
  2. Keyword arguments
  3. Positional Arguments
  4. Arbitrary Arguments

Why *args and **kwargs

Basically, we use *args and **kwargs when we have to pass variable number of arguments in function . In simple words we can say , it allows us to pass any number of arguments during function call . We also use them when we don’t know exact number of parameters which we need to pass . It supports dynamic time argument declaration / passing . args and kwargs are just only naming conventions , you can use any name instead .

For Example , if you want a function to add numbers. In that case it is depend upon user , how many number of arguments he need to pass . In that case we  can use *args or *kwargs .

*args

It is an type of Arbitrary arguments , it allows us to pass variable number of arguments .It is used for positional / non-keyword arguments . Here is the syntax of function with variable number of arguments :

def function_name( *args ):
    pass

Example 1 – Accessing *args

def fun(a, *args):
    print(a)
    for i in args:  #Iterating to arguments
        print("Arbitary Argument",i)

fun(10,"Hello",20,30,"There")

Output

args
args

Explanation

  • As you can see in the example above, here is a function named fun() .
  • This fun() accepts any number of arguments .
  • We use single asterisk(*) arguments for non-keyword arguments .
  • In example above , it takes first argument as an positional argument which refers to ‘a’ parameter .

Example 2 – Addition of variable number of arguments

def add(*args):
    sum=0
    for i in args:
        sum += i
    print("Sum=",sum)

add(10,80,50)

Output

addition of args
addition of args

**kwargs

We can use **kwargs for keyword arguments . Keyword arguments are those which comes in key and value pairs like an dictionary . We can access these arguments in the same way as access dictionary’s keys and values . Here is an example of accessing kwargs .

Syntax

def function_name(**kwargs):
    pass

Example

def fun(**kwargs):
    print(kwargs)
    for i in kwargs:
        print(i , kwargs[i])
fun(name="Aman",Course="Python",Id=1)

Output

kwargs
kwargs

Explanation

  • As shown in example above , **kwargs  are used for keyword arguments .
  • Keywords arguments are the values followed by key and equals to sign .
  • We can access these keys and values as same way as accessing dictionary items .

Example – Addition of variable number of keyword arguments

def fun(**kwargs):
    sum = 0
    for i in kwargs:
        sum += kwargs[i]
    print("Sum = ",sum)
fun(a=10,b=100,c=30,x=40)

Output

kwargs
kwargs

So it is all about *args and **kwargs , i hope you guys get it . Thanks!!!

Please wait...

Subscribe to our newsletter

Want to be notified when our article is published? Enter your email address and name below to be the first to know.