Search

Python Programming Filter

What is Python, it's basics and getting started with Python

Learning something new is always interesting and exciting but how to learn makes it challenging. It is believed that learning how to learn is the most critical task while learning a new programming language. A proper strategy to learn makes the journey easier and smooth. Let us look into such essential learning strategies which will help you learn the basics of Python and guide you through the journey of becoming a programmer.Code Regularly: It is important for a beginner to practice Python coding on a regular basis which will develop a muscle memory. At first it might seem to be difficult but a regular practice of half an hour will make your basics stronger.Use Pen and Paper: Many learners have this question in mind, whether they should write codes using a pen and paper or not. It is recommended to write codes or take notes by hand as it is beneficial for long-term retention as you get a firm hold over writing flawless codes. Also, in a lot of interviews, you are asked to write codes on a white board.Program as a Pair: With a friend or another learner completing a task together is called pair programming. It is a technique where two developers work at a single workstation. One of the developers should be the “driver” and the other should be the “navigator”. The “driver” writes the code, while the “navigator” helps guide the problem solving and reviews the code as it is written. Both the developers should switch between the roles.Build new things: There are a lot of short exercises for beginners which will make you confident with Python. You should have good knowledge about basic data structures (strings, lists, dictionaries, sets), object-oriented programming, and writing classes. Here, let us discuss about what Python is all about, how to get started with Python and learn about the basics of Python.What is Python?Python is an interpreted, interactive, object-oriented and multi-purpose programming language created by Guido Van Rossum in the late 1980s. It is a programming language— a language which people and computers both can understand. It is powerful and has an easy-to-use syntax, making it perfect for beginners.Python is a flexible language which has the ability to write simple programs and also create large complex programming solutions. It is used extensively for web and internet developments, for mathematical and scientific computations of data and also in the field of game and graphics development. Some of the popular websites that use Python are Youtube, Instagram, Dropbox, Pinterest etc. Join the certification course on Python Programming to learn more about Python and its capabilities.Why Choose Python?Whether you’re a beginner to programming or an experienced programmer designing a complex application, Python is a great choice because of its easily understandable nature and vast capabilities. Some of the features of Python that make it irresistible to users:Popularity: Python is considered as the 4th most popular and fastest growing programming language according to the Stack Overflow Developer Survey 2019. Python is used by the world’s most renowned Software Companies like Google, YouTube, Instagram, Netflix, Spotify, Quora and much more.Interpretation: Python is an interpreted language which means the programs are passed straight to the interpreter which executes them directly; unlike compilers where the source code is converted to machine code before running.OpenSource: Python is a free language developed under OSI-approved open-source license which makes it free to use and distribute even for commercial purposes.Portability: Python code is portable, which means the code written in one platform will work in any other platform, having the Python interpreter installed.Simplicity: Python’s coding style is very simple and clean which makes it easy to read and learn. It uses less keywords compared to other languages like C++ or Java. Developers tend to use it all the time because of its neat and organized code structure.How to Get Python?Python is an open-source software that comes pre-installed in Mac and works on most distributions of Linux and other platforms. However, you might need to download the latest version to get the most out of it.Choosing Python Presently, there are two major versions of Python - 2.x and 3.x. However, at an early stage, you can use either of the two because there are very few differences between them. Also once you have learned one, the other one won’t be difficult to learn.In simple terms, if you’re starting to learn Python, the latest version 3.7.x would be more suitable since it comes with extra features with a number of bug fixes. On the other hand, you can use the version 2.7.x when you need support from third-party libraries to perform your task.Installing PythonYou can download the specific version of Python that suits your OS and processor (32-bit or 64-bit) from the Python Software Foundation (PSF).Installation pertaining to OS requirement:Windows: In any Windows platform, you can directly download Python software from the PSF.Linux: You can download the latest version of Python on Linux in the same manner. However, you can also use a package manner, if needed.Mac: For Mac systems, download the software from PSF and then install it. Moreover, it is suggested to use a package manager like Homebrew for installing and managing different versions of Python.Python ShellAfter you have successfully installed Python in your system, you can check whether it is installed or not using the Python Interactive Shell:Windows: Open the terminal and type python for Python 2.7 or py -3 for Python 3.Linux: Open your terminal and simply run python.Mac: Depending on the version of Python you’ve installed, open your terminal and run python or python3.The command prompt or the terminal will look somewhat like this:Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:21) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>>You can use the exit() to leave the Python shell or you can also use CTRL + D and then press the ENTER key to terminate the command prompt.What are the Basics of Python?Python is a very beautiful language and feels very natural to work with. It consists of a number of coding basics. Let us first start by running the universal Hello World program.The Hello World ProgramIf you want to display a line in the terminal, you can do so by using the print statement:>>> print("HELLO WORLD!")The output will be displayed as follows:HELLO WORLD!VariablesVariables are defined as containers or memory locations for storing data. The syntax of declaring a variable is variable_name = variable_value. However, it is recommended to use variables names like num1, my_int or mystring other than simple variables like x or y.Sensible names gives a clear indication of the type of variable and it is also useful for others to understand your code clearly. Thinking of others while writing your program will improve your coding skills.Built-in Data TypesPython comprises of many built-in data types starting from numbers, strings, lists, tuples and dictionaries.NumbersPython supports many types of numbers like integers (1, 2, 55, 599, -99), floating points (1.0, 5.55,  661.1, -99.9),  Booleans (True or False) or complex numbers. We can perform addition and subtraction with numbers just like normal addition and subtraction we learnt in our school:>>> 1 + 5   # Addition 6 >>> num1 = 5 >>> num2 = 5.01 >>> num3 = num1 + num2 >>> 10 - 5   # Subtraction 5We can also compare numbers that will result in a boolean value:>>> 1 < 3 True >>> 4 > 5 FalsePython consists of a number of built-in functions that you can use to handle numbers:>>> float(13) 13.0A float() function takes an integer and returns a floating point number.Other than functions, Python also has a number of data-type methods connected to each type of number. float.is_integer() is a data-type method which checks whether a floating point number is finite or not:>>> (10.1).is_integer() False >>> (5.0).is_integer() True StringsA String is a list of characters in an organized manner. A character can be a number or letter or even a backslash. In simple words, they are lines enclosed in single or double quotes:>>> string1 = "hello" >>> string 'hello' >>> string2 = 'hey' >>> string2 "hey"In Python, we can combine strings in a series without any gaps. This is called Concatenation:>>> "Python is" + "easy" 'Python is easy'We can also manipulate strings using functions:>>> len('Python') 6Here, len() is a function that takes a string as an input and returns the size of the string.Data-type methods also exist for handling strings. string.capitalize() takes an input string and returns by capitalizing the first string:>>> lower_case_string = 'python' >>> lower_case_string.capitalize() 'Python' >>> ('the Avengers').capitalize() 'The Avengers' ListsA list is an ordered sequence of elements in Python. Each element in a list is known as an item. They are similar to array in C or C++.Lists may consist of any data type like numbers or strings mixed together, or other lists or they may be empty too. The syntax is usual:>>> create_a_list = [] >>> list_of_numbers = [1, 5, 10, 1000] >>> list_of_numbers [1, 5, 10, 1000] >>> list = ["ironman", "thor", "hulk"] >>> list ['ironman', 'thor', 'hulk'] >>> mixed_list = ["Python", [1, 2, 3], True] >>> mixed_list ['Python', [1, 2, 3], True]Elements of lists can be accessed either from the start or the end. Also, you can create a new list just by accessing the elements:>>> list_of_numbers = [1, 5, 10, 1000] >>> new_list = list_of_numbers[0:2] >>> new_list [1, 5]Concatenation of lists using operators:>>> marvel = ["ironman", "thor", "hulk"] >>> dc = ["superman", "batman", "flash"] >>> multiverse = marvel + dc >>> multiverse [‘ironman’, ‘thor’, ‘hulk’, ‘superman’, ‘batman’, ‘flash’]The function of lists works in the same manner as of strings:>>> list_of_numbers = [1, 5, 10, 1000] >>> len(list_of_numbers) 4len() returns the size of the list.Data-type methods like list.sort() and list.append() are used to sort  and append lists:#append >>> stationary = ["inkpen", "pencil", "eraser"] >>> stationary.append("sharpener") >>> fruits ['inkpen', 'pencil', 'eraser', 'sharpener']#sort>>> stationary.sort()>>> stationary[ 'eraser', 'inkpen', 'pencil', 'sharpener']TuplesTuples are sequence of Python objects that cannot be changed after creation. They are similar to lists, the only difference being that lists are mutable.An example of a tuple:my_tuple = ("Alex", "Blanc", 27, "Technical Blogger")You can concatenate two tuples using operators just like lists:>>> tuple1 = (11, 29) >>> tuple2 = (30, 90) >>> tuple3 = tuple1 + tuple1 >>> tuple3 (11, 29, 30, 90)You can convert a tuple into a list by using the function list():>>> tuple1 = (100, 500)>>> list(tuple1)[100, 500]Since tuples cannot be changed after it is created, most of the data-type methods like sort() or append() or reverse() will not work on tuples.DictionaryA dictionary in Python is an unordered collection of associative arrays (or objects).An example of a dictionary of phone numbers:>>> phonebook = {} >>> phonebook["Alex"] = 9038478766 >>> phonebook["Bob"] = 9098379264 >>> phonebook["Charlie"] = 9017652781ConditionsA conditional statement is a statement that handles the flow of execution depending on some condition.Statements can be compared or evaluated in Python using boolean expressions as follows:>>> x = 5 >>> print(x == 5) # prints True >>> print(x == 2) # prints FalseYou can also use the if-else statements to check if a statement is true or not:>>>if 2 > 3:   print("2 is greater than 3")   else:   print("2 is not greater than 3")LoopsYou can use loops when you want to repeat a block of code in a fixed number of time. You can iterate in two different ways, the first is by using the while loop:>>> num = 1 >>> while num <= 5:     print(num)     num = num + 1While the statement is true, the loop will iterate and the code will be executed. It will print the number from 1 to 5.Another way of implementing a loop is using the for statement:>>> for num in range(1, 10):     print(num) Here, the range starts from 1 and goes until 10. The loop iterates 10 times over the statement.FunctionsFunctions in Python are a block of organized code which is useful in performing a single action. Syntax of defining a function is def function_name.An example of a function is:>>> def my_first_function(): print("HELLO WORLD!")You can also return a value to the caller in a function using the return statement:>>> def multiply_by_2(a): return a * 2Classes and ObjectsAn object in Python is a collection of variables and methods. A class is a blueprint for the object.For example, we can consider a prototype of a house as the class. It consists of all the details of the floors, walls, doors, windows etc. We can build the house on the basis of the details. So, house becomes the object. Objects are instances of a class.You can define a class in Python using the keyword class as follows: >>> class My_First_Class:     my_variable = "blah"You can create an object in Python which can be used to access different attributes of a class. This process of creating new object instances is called instantiation.An example to illustrate that:class My_First_Class: def func(self): print('Hello') ob = My_First_Class() #creating a class objectModules and PackagesA module is a single file (or files) that are imported under one import and then used. In simple words, any Python file is a module. On the other hand, packages are simple directories consisting of multiple modules and packages themselves.Python consists of a number of packages and modules to increase the extent of the language. Some of the useful built-in Python modules are:math: This module gives access to mathematical functions from the standard library of C.random: This module is a pseudo-random number generator.datetime: This module comprises of classes by which you can manipulate dates and times.Pip is the standard package manager which is used to handle Python’s third party packages and modules in an efficient manner. It allows you to install the packages that are not part of the Python Standard Library. You can download Pip from pypi.org.CommentsComments can be in the form of module-level docstrings or inline explanations that are used to describe your code in a clear manner so that developers can understand. It starts with a hash (#) character and can extend to the end of the line.An example of a simple comment:# This is a commentAn example of an inline comment:variable = "Hello World"  # This is an inline commentErrors and Exceptions Python consists of two types of errors:Syntax errors.Exceptions or errors during execution.Syntax ErrorsSyntax errors occur when the Python parser is unable to understand a line of code. Most syntax errors occur because of incorrect indentation or arguments.An example to illustrate such:>>> if 2 < 5   File "<stdin>", line 1      if 2 < 5              ^ SyntaxError: invalid syntaxHere, the if statement is missing a colon(:)at the end of the statement which results into a syntax error.ExceptionsErrors that occur during execution are known as exceptions. There are a number of built-in exceptions in Python.An example of an exception:>>> prices = { 'Pen' : 10, 'Pencil' : 5, 'Notebook' : 25} >>> prices['Eraser'] Traceback (most recent call last):   File "<pyshell#1>", line 1, in <module>     prices['Eraser'] KeyError: 'Eraser'Here, dictionary prices is declared with the prices of three items. The KeyError is raised when the item ‘Eraser’ is being accessed which is not present in prices. Learn more about exceptions in our blog- Python KeyError Exceptions and How to Handle Them.Semantic ErrorsA semantic error, also known as logic error, is an error that occurs because of an incorrect logic. They are much more difficult to catch as compared to syntax errors.These type of errors are complex in nature and generate incorrect or no output. The most common example of a semantic error is an infinite loop. Programmers in their early stage of learning encounter an infinite loop at least once.What are the Different ways of Coding in Python?When you’re in the process of learning a new programming language, you might want things to be simple and your path of becoming a good programmer to be smooth and clear. The first approach to this will be choosing an efficient way of running and executing code in Python.There are mainly three primary approaches to coding in Python— the shell, IDLE and the code editor.The ShellPython provides the Python Shell, which is useful for simple, one-line statements. It waits for the input commands from the user and returns the result of the execution. It is the least powerful among the three.You can open shell in your system and run the following command:>>> 11 + 9 20 Here, the Python Shell evaluated the statement 11 + 9 , performed the addition operation and displayed the result 20.Another example of coding in shell:>>> import thisWhen you execute this statement, you can see the Zen of Python. It is a collection of 19 principles which acts as a guide to write idiomatic Python code.However, the shell has a drawback. The code written in a Python Shell is not persistent which means the code cannot be reused. IDLEIDLE stands for Integrated Development and Learning Environment. It is similar to the shell and contains both the Shell window and the Editor Window. You can create and save Python code because the IDLE allows code reusability. However, it still stands second in the rank powerfulness. Code EditorA code editor is the most powerful among all the three. It is a text-editor program that is useful in editing source codes of computer programs. A code editor can be a single application or act as an Integrated Development Environment or IDE.There are a lot of code editors available in the market. Choosing a code-editor for your task might be a time-consuming work. However, you can take into consideration some factors while choosing a code editor like easy to use, line numbering, auto-indentation, highlighting of syntax and availability of adding extra features.One of the most powerful and popular cross-platform code editor is the Sublime Text.  Other code editors might include gedit,  which is a bit simpler than Sublime. You can also use Notepad++, however it is only for Windows.ConclusionLet’s sum up what we have learnt so far in this article:What is Python programming and what is the need.How to install and run Python.What are the primitives of the Python programming language.What are the ways of Python coding.Though you have learned the basics of the Python Programming Language, here are some tricks and tricks for you remember while coding in Python—Good coding is happy coding. Good code depends on the way you write a code. The key to a good code is to maintain a proper style. You can go through the blog on How To Write Beautiful Python Code With PEP 8 which focuses on enhancing the readability and consistency of code.The logic is the most crucial part when you’re writing a program. If you have a clear understanding of the concepts, you can easily shape your code into a logical program. And the most effective way to do that is to logically break your problem into different parts and then solve it one by one.The best way of learning how to code is by building a project-driven learning approach. There are a lot of free resources, online courses, books and tutorials available. You can refer to the official Python documents - Python 2.7 or Python 3 for more information.You can also join the Python certification course offered by KnowledgeHut.And last but not the least, always keep brushing up the concepts. As a beginner, you might face difficulties in every step, but always try and resolve your issues on your own. Test your skills and take up new challenges everyday.

What is Python, it's basics and getting started with Python

9962
What is Python, it's basics and getting started with Python

Learning something new is always interesting and exciting but how to learn makes it challenging. It is believed that learning how to learn is the most critical task while learning a new programming language. A proper strategy to learn makes the journey easier and smooth. Let us look into such essential learning strategies which will help you learn the basics of Python and guide you through the journey of becoming a programmer.

  • Code Regularly: It is important for a beginner to practice Python coding on a regular basis which will develop a muscle memory. At first it might seem to be difficult but a regular practice of half an hour will make your basics stronger.
  • Use Pen and Paper: Many learners have this question in mind, whether they should write codes using a pen and paper or not. It is recommended to write codes or take notes by hand as it is beneficial for long-term retention as you get a firm hold over writing flawless codes. Also, in a lot of interviews, you are asked to write codes on a white board.
  • Program as a Pair: With a friend or another learner completing a task together is called pair programming. It is a technique where two developers work at a single workstation. One of the developers should be the “driver” and the other should be the “navigator”. The “driver” writes the code, while the “navigator” helps guide the problem solving and reviews the code as it is written. Both the developers should switch between the roles.
  • Build new things: There are a lot of short exercises for beginners which will make you confident with Python. You should have good knowledge about basic data structures (strings, lists, dictionaries, sets), object-oriented programming, and writing classes. Here, let us discuss about what Python is all about, how to get started with Python and learn about the basics of Python.

What is Python?

What is Python? Python is an interactive, object-oriented & multi purpose programming language which is easy to understand & use.

Python is an interpreted, interactive, object-oriented and multi-purpose programming language created by Guido Van Rossum in the late 1980s. It is a programming language— a language which people and computers both can understand. It is powerful and has an easy-to-use syntax, making it perfect for beginners.

Python is a flexible language which has the ability to write simple programs and also create large complex programming solutions. It is used extensively for web and internet developments, for mathematical and scientific computations of data and also in the field of game and graphics development. Some of the popular websites that use Python are Youtube, Instagram, Dropbox, Pinterest etc. Join the certification course on Python Programming to learn more about Python and its capabilities.

Why Choose Python?

Why to Choose Python? Popularity, Interpretation, OpenSource, Portability and Simplicity.

Whether you’re a beginner to programming or an experienced programmer designing a complex application, Python is a great choice because of its easily understandable nature and vast capabilities. 

Some of the features of Python that make it irresistible to users:

  • Popularity: Python is considered as the 4th most popular and fastest growing programming language according to the Stack Overflow Developer Survey 2019. Python is used by the world’s most renowned Software Companies like Google, YouTube, Instagram, Netflix, Spotify, Quora and much more.
  • Interpretation: Python is an interpreted language which means the programs are passed straight to the interpreter which executes them directly; unlike compilers where the source code is converted to machine code before running.
  • OpenSource: Python is a free language developed under OSI-approved open-source license which makes it free to use and distribute even for commercial purposes.
  • Portability: Python code is portable, which means the code written in one platform will work in any other platform, having the Python interpreter installed.
  • Simplicity: Python’s coding style is very simple and clean which makes it easy to read and learn. It uses less keywords compared to other languages like C++ or Java. Developers tend to use it all the time because of its neat and organized code structure.

How to Get Python?

Python is an open-source software that comes pre-installed in Mac and works on most distributions of Linux and other platforms. However, you might need to download the latest version to get the most out of it.

Choosing Python 

Presently, there are two major versions of Python - 2.x and 3.x. However, at an early stage, you can use either of the two because there are very few differences between them. Also once you have learned one, the other one won’t be difficult to learn.

In simple terms, if you’re starting to learn Python, the latest version 3.7.x would be more suitable since it comes with extra features with a number of bug fixes. On the other hand, you can use the version 2.7.x when you need support from third-party libraries to perform your task.

Installing Python

You can download the specific version of Python that suits your OS and processor (32-bit or 64-bit) from the Python Software Foundation (PSF).

Installation pertaining to OS requirement:

  • Windows: In any Windows platform, you can directly download Python software from the PSF.
  • Linux: You can download the latest version of Python on Linux in the same manner. However, you can also use a package manner, if needed.
  • Mac: For Mac systems, download the software from PSF and then install it. Moreover, it is suggested to use a package manager like Homebrew for installing and managing different versions of Python.

Python Shell

After you have successfully installed Python in your system, you can check whether it is installed or not using the Python Interactive Shell:

  • Windows: Open the terminal and type python for Python 2.7 or py -3 for Python 3.
  • Linux: Open your terminal and simply run python.
  • Mac: Depending on the version of Python you’ve installed, open your terminal and run python or python3.

The command prompt or the terminal will look somewhat like this:

Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:21)
[MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

You can use the exit() to leave the Python shell or you can also use CTRL + D and then press the ENTER key to terminate the command prompt.

What are the Basics of Python?

Python is a very beautiful language and feels very natural to work with. It consists of a number of coding basics. Let us first start by running the universal Hello World program.

The Hello World Program

If you want to display a line in the terminal, you can do so by using the print statement:

>>> print("HELLO WORLD!")

The output will be displayed as follows:
HELLO WORLD!

Variables

Variables are defined as containers or memory locations for storing data. The syntax of declaring a variable is variable_name = variable_value. However, it is recommended to use variables names like num1, my_int or mystring other than simple variables like x or y.

Sensible names gives a clear indication of the type of variable and it is also useful for others to understand your code clearly. Thinking of others while writing your program will improve your coding skills.

Built-in Data Types

Python comprises of many built-in data types starting from numbers, strings, lists, tuples and dictionaries.

Numbers

Python supports many types of numbers like integers (1, 2, 55, 599, -99), floating points (1.0, 5.55,  661.1, -99.9),  Booleans (True or False) or complex numbers. We can perform addition and subtraction with numbers just like normal addition and subtraction we learnt in our school:

>>> 1 + 5   # Addition
6
>>> num1 = 5
>>> num2 = 5.01
>>> num3 = num1 + num2
>>> 10 - 5   # Subtraction
5

We can also compare numbers that will result in a boolean value:

>>> 1 < 3
True
>>> 4 > 5
False

Python consists of a number of built-in functions that you can use to handle numbers:

>>> float(13)
13.0

A float() function takes an integer and returns a floating point number.

Other than functions, Python also has a number of data-type methods connected to each type of number. float.is_integer() is a data-type method which checks whether a floating point number is finite or not:

>>> (10.1).is_integer()
False
>>> (5.0).is_integer()
True 

Strings

A String is a list of characters in an organized manner. A character can be a number or letter or even a backslash. In simple words, they are lines enclosed in single or double quotes:

>>> string1 = "hello"
>>> string
'hello'
>>> string2 = 'hey'
>>> string2
"hey"

In Python, we can combine strings in a series without any gaps. This is called Concatenation:

>>> "Python is" + "easy"
'Python is easy'

We can also manipulate strings using functions:

>>> len('Python')
6

Here, len() is a function that takes a string as an input and returns the size of the string.

Data-type methods also exist for handling strings. string.capitalize() takes an input string and returns by capitalizing the first string:

>>> lower_case_string = 'python'
>>> lower_case_string.capitalize()
'Python'
>>> ('the Avengers').capitalize()
'The Avengers' 

Lists

A list is an ordered sequence of elements in Python. Each element in a list is known as an item. They are similar to array in C or C++.
Lists may consist of any data type like numbers or strings mixed together, or other lists or they may be empty too. The syntax is usual:

>>> create_a_list = []
>>> list_of_numbers = [1, 5, 10, 1000]
>>> list_of_numbers
[1, 5, 10, 1000]
>>> list = ["ironman", "thor", "hulk"]
>>> list
['ironman', 'thor', 'hulk']
>>> mixed_list = ["Python", [1, 2, 3], True]
>>> mixed_list
['Python', [1, 2, 3], True]

Elements of lists can be accessed either from the start or the end. Also, you can create a new list just by accessing the elements:

>>> list_of_numbers = [1, 5, 10, 1000]
>>> new_list = list_of_numbers[0:2]
>>> new_list
[1, 5]

Concatenation of lists using operators:

>>> marvel = ["ironman", "thor", "hulk"]
>>> dc = ["superman", "batman", "flash"]
>>> multiverse = marvel + dc
>>> multiverse
[‘ironman’, ‘thor’, ‘hulk’, ‘superman’, ‘batman’, ‘flash’]

The function of lists works in the same manner as of strings:

>>> list_of_numbers = [1, 5, 10, 1000]
>>> len(list_of_numbers)
4

len() returns the size of the list.

Data-type methods like list.sort() and list.append() are used to sort  and append lists:

#append
>>> stationary = ["inkpen", "pencil", "eraser"]
>>> stationary.append("sharpener")
>>> fruits
['inkpen', 'pencil', 'eraser', 'sharpener']

#sort
>>> stationary.sort()
>>> stationary
[ 'eraser', 'inkpen', 'pencil', 'sharpener']

Tuples

Tuples are sequence of Python objects that cannot be changed after creation. They are similar to lists, the only difference being that lists are mutable.

An example of a tuple:

my_tuple = ("Alex", "Blanc", 27, "Technical Blogger")

You can concatenate two tuples using operators just like lists:

>>> tuple1 = (11, 29)
>>> tuple2 = (30, 90)
>>> tuple3 = tuple1 + tuple1
>>> tuple3
(11, 29, 30, 90)

You can convert a tuple into a list by using the function list():

>>> tuple1 = (100, 500)
>>> list(tuple1)
[100, 500]

Since tuples cannot be changed after it is created, most of the data-type methods like sort() or append() or reverse() will not work on tuples.

Dictionary

A dictionary in Python is an unordered collection of associative arrays (or objects).
An example of a dictionary of phone numbers:

>>> phonebook = {}
>>> phonebook["Alex"] = 9038478766
>>> phonebook["Bob"] = 9098379264
>>> phonebook["Charlie"] = 9017652781

Conditions

A conditional statement is a statement that handles the flow of execution depending on some condition.
Statements can be compared or evaluated in Python using boolean expressions as follows:

>>> x = 5
>>> print(x == 5) # prints True
>>> print(x == 2) # prints False

You can also use the if-else statements to check if a statement is true or not:

>>>if 2 > 3:
  print("2 is greater than 3")
  else:
  print("2 is not greater than 3")

Loops

You can use loops when you want to repeat a block of code in a fixed number of time. You can iterate in two different ways, the first is by using the while loop:

>>> num = 1
>>> while num <= 5:
    print(num)
    num = num + 1

While the statement is true, the loop will iterate and the code will be executed. It will print the number from 1 to 5.

Another way of implementing a loop is using the for statement:

>>> for num in range(1, 10):
    print(num) 

Here, the range starts from 1 and goes until 10. The loop iterates 10 times over the statement.

Functions

Functions in Python are a block of organized code which is useful in performing a single action. Syntax of defining a function is def function_name.

An example of a function is:

>>> def my_first_function():
print("HELLO WORLD!")

You can also return a value to the caller in a function using the return statement:

>>> def multiply_by_2(a):
return a * 2

Classes and Objects

An object in Python is a collection of variables and methods. A class is a blueprint for the object.

For example, we can consider a prototype of a house as the class. It consists of all the details of the floors, walls, doors, windows etc. We can build the house on the basis of the details. So, house becomes the object. Objects are instances of a class.

You can define a class in Python using the keyword class as follows: 

>>> class My_First_Class:
    my_variable = "blah"

You can create an object in Python which can be used to access different attributes of a class. This process of creating new object instances is called instantiation.

An example to illustrate that:

class My_First_Class:
def func(self):
print('Hello')
ob = My_First_Class() #creating a class object

Modules and Packages

A module is a single file (or files) that are imported under one import and then used. In simple words, any Python file is a module. On the other hand, packages are simple directories consisting of multiple modules and packages themselves.

Python consists of a number of packages and modules to increase the extent of the language. 

Some of the useful built-in Python modules are:

  • math: This module gives access to mathematical functions from the standard library of C.
  • random: This module is a pseudo-random number generator.
  • datetime: This module comprises of classes by which you can manipulate dates and times.

Pip is the standard package manager which is used to handle Python’s third party packages and modules in an efficient manner. It allows you to install the packages that are not part of the Python Standard Library. You can download Pip from pypi.org.

Comments

Comments can be in the form of module-level docstrings or inline explanations that are used to describe your code in a clear manner so that developers can understand. It starts with a hash (#) character and can extend to the end of the line.

An example of a simple comment:
# This is a comment

An example of an inline comment:

variable = "Hello World"  # This is an inline comment

Errors and Exceptions 

Python consists of two types of errors:

  • Syntax errors.
  • Exceptions or errors during execution.

Syntax Errors

Syntax errors occur when the Python parser is unable to understand a line of code. Most syntax errors occur because of incorrect indentation or arguments.

An example to illustrate such:

>>> if 2 < 5
   File "<stdin>", line 1
     if 2 < 5
             ^
SyntaxError: invalid syntax

Here, the if statement is missing a colon(:)at the end of the statement which results into a syntax error.

Exceptions

Errors that occur during execution are known as exceptions. There are a number of built-in exceptions in Python.

An example of an exception:

>>> prices = { 'Pen' : 10, 'Pencil' : 5, 'Notebook' : 25}
>>> prices['Eraser']
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    prices['Eraser']
KeyError: 'Eraser'

Here, dictionary prices is declared with the prices of three items. The KeyError is raised when the item Eraser is being accessed which is not present in prices. Learn more about exceptions in our blog- Python KeyError Exceptions and How to Handle Them.

Semantic Errors

A semantic error, also known as logic error, is an error that occurs because of an incorrect logic. They are much more difficult to catch as compared to syntax errors.

These type of errors are complex in nature and generate incorrect or no output. The most common example of a semantic error is an infinite loop. Programmers in their early stage of learning encounter an infinite loop at least once.

What are the Different ways of Coding in Python?

When you’re in the process of learning a new programming language, you might want things to be simple and your path of becoming a good programmer to be smooth and clear. The first approach to this will be choosing an efficient way of running and executing code in Python.

There are mainly three primary approaches to coding in Python— the shell, IDLE and the code editor.

The Shell

Python provides the Python Shell, which is useful for simple, one-line statements. It waits for the input commands from the user and returns the result of the execution. It is the least powerful among the three.

You can open shell in your system and run the following command:

>>> 11 + 9
20 

Here, the Python Shell evaluated the statement 11 + 9 , performed the addition operation and displayed the result 20.

Another example of coding in shell:

>>> import this

When you execute this statement, you can see the Zen of Python. It is a collection of 19 principles which acts as a guide to write idiomatic Python code.

However, the shell has a drawback. The code written in a Python Shell is not persistent which means the code cannot be reused. 

IDLE

IDLE stands for Integrated Development and Learning Environment. It is similar to the shell and contains both the Shell window and the Editor Window. You can create and save Python code because the IDLE allows code reusability. However, it still stands second in the rank powerfulness. 

Code Editor

A code editor is the most powerful among all the three. It is a text-editor program that is useful in editing source codes of computer programs. A code editor can be a single application or act as an Integrated Development Environment or IDE.

There are a lot of code editors available in the market. Choosing a code-editor for your task might be a time-consuming work. 

However, you can take into consideration some factors while choosing a code editor like easy to use, line numbering, auto-indentation, highlighting of syntax and availability of adding extra features.

One of the most powerful and popular cross-platform code editor is the Sublime Text.  Other code editors might include gedit,  which is a bit simpler than Sublime. You can also use Notepad++, however it is only for Windows.

Conclusion

Let’s sum up what we have learnt so far in this article:

  • What is Python programming and what is the need.
  • How to install and run Python.
  • What are the primitives of the Python programming language.
  • What are the ways of Python coding.

Though you have learned the basics of the Python Programming Language, here are some tricks and tricks for you remember while coding in Python—

  • Good coding is happy coding. Good code depends on the way you write a code. The key to a good code is to maintain a proper style. You can go through the blog on How To Write Beautiful Python Code With PEP 8 which focuses on enhancing the readability and consistency of code.
  • The logic is the most crucial part when you’re writing a program. If you have a clear understanding of the concepts, you can easily shape your code into a logical program. And the most effective way to do that is to logically break your problem into different parts and then solve it one by one.
  • The best way of learning how to code is by building a project-driven learning approach. There are a lot of free resources, online courses, books and tutorials available. You can refer to the official Python documents - Python 2.7 or Python 3 for more information.You can also join the Python certification course offered by KnowledgeHut.
  • And last but not the least, always keep brushing up the concepts. As a beginner, you might face difficulties in every step, but always try and resolve your issues on your own. Test your skills and take up new challenges everyday.
Priyankur

Priyankur Sarkar

Data Science Enthusiast

Priyankur Sarkar loves to play with data and get insightful results out of it, then turn those data insights and results in business growth. He is an electronics engineer with a versatile experience as an individual contributor and leading teams, and has actively worked towards building Machine Learning capabilities for organizations.

Join the Discussion

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

3 comments

Ravichandran 13 Aug 2019

Clearly explained about the basics of python & different ways of coding in python thanks for the article.

Prasad 13 Aug 2019

Presented well thanks for the article.

kavya 16 Aug 2019

fabulous article, i am searching for this type of article only.

Suggested Blogs

9 Stupendous Technologies You Might Be Using In Near Future

Our lives have made a 360 degree turn in the past decade. Technology is making us move at break neck speed and our lives are all about going somewhere and getting things done. The internet brought the world closer and it has been predicted that it will lead to the democratization of the world. While until a few years back we needed our PCs and laptops to get online, today we can do so with the touch of a button on our smartphones. Indeed, the smartphone has now become the most popular device in many parts of the world. Mobile technology is exactly what the name implies; technology that is mobile, portable and you can carry around in your pocket. A smartphone with an internet connection is all you need to get all your work done. Android and iOS are changing the way we live, eat, sleep, work and even travel. As consumerism grows so does the mobile technology, giving us better, richer and safer experiences than ever before. You will no longer be standing in a checkout line: The future of easy shopping is upon us. With the right app, you will soon be scanning your product and getting it delivered across to your address, which is already stored in the app and the payment would be deducted from your account which is already linked to this app. Of course, the app knows all about your shopping preferences and would suggest possible online stores if you do not get in at the store. Wearable technology: Google Glass and Apple Watch are not the only wearable technology out there. Medical wearable trends are fast changing the landscape of healthcare with such things as computer pills that when ingested send a patient’s medical information to a health centre wirelessly or artificial pancreas that monitor a patient’s glucose levels and also injects insulin at defined intervals. In fact, the future might be even more high-tech with a camera for a contact lens and a microphone under the skin. Your vehicle, a Wi-Fi hotspot: Your car might soon be an escape into a sci-fi movie. GPS enabled location trackers are already widely used but now your vehicle might have wi-fi and enhanced location guidance that may be displayed on the windshield. Data transfer between devices: You are working on your laptop, now on your phone and now on your tablet. There will soon be apps that will allow you to seamlessly move between devices without disrupting your work. No keys future: How many times have you locked yourself out of your house or your car? If carrying a hundred keys around is not exactly your cup of tea then you might as well make your smartphone your best friend since it might be all that you need to open your house, locker, car, safe or any other lock. No more charging: A charge less phone is a complete killjoy. But what if your phone charged by itself without a charger? This ‘”dream come true” situation might soon become a reality with a phenomenon called Piezoelectricity that converts mechanical movements into electric current. So your phone will charge as you are texting or talking. Now that is really a dream come true! Don’t like to type? Then just think: Technology that uses electroencephalography (EEG) might soon hit the market where in devices will be able to read your brain waves and allow interaction with phones or computers or other devices. Advent of the 5G: Once in every 5 years, cellular standards take a quantum leap and the 5G promises to be the most futuristic of them all in terms of power and functionality. This standard is expected to deliver higher speed internet services and greater levels of AI capabilities. No communication barriers: You will soon understand as many languages as you want due to the instant translation apps that will be available on your phone. Global communication barriers will be brought down as people can connect across geographies and text each other in multiple languages. The number of mobile users is expected to reach 5 billion by the year 2020 and this means better connectivity and infrastructure even in the remotest parts of the world. Technology is bringing the world closer and with such advances as interactive t-shirts, USB drives in ornaments and ear patches with voice recognition, the future of mobile technology will be you!
9 Stupendous Technologies You Might Be Using In Ne...

Our lives have made a 360 degree turn in the past ... Read More

Scala In Demand Technologies Built On Scala

The term Scala originated from “Scalable language” and it means that Scala grows with you. In recent times, Scala has attracted developers because it has enabled them to deliver things faster with fewer codes. Developers are now much more interested in having Scala training to excel in the big data field. The Scala community has grown over the years and it has now become a standard for enterprise, start-ups and universities alike. Scala is now being used by many companies and individuals to build their own new ideas. Play Framework, Akka, Apache Spark, etc are some of the tools and projects created using Scala. Scala is now the next wave of computation engines and more importance has been given to the speed processing rather than the size of the batch, and the ability to process event streaming in real-time. 1.Apache Spark Apache Spark can be considered as the replacement of MapReduce. In late 2013, Cloudera, the largest Hadoop vendor supported the idea of replacing MapReduce with Apache Spark. Spark is developed by AMPLab and it is a fast and general purpose engine for large-scale data processing. Spark effectively provides an alternative for Hadoop’s two stage MapReduce model. It has improved the performance of certain applications to 100 times with its fine grain operators, in-memory caching of intermediate data, and data flow optimization. 2. Scalding Scalding has been introduced and maintained by Twitter. It provides full benefits of Scala syntax and functional operations. Scala is a powerful language for solving functional problems. Scalding makes comprehensive use of Scala and it is an extension to cascading that enables application development with Scala. If we focus on the benefits of Scalding, data applications can be built with Scala. With simple and concise syntax code becomes easier to interpret. Scalding has filled the benefits of cascading application framework. 3. Apache Kafka Built and maintained by LinkedIn, Apache Kafka is a distributed streaming platform. Apache Kafka allows the user to publish and subscribe streams of data, just like a messaging system. Kafka is responsible for handling hundred of megabytes of read-write traffic per second from thousand of clients. It is also empowered by Scala and we can see the influence of the language. Real-time data pipelines and streaming apps can be built by using Apache Kafka. Yahoo Kafka Manager is also written in Scala and the web console is built using Play Framework. The Kafka Manager is being used by many teams including the Media Analytics team. It interacts with an actor-based, in-memory model built with Akka and Apache Curator. 4. Finagle Built by the people at twitter, Finagle can be considered as one of the best case using Scala. It is used to build high-concurrency servers and is an extensible RPC system for JVM. Finagle was intended to provide high performance, concurrency along with Scala and Java idiomatic APIs. Finagle is known for the optimal use of available system resources and high scalability through concurrency. It uses safe, simple and clean concurrent programming model which is based on Futures. All these results in safe and modular programs.
Scala In Demand Technologies Built On Scala

The term Scala originated from “Scalable languag... Read More

Web Development Using PHP And MySQL

PHP (or PHP Hypertext Preprocessor) is a server-side scripting language that is used to create dynamic web pages that can interact with databases. It is a widely-used open source language that is specifically used for web application development and can be embedded within HTML. Why PHP? The distinguishing feature of PHP is that the scripting code is executed on the server, which generates HTML that is sent back to the client. The client receives the result of executing the script without knowing the underlying code. Developers can configure the web server to process all the HTML files (containing the PHP script). PHP course is easy to learn for any newcomer, but also offers advanced programming features. Using PHP with a database system PHP, as a scripting language, is popular among web developers because of its ability to interact with database systems including Oracle and MySQL. This article discusses the use of PHP scripting language with the MySQL database. Any website can require a variety of data or information to display and to retrieve them from the database. This can include display of a simple list to the running of the website based on data stored in the database. Listed below are some examples where PHP and MySQL can be used together: • Digital Ad banners, where the PHP script can be used to retrieve a digital banner from the database, which then selects a random banner from its table records and sends it back to the calling script. The PHP script can also maintain a count of banner views and clicks from the website. • Internet forums or digital boards, which use PHP and MySQL to store and retrieve user messages. • Website designing, where the design of an entire website can be changed using a couple of PHP scripts, instead of changing and uploading each web page. The PHP script can access the MySQL database to retrieve all information about the web page. Setting up the MySQL database The procedure of setting up the MySQL database varies according to the host. Every database would require a user name and password, in order to access the database. Database administration can be done using PHP scripts or using a program like PHPMyAdmin. The next step is to create the database tables for storing the website information. Creating a database table using PHPMyAdmin is also simple. Alternatively, one can create and configure the entire database using the following PHP script: CREATE TABLE tablename { Fields } Where the Fields are coded as fieldname type(length) extra_info Example: first varchar(15) NOT NULL The following command is used in the PHP script to connect to the MySQL database: mysql_connect(localhost,$username,$password); where: • localhost is the server address on which the web site is running, • $username is the user name for the database access • $password is the password for the database access Executing PHP commands After configuring and connecting to the MySQL database, you can start executing PHP commands on the server. Following are the 2 methods of executing a PHP command: • Entering the command in PHP using the following syntax: Mysql_query($query) This form of command can be used to repeat the command simply by changing the variable. • Defining the command as a variable. The result of the operation will be assigned to the variable. Data input and output Inserting data using PHP is identical to the procedure of data input using HTML pages. The advantage of using PHP is that the script does not need to be changed for each new piece of input data. Users can also input their own data on the web page. Following is an example of an HTML page with textboxes that can be used to enter data in a form: Alternatively, you can use variables to input information into the database. Example: $first=$_POST[‘first’]; $last=$_POST[‘last’]; $phone=$_POST[‘phone’]; $mobile=$_POST[‘mobile’]; $fax=$_POST[‘fax’]; $email=$_POST[’email’]; $web=$_POST[‘web’]; … $query = “INSERT INTO contacts VALUES (”,’$first’,’$last’,’$phone’,’$mobile’,’$fax’,’$email’,’$web’)”; mysql_query($query); This script is saved in the insert.php file, which can be called from the HTML form. Using this method, data entered in the web page form is stored in the defined variables, which are then passed to the PHP. To display (or output) the entered data using PHP, you can use the following MySQL command with the result assigned to the variable. $query=”SELECT * FROM contacts”; $result=mysql_query($query); PHP provides 2 submission methods, GET and POST to get the data submitted by the form into your PHP script. GET method displays the variables and the data in the page address, while they are invisible in the POST method. For example, a script can be created that will display different web pages depending on the clicked link. yourpage.php?user=david (to show David’s page) yourpage.php?user=tom (to show Tom’s page)
3972
Web Development Using PHP And MySQL

PHP (or PHP Hypertext Preprocessor) is a server-si... Read More

20% Discount