Search

Series List 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.
Rated 4.5/5 based on 3 customer reviews

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

8814
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

How to Build a Python GUI Application With wxPython

A Graphical User Interface or GUI is a user interface that includes graphical elements that enable a person to communicate with electronic devices like computers, hand-held devices, and other appliances. It displays information using icons, menus, and graphics. They are handled with the help of a pointing device such as a mouse, trackball or a stylus.A GUI is basically an application that has windows, buttons and lots of other widgets that allows a user to interact with your application. A web browser is a common example of a GUI that has buttons, tabs, and the main window and where the content is displayed.It was developed by the Xerox Palo Alto research laboratory in the late 1970s. Today, every OS has its own GUI. Software applications make use of these and develop their own GUIs.Python contains many GUI toolkits, out which Tkinter, wxPython, and PyQt are the important ones. All these toolkits have the ability to work with Windows, macOS, and Linux with the additional quality of working on mobile phones.How to get started with wxPython?wxPython was first released in the year 1998. It is an open-source cross-platform Python GUI toolkit used as a wrapper class around a C++ library called wxWidgets. The main feature of wxPython which distinguishes itself from other toolkits like PyQt and Tkinter is that it uses actual widgets on the native platform where required. This allows the wxPython applications to look native to the operating system in which it is running.The wxPython toolkit contains a lot of core widgets along with many custom widgets which you can download from the Extra Files section of the wxPython official page.Here, there is a download of the wxPython demo package which is an application demonstrating the robustness of the widgets included with wxPython. The main advantage of this demo is that you can view it one tab and run it in another and it also allows to edit and re-run the code to observe the changes.Installing wxPythonYou will be using the latest wxPython release, wxPython 4, which is also called the wxPython’s Project Phoenix. It is a new implementation of wxPython that aims at improving the speed, maintainability, and extensibility of wxPython. The wxPython 3 and wxPython 2 were built only for Python 2. The maintainer of wxPython rejected a lot of aliases and cleaned up a lot of code to make wxPython more easy and Pythonic.If you are migrating from an older version of wxPython to wxPython 4, take a look at the following references:Classic version vs project PhoenixPhoenix Migration GuideThe Phoenix version is compatible with both Python 2.7 and Python 3. You can use pip to install wxPython 4:$ pip install wxpythonYou will get a prerequisites section on the Github page of wxPython which will provide information to install wxPython on Linux systems.You can also look into the Extras Linux section to learn about the Python wheels for both GTK2 and GTK3 versions. To install one of the wheels, use the command below:$ pip install -U -f https://extras.wxpython.org/wxPython4/extras/linux/gtk3/ubuntu-18.04/ wxPythonRemember to modify the command to match with the version of Linux.Components of GUIAs mentioned earlier, GUI is nothing but an interface that allows user interaction.Common components of the user interfaces:Main Window.Menu.Toolbar.Buttons.Text Entry.Labels.These items are generally known as widgets. wxPython supports many other common widgets and many custom widgets that are arranged in a logical manner by a developer to allow user interaction.Event LoopsA GUI works by waiting for the user to perform an action. This is known as an event. An event occurs when something is typed by the user or when the user uses their mouse to press a button or some widget while the application is in focus.The GUI toolkit runs an infinite loop called an event loop underneath the covers. The task of the event loop is to act on occurred events on the basis of what the developer has coded the application to do. The application ignores the event when it is not able to catch it.When you are programming a graphical user interface, make sure to attach the widgets to event handlers in order to make your application do something.You can also block an event loop to make the GUI unresponsive which will appear to freeze to the user. This is a special consideration for you to keep in mind while working with event loops. Launch a special thread or process whenever a GUI takes longer than a quarter of a second to launch a process.The frameworks of wxPython contain special thread-safe methods that you can use to communicate back to your application. This informs the thread is finished or given an update.How to create a Skeleton Application?An application skeleton is basically used for prototyping. It is a user interface comprising of widgets that do not contain event handlers. You just need to create the GUI and show it to the stakeholders for signing off and avoid spending time on the backend logic.An example of creating a Hello World application with Python:import wx   application = wx.App() framework = wx.Frame(parent=None, title='Hello World') framework.Show() app.MainLoop()In the example above, there are two parts of the program – wx.App and wx.Frame. The former one is wxPython’s application object which is basically required for running the GUI. It initiates the .MainLoop() which is the event loop you have learned earlier.The latter part creates a window for user interaction. It informs wxPython that the frame has no parent and its title is Hello World. If you run the code above, this is how it will look like:The application will look different if you execute it in Mac or Linux.Note: Mac users may get the following message: This program needs access to the screen. Please run with a Framework build of Python, and only when you are logged in on the main display of your Mac. If you see this message and you are not running in a virtualenv, then you need to run your application with pythonw instead of python. If you are running wxPython from within a virtualenv, then see the wxPython wiki for the solution.The minimize, maximize and exit will be included in the wx.Frame by default. However, most wxPython code will require you to make the wx.Frame as a subclass and other widgets in order to grab the full power of the toolkit.Let us rewrite the code using class:import wx   class MyFramework(wx.Frame):     def frame(self):         super().frame(parent=None, title='Hello World') self.Show()   if __name__ == '__main__':     application = wx.App()     framework = MyFramework() application.MainLoop()This code can be used as a template for your application.Widgets in wxPythonThe wxPython toolkit allows you to create rich applications from more than one hundred widgets. But it can be very daunting to choose the perfect widget from such a large number, so wxPython has included a wxPython Demo which contains a search filter which will help you to find the right widget from the list.Now, let us add a button and allow the user to enter some text by adding a text field:import wx   class MyFramework(wx.Frame):     def frame(self):         super().frame(parent=None, title='Hello World')         panel = wx.Panel(self)   self.text_ctrl = wx.TextCtrl(panel, pos=(5, 5)) my_button = wx.Button(panel, label='Press Me', pos=(5, 55))   self.Show()   if __name__ == '__main__':     application = wx.App()     framework = MyFramework() application.MainLoop()When you run the code, the application will look like this:The first widget that is recommended on Windows is wx.Panel. It makes the background color of the frame as the right shade of gray. Tab traversal is disabled without a Panel on Windows.If the panel is the sole child of the frame, it will be expanded automatically to fill the frame with itself. The next thing you need to do is to add a wx.TextCtrl to the panel. The first argument is always that which parent the widget should go to for almost all widgets. So if you are willing to keep the text control and the button on the top of the panel, it is the parent you need to specify.You also need to inform wxPython about the position of the widget. You can do it using the pos parameter. The default location is (0,0) which is actually at the upper left corner of the parent. So to change the text control, you can change the position of the frame, you can shift its left corner 5 pixels from the left(x) and 5 pixels from the top(y). Finally, you can add your button to the panel and label it. You can also set the y-coordinate to 55 to prevent the overlapping of widgets.Absolute PositioningAbsolute positioning is the technique found in most GUI toolkits by which you can provide the exact coordinates for your widget’s position.There might be situations when you need to keep track of all your widgets and relocate the widgets in case of a complex application. This can be a really difficult thing to do. However, most modern-day toolkits provide a solution for this, which we’ll study next.Sizers (Dynamic Sizing)Sizers are methods to define the control layout in dialogs in wxPython. They have the ability to create dialogs that are not dependent on the platform. They manage the positioning of the widgets and adjust them when the user resizes the application window.Some of the primary types of sizers that are commonly used are:wx.BoxSizerwx.GridSizerwx.FlexGridSizerAn example code to add wx.BoxSizer to the previous code:import wx   class MyFramework(wx.Frame):     def frame(self):         super().frame(parent=None, title='Hello World')         panel = wx.Panel(self)         my_sizer = wx.BoxSizer(wx.VERTICAL)         self.text_ctrl = wx.TextCtrl(panel) my_sizer.Add(self.text_ctrl, 0, wx.ALL | wx.EXPAND, 5)         my_button = wx.Button(panel, label='Press Me') my_sizer.Add(my_btn, 0, wx.ALL | wx.CENTER, 5)         panel.SetSizer(my_sizer)         self.Show()   if __name__ == '__main__':     application = wx.App()     framework = MyFramework() application.MainLoop() In the example above, an instance of wx.BoxSixer is created and passed to wx.VERTICAL which is actually the orientation that widgets are included in the sizer. The widgets will be added in a vertical manner from top to bottom. You can also set the BoxSizer’s orientation to wx.HORIZONTAL. In this case, the widgets are added from left to right.  You can use .Add() to a widget to a sizer which takes maximum five arguments as follows: window ( the widget )- This is the widget that is added to the sizer. proportion - It sets how much space corresponding to other widgets in the sizer will the widget should take. By default, the proportion is zero which leaves the wxPython to its original proportion. flag - It allows you to pass in multiple flags by separating them with a pipe character: |. The text control is added using wx.ALL and wx.EXPAND flags. The wx.ALL flag adds a border on all sides of the widget. On the other hand, wx.EXPAND expands the widgets as much as the sizer can be expanded. border - This parameter informs wxPython about the number of pixels of border needed around the widget.  userData - It is a rare argument that is used for resizing in case of complex applications. However, in this example, the wx.EXPAND flag is replaced with wx.CENTER to display the button in the center on-screen. When you run the code, your application will look something like this:Adding an event using wxPython Though your application looks cool, but it really does nothing. The button you have created does nothing on pressing it. Let us give the button a job:import wx   class MyFramework(wx.Frame):     def frame(self):         super().frame(parent=None, title='Hello World')         panel = wx.Panel(self)         my_sizer = wx.BoxSizer(wx.VERTICAL)         self.text_ctrl = wx.TextCtrl(panel) my_sizer.Add(self.text_ctrl, 0, wx.ALL | wx.EXPAND, 5)         my_button = wx.Button(panel, label='Press Me') my_button.Bind(wx.EVT_BUTTON, self.on_press) my_sizer.Add(my_btn, 0, wx.ALL | wx.CENTER, 5)         panel.SetSizer(my_sizer)         self.Show()   def button_press(self, event):         value = self.text_ctrl.GetValue()         if not value:             print("You didn't enter anything!")        else:             print(f'You typed: "{value}"')   if __name__ == '__main__':     application = wx.App()     framework = MyFramework() application.MainLoop() You can attach event bindings to the widgets in wxPython. This allows them to respond to certain types of events.If you want the button to do something, you can do it using the button’s .Bind() method. It takes the events you want to bind to, the handler to call an event, an optional source, and a number of optional ids. In the example above, the button object is binded to wx.EVT_BUTTON and told to call button_press when the event gets fired..button_press also accepts a second argument by convention that is called event. The event parameter suggests that the second argument should be an event object.You can get the text control’s contents with the help of GetValue() method within .button_press.How to create a Working Application?Consider a situation where you are asked to create an MP3 tag editor. The foremost thing you need to do is to look out for the required packages.Consider a situation where you are asked to create an MP3 tag editor. The foremost thing you need to do is to look out for the required packages.If you make a Google search for Python mp3 tag editor, you will find several options as below:mp3 -taggereyeD3mutagenOut of these, eyeD3 is a better choice than the other two since it has a pretty nice API that can be used without getting bogged down with MP3’s ID3 specification.You can install eyeD3 using pip from your terminal:pip install eyed3If you want to install eyeD3 in macOS, you have to install libmagic using brew. Linux and Windows users can easily install using the command mentioned above.Designing the User Interface using wxPythonThe very first thing you must do before designing an interface is to sketch out how you think the interface should look.The user interface should perform the following tasks:Open up one or more MP3 files.Display the current MP3 tags.Edit an MP3 tag.If you want to open a file or a folder, you need to have a menu or a button in your user interface. You can do that with a File menu. You will also need a widget to see the tags for multiple MP3 files. A tabular structure consisting of columns and rows would be perfect for this case since you can have labeled columns for the MP3 tags. wxPython toolkit consists of afew widgets to perform this task:wx.grid.Gridwx.ListCtrlwx.ListCtrl would be a better option of these two since the Grid widget is overkill and complex in nature. Finally, you can use a button to perform the editing tasks.Below is an illustration of what the application should look like:Creating the User Interface You can refer to a lot of approaches when you are creating a user interface. You can follow the Model-View-Controller design pattern that is used for developing user interfaces which divides the program logic into three interconnected elements. You should know how to split up classes and how many classes should be included in a single file and so on.However, in this case, you need only two classes which are as follows:wx.Panel classwx.Frame class Let’s start with imports and the panel class:import eyed3 import glob import wx   class Mp3Panel(wx.Panel):     def frame(self, parent):         super().__init__(parent) main_sizer = wx.BoxSizer(wx.VERTICAL) self.row_obj_dict = {}   self.list_ctrl = wx.ListCtrl(             self, size=(-1, 100),               style=wx.LC_REPORT | wx.BORDER_SUNKEN         ) self.list_ctrl.InsertColumn(0, 'Artist', width=140) self.list_ctrl.InsertColumn(1, 'Album', width=140) self.list_ctrl.InsertColumn(2, 'Title', width=200) main_sizer.Add(self.list_ctrl, 0, wx.ALL | wx.EXPAND, 0)         edit_button = wx.Button(self, label='Edit') edit_button.Bind(wx.EVT_BUTTON, self.on_edit) main_sizer.Add(edit_button, 0, wx.ALL | wx.CENTER, 5)         self.SetSizer(main_sizer)   def on_edit(self, event):         print('in on_edit')   def update_mp3_listing(self, folder_path):         print(folder_path)In this example above, the eyed3 package, glob package, and the wx package are imported. Then, the user interface is created by making wx.Panel a subclass. A dictionary row_obj_dict is created for storing data about the MP3s. The next thing you do is create a wx.ListCtrl and set it to report mode, i.e. wx.LC_REPORT. This report flag is the most popular among all but you can also choose your own depending upon the style flag that you pass in. Now you need to call .InsertColumn() to make the ListCtrl have the correct headers and then provide the index of the column, its label and the width of the column pixels. Finally, you need to add your Edit button, an event handler, and a method. The code for the frame is as follows:class Mp3Frame(wx.Frame):     def__init__(self):         super().__init__(parent=None,                          title='Mp3 Tag Editor') self.panel = Mp3Panel(self) self.Show()   if __name__ == '__main__':     app = wx.App(False)     frame = Mp3Frame() app.MainLoop()This class function is a better and simpler approach than the previous one because you just need to set the title of the frame and instantiate the panel class, MP3Panel. The user interface will look like this after all the implementations:The next thing we will do is add a File menu to add MP3s to the application and also edit their tags.Make a Functioning ApplicationThe very first thing you need to do to make your application work is to update the wx.Frame class to include the File menu which will allow you to add MP3 files.Code to add a menu bar to our application:class Mp3Frame(wx.Frame):   def__init__(self):         wx.Frame.__init__(self, parent=None,                             title='Mp3 Tag Editor') self.panel = Mp3Panel(self) self.create_menu() self.Show()   def create_menu(self): menu_bar = wx.MenuBar() file_menu = wx.Menu() open_folder_menu_item = file_menu.Append( wx.ID_ANY, 'Open Folder',   'Open a folder with MP3s'         ) menu_bar.Append(file_menu, '&File') self.Bind(             event=wx.EVT_MENU,               handler=self.on_open_folder,             source=open_folder_menu_item,         ) self.SetMenuBar(menu_bar)   def on_open_folder(self, event):         title = "Choose a directory:" dlg = wx.DirDialog(self, title,                              style=wx.DD_DEFAULT_STYLE) if dlg.ShowModal() == wx.ID_OK:             self.panel.update_mp3_listing(dlg.GetPath()) dlg.Destroy() In the example code above, .create_menu() is called within the class’s constructor and then two instances – wx.MenuBar and wx.Menu are created.Now, if you’re willing to add an item to the menu, you need to call the menu instance’s .Append() and pass the following things:A unique identifierLabelA help stringAfter that call the menubar’s .Append() to add the menu to the menubar. It will take the menu instance and the label for menu. The label is called as &File so that a keyboard shortcut is created to open the File menu using just the keyboard.Now self.Bind() is called to bind the frame to wx.EVT_MENU. This informs wxPython about which handler should be used and which source to bind the handler to. Lastly, call the frame’s .SetMenuBar and pass it the menubar instance. Your menu is now added to the frame.Now let’s come back to the menu item’s event handler:def on_open_folder(self, event):     title = "Choose a directory:" dlg = wx.DirDialog(self, title, style=wx.DD_DEFAULT_STYLE) if dlg.ShowModal() == wx.ID_OK:         self.panel.update_mp3_listing(dlg.GetPath()) dlg.Destroy()You can use wxPython’s wx.DirDialog to choose the directories of the correct MP3 folder. To display the dialog, use .ShowModal(). This will display the dialog modally but will disallow the user to interact with the main application.  You can get to the user’s choice of path using .GetPath() whenever the user presses the OK button. This path has to be added to the panel class and this can be done by the panel’s .update_mp3_listing().Finally, you will have to close the dialog and the best method is using .Destroy().  There are methods to close the dialog like .Close() which will just dialog but will not destroy it, so .Destroy() is the most effective option to prevent such situation.Now let’s update the MP3Panel class starting with .update_mp3_listing():def update_mp3_listing(self, folder_path): self.current_folder_path = folder_path self.list_ctrl.ClearAll()   self.list_ctrl.InsertColumn(0, 'Artist', width=140) self.list_ctrl.InsertColumn(1, 'Album', width=140) self.list_ctrl.InsertColumn(2, 'Title', width=200) self.list_ctrl.InsertColumn(3, 'Year', width=200)       mp3s = glob.glob(folder_path + '/*.mp3')     mp3_objects = []     index = 0 for mp3 in mp3s:         mp3_object = eyed3.load(mp3) self.list_ctrl.InsertItem(index,               mp3_object.tag.artist) self.list_ctrl.SetItem(index, 1,               mp3_object.tag.album) self.list_ctrl.SetItem(index, 2,               mp3_object.tag.title)         mp3_objects.append(mp3_object) self.row_obj_dict[index] = mp3_object         index += 1In the example above, the current directory is set to the specified folder and the list control is cleared. The list controls stay fresh and shows the MP3s you’re currently working with. Next, the folder is taken and Python’s globmoduleis used to search for the MP3 files. Then, the MP3s are looped over and converted into eyed3 objects. This is done by calling the .load() of eyed3. After that, you can add the artist, album, and the title of the Mp3 to the control list given that the MP3s have the appropriate tags..InsertItem() is used to add a new row to a list control for the first time and SetItem()  is used to add rows to the subsequent columns. The last step is to save your MP3 object to your Python dictionary row_obj_dict.Now to edit an MP3’s tags, you need to update the .on_edit() event handler:def on_edit(self, event):     selection = self.list_ctrl.GetFocusedItem() if selection >= 0:         mp3 = self.row_obj_dict[selection] dlg = EditDialog(mp3) dlg.ShowModal()         self.update_mp3_listing(self.current_folder_path) dlg.Destroy()The user’s selection is taken by calling the list control’s .GetFocusedItem(). It will return -1 if the user will not select anything in the list control. However, if you want to extract the MP3 obj3ct from the dictionary, the user have to select something. You can then open the MP3 tag editor dialog which will be a custom dialog. As before, the dialog is shown modally, then the last two lines in .on_edit() will execute what will eventually display the current MP3 tag information. SummaryLet us sum up what we have learned in this article so far – Installing wxPython and Working with wxPython’s widgets Working of events in wxPython Comparing absolute positioning with sizers Creating a skeleton application and a working application The main feature of the wxPython Graphical User Interface is its robustness and a large collection of widgets that you can use to build cross-platform applications. Since you have now learned how to create a working application, that is an MP3 tag editor, you can try your hand to enhance this application to a more beautiful one with lots of new features or you can perhaps create your own wonderful application. To gain more knowledge about Python tips and tricks, check our Python tutorial and get a good hold over coding in Python by joining the Python certification course.
Rated 4.5/5 based on 2 customer reviews
5956
How to Build a Python GUI Application With wxPytho...

A Graphical User Interface or GUI is a user interf... Read More

How To Run Your Python Scripts

If you are planning to enter the world of Python programming, the first and the most essential skill you should learn is knowing how to run Python scripts and code. Once you grab a seat in the show, it will be easier for you to understand whether the code will actually work or not.Python, being one of the leading programming languages, has relatively easy syntax which makes it even easier for the ones who are in their initial stage of learning the language. Also, it is the language of choice for working with large datasets and data science projects. Get certified and learn more about Python Programming and apply those skills and knowledge in the real world.What is the difference between Code, Script and Modules?In computing, the code is a language that is converted from a human language into a set of ‘words’ which the computer can understand. It is also referred to as a piece of statements together which forms a program. A simple function or a statement can also be considered a code.On the other hand, a script is a file consisting of a logical sequence of instructions or a batch processing file that is interpreted by another program instead of the computer processor.In simple terms, a script is a simple program, stored in a plain file text which contains Python code. The code can be directly executed by the user. A script is also called a top-level-program-file. A module is an object in Python with random attributes that you can bind and reference.Is Python a Programming Language or a Scripting Language?Basically, all scripting languages are considered to be programming languages. The main difference between the two is that programming languages are compiled, whereas scripting languages are interpreted. Scripting languages are slower than programming languages and usually sit behind them. Since they only run on a subset of the programming language, they have less access to a computer’s local abilities. Python can be called a scripting language as well as a programming language since it works both as a compiler and an interpreter. A standard Python can compile Python code into bytecodes and then interpret it just like Java and C.However, considering the historical relationship between the general purpose programming language and the scripting language, it will be more appropriate to say that Python is a general-purpose programming language which works nicely as a scripting language too.The Python InterpreterThe Interpreter is a layer of software that works as a bridge between the program and the system hardware to keep the code running. A Python interpreter is an application which is responsible for running Python scripts.The Python Interpreter works on the Read-Eval-Print-Loop (REPL) environment.Reads the command.Evaluates the command.Prints the result.Loops back and process gets repeated.The interpreter terminates when we use the exit() or quit() command otherwise the execution keeps on going.A Python Interpreter runs code in two ways— In the form of a script or module.In the form of a piece of code written in an interactive session.Starting the Python InterpreterThe simplest way to start the interpreter is to open the terminal and then use the interpreter from the command-line.To open the command-line interpreter:On Windows, the command-line is called the command prompt or MS-DOS console. A quicker way to access it is to go to Start menu → Run and type cmd.On GNU/Linux, the command-line can be accessed by several applications like xterm, Gnome Terminal or Konsole.On MAC OS X, the system terminal is accessed through Applications → Utilities → Terminal. Running Python Code InteractivelyRunning Python code through an interactive session is an extensively used way. An interactive session is an excellent development tool to venture with the language and allows you to test every piece of Python code on the go.To initiate a Python interactive session, type python in the command-line or terminal and hit the ENTER key from the keyboard.An example of how to do this on Windows:C:\users>python Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>>The >>> on the terminal represents the standard prompt for the interactive mode. If you do not see these characters, you need to re-install Python on your system.The statements you write when working with an interactive session are evaluated and executed immediately:print('HELLO WORLD!') HELLO WORLD! 2 + 3 5 print('Welcome to the world of PYTHON') Welcome to the world of PYTHON The only disadvantage is when you close the interactive session, the code no longer exists.Running Python Scripts by the InterpreterThe term Python Execution Model is given to the entire multi-step process to run Python scripts.At first, the statements or expressions of your script are processed in a sequential manner by the interpreter. Then the code is compiled into a form of instruction set called the bytecode.Basically, the code is converted into a low-level language known as the bytecode. It is an intermediate, machine-independent code which optimizes the process of code execution. So, the interpreter ignores the compilation step when executing the code for the next time.Finally, the interpreter transfers the code for execution.The Python Virtual Machine (PVM) is the ultimate step of the Python interpreter process. It is a part of the Python environment installed in your system. The PVM loads the bytecode in the Python runtime and reads each operation and executes them as indicated. It is the component which actually runs your scripts.Running Python Scripts using Command-LineThe most sought after way of writing a Python program is by using a plain text editor. The code written in the Python interactive session is lost once the session is closed, though it allows the user to write a lot of lines of code. On Windows, the files use the .py extension.  If you are at the beginning of working with Python, you can use editors like Sublime or Notepad++ which are easy-to-use or any other text editors.Now you need to create a test script. In order to do that, open your most suited text editor and write the following code:print('Hello World!')Then save the file in your desktop with the name first_script.py or anything you like. Remember you need to give the .py extension only.Using python commandThe most basic and the easy way to run Python scripts is by using the python command. You need to open a command-line and type the word python followed by the path to your script file, like this:python first_script.py Hello World!Then you hit the ENTER button from the keyboard and that's it. You can see the phrase Hello World! on the screen. Congrats! You just ran your first Python script. However, if you do not get the output, you might want to check your system PATH and the place where you saved your file. If it still doesn’t work, re-install Python in your system and try again.Redirecting outputWindows and Unix-like systems have a process called stream redirection. You can redirect the output of your stream to some other file format instead of the standard system output. It is useful to save the output in a different file for later analysis.An example of how you can do this:python first_script.py > output.txtWhat happens is your Python script is redirected to the output.txt file. If the file doesn’t exist, it is systematically created. However, if it already exists, the contents are replaced.Running modules with the -m optionA module is a file which contains the Python code. It allows you to arrange your Python code in a logical manner. It defines functions, classes, and variables and can also include runnable code.If you want to run a Python module, there are a lot of command-line options which Python offers according to the needs of the user. One of which is the command  python -m . It searches the module name in the sys.path and runs the content as __main__:python -m first_script Hello World!Note that the module-name is a module object and not any string.Using Script FilenameWindows makes use of the system registers and file association to run Python scripts. It determines the program needed to run that particular file. You need to simply enter the file-name containing the code.An example on how to do this using command prompt:C:\Users\Local\Python\Python37> first_script.py Hello World!On GNU/Linux systems, you need to add a line before the text— #!/usr/bin/env python. Python considers this line nothing but the operating system considers it everything. It helps the system to decide what program should it use to run the file.The character combination #! known as hashbang or shebang is what the line starts with, which is then followed by the interpreter path.Finally, to run scripts, assign execution permissions and configure the hashbang line and then simply type the filename in the command line:#Assign the execution permissions chmod +x first_script.py #Run script using its filename ./first_script.py Hello World!However, if it doesn’t work, you might want to check if the script is located in your currentworking directory or not. Otherwise, you can use the path of the file for this method. Running Python Scripts InteractivelyAs we have discussed earlier, running Python scripts in an interactive session is the most common way of writing scripts and also offers a wide range of possibilities.Using importImporting a module means loading its contents so that it can be later accessed and used. It is the most usual way of invoking the import machinery. It is analogous to #include in C or C++. Using import, the Python code in one module gets access to the code in another module. An implementation of the import:import first_script Hello World!You can see its execution only when the module contains calls to functions, methods or other statements which generate visible output.One important thing to note is that the import option works only once per session. This is because these operations are expensive.For this method to work efficiently, you should keep the file containing the Python code in your current working directory and also the file should be in the Python Module Search Path (PMSP). The PMSP is the place where the modules and packages are imported.You can run the code below to know what’s in your current PSMP:import sys for path in sys.path: print(path)\Users\Local\Python37\Lib\idlelib \Users\Local\Python37\python37.zip \Users\Local\Python37\DLLs \Users\Local\Python37\lib \Users\Local\Python37 \Users\Local\Python37\lib\site-packagesYou’ll get the list of directories and .zip files where your modules and packages are imported.Using importlibimportlib is a module which is an implementation of the import statement in the Python code. It contains the import_module whose work is to execute any module or script by imitating the import operation.An example to perform this:import importlib importlib.import_module('first_script') Hello World! importlib.reload() is used to re-import the module since you cannot use import to run it for the second time. Even if you use import after the first time, it will do nothing. importlib.reload() is useful when you want to modify and test your changes without exiting the current session.The following code shows that:import first_script #First import Hello World! import first_script import importlib #Second import does nothing importlib.reload(first_script) Hello World! However, you can only use a module object and not any string as the argument of reload(). If you use a string as an argument, it will show a TypeError as follows:importlib.reload(first_script)Traceback (most recent call last): ... ...   raise TypeError("reload() argument must be a module") TypeError: reload() argument must be a moduleUsing runpy.run_module() and runpy.run_path()The Python Standard Library has a module named runpy. run_module() is a function in runpy whose work is to execute modules without importing them in the first place. The module is located using import and then executed. The first argument of the run_module() must contain a string:import runpy runpy.run_module(mod_name='first_script') Hello World! {'__name__': 'first_script',     ... '_': None}}Similarly, runpy contains another function run_path() which allows you to run a module by providing a location.An example of such is as follows:import runpy runpy.run_path(file_path='first_script.py') Hello World! {'__name__': '',     ... '_': None}}Both the functions return the globals dictionary of the executed module.Using exec()Other than the most commonly used ways to run Python scripts, there are other alternative ways. One such way is by using the built-in function exec(). It is used for the dynamic execution of Python code, be it a string or an object code.An example of exec() is:exec(open('first_script.py').read()) Hello World!Using py_compilepy_compile is a module which behaves like the import statement. It generates two functions— one to generate the bytecode from the source file and another when the source file is invoked as a script.You can compile your Python script using this module:import py_compile py_compile.compile('first_script.py'  '__pycache__\\first_script.cpython-37.pyc' The py_compile generates a new subdirectory named "__pycache__" if it doesn’t already exist. Inside the subdirectory, a Compiled Python File (.pyc) version of the script file is created. When you open the .pyc file, you can see the output of your Python script.Running Python Scripts using an IDE or a Text EditorAn Integrated Development Environment (IDE) is an application that allows a developer to build software within an integrated environment in addition to the required tools.You can use the Python IDLE, a default IDE of the standard Python Distribution to write, debug, modify, and run your modules and scripts. You can use other IDEs like Spyder, PyCharm, Eclipse, and Jupyter Notebook which also allow you to run your scripts inside its environment.You can also use popular text editors like Sublime and Atom to run Python scripts.If you want to run a Python script from your IDE or text editor, you need to create a project first. Once it is created, add your .py file to it or you can just simply create one using the IDE. Finally, run it and you can see the output in your screen.Running Python Scripts from a File ManagerIf you want to run your Python script in a file manager, all you need to do is just double-click on the file icon. This option is mainly used in the production stage after you have released the source code.However, to achieve this, some conditions must be met:On Windows, to run your script by double-clicking on them, you need to save your script file with extension .py for python.exe and .pyw for pythonw.exe.If you are using the command-line for running your script, you might likely come  through a situation where you’ll see a flash of a black window on the screen. To avert this, include a statement at the tail of the script — input(‘Enter’). This will exit the program only when you hit the ENTER key. Note that the input() function will work only if your code is free of errors.On GNU/Linux and other Unix-like systems, your Python script must contain the hashbang line and execution permissions. Otherwise, the double-click trick won’t work in a file manager.Though it is easy to execute a script by just double-clicking on the file, it isn’t considered a feasible option because of the limitations and dependency factors it comes with, like the operating system, the file manager, execution permissions, and also the file associations.So it is suggested to use this option only after the code is debugged and ready to be in the production market.ConclusionWorking with scripts has its own advantages like they are easy to learn and use, faster edit and run, interactivity, functionality and so on. They are also used to automate complex tasks in a simplified manner.In this article, you have learned to run your Python scripts using:The terminal or the command-line of the operating system.The Python Interactive session.Your favorite IDE or text editor.The system file manager.Here, you have gathered the knowledge and skills of how to run your scripts using various techniques.You will feel more comfortable working with larger and more complex Python environments which in turn will enhance the development process and increase efficiency. You can learn more about such techniques as KnowledgeHut offers Python Certification Course.
Rated 4.5/5 based on 19 customer reviews
5970
How To Run Your Python Scripts

If you are planning to enter the world of Python p... Read More

What are Python KeyError Exceptions and How to Handle Them

There are times when you have written your code but while you execute, it might not run. These types of situations occur when the input is inappropriate or you try to open a file with a wrong path or try to divide a number by zero. Due to some errors or incorrect command the output will not be displayed. This is because of errors and exceptions which are a part of the Python programming language. Learn about such concepts and gain further knowledge by joining Python Programming Course.What is Exception Handling?Python raises exceptions when it encounters errors during execution. A Python Exception is basically a construct that signals any important event, such as a run-time error.Exception Handling is the process of responding to executions during computations, which often interrupts the usual flow of executing a program. It can be performed both at the software level as part of the program and also at hardware level using built-in CPU mechanisms.Why is Exception Handling Important?Although exceptions might be irritating when they occur, they play an essential role in high level languages by acting as a friend to the user.An error at the time of execution might lead to two things— either your program will die or will display a blue screen of death. On the other hand, exceptions act as communication tools. It allows the program to answer the questions — what, why and how something goes wrong and then terminates the program in a delicate manner.In simple words, exception handling protects against uncontrollable program failures and increases the potency and efficiency of your code. If you want to master yourself in programming, the knowledge of exceptions and how to handle them is very crucial, especially in Python.What are the Errors and Exceptions in Python?Python doesn’t like errors and exceptions and displays its dissatisfaction by terminating the program abruptly.There are basically two types of errors in the Python language-Syntax Error.Errors occuring at run-time or Exceptions.Syntax ErrorsSyntax Errors, also known as parsing errors, occur when the parser identifies an incorrect statement. In simple words, syntax error occurs when the proper structure or syntax of the programming language is not followed.An example of a syntax error:>>> print( 1 / 0 )) File "", line 1 print( 1 / 0 ))   ^SyntaxError: invalid syntaxExceptionsExceptions occur during run-time. Python raises an exception when your code has a correct syntax but it encounters a run-time issue which it is not able to handle.There are a number of defined built-in exceptions in Python which are used in specific situations. Some of the built-in exceptions are:ExceptionCause Of ErrorArithmeticErrorRaised when numerical computation fails.FloatingPointErrorRaised when floating point calculation fails.AssertionErrorRaised in case of failure of the Assert statement.ZeroDivisionErrorRaised when division or modulo by zero takes place for all numerical values.OverflowErrorRaised when result of an arithmetic operation is very large to be represented.IndexErrorRaised when an index is not found in a sequence.ImportErrorRaised when the imported module is not found.IndentationErrorRaised when indentation is not specified properly.KeyboardInterruptRaised when the user hits interrupt key.RuntimeErrorRaised when a generated error does not fall into any category.SyntaxErrorRaised when there is an error in Python syntax.IOErrorRaised when Python cannot access a file correctly on disk.KeyErrorRaised when a key is not found in a dictionary.ValueErrorRaised when an argument to a function is the right type but not in the right domain.NameErrorRaised when an identifier is not found in the local or global namespace.TypeErrorRaised when an argument to a function is not in the right type.There are another type of built-in exceptions called warnings. They are usually issued in situations where the user is alerted of some conditions. The condition does not raise an exception; rather it  terminates the program.What is a Python KeyError?Before getting into KeyError, you must know the meaning of dictionary and mapping in Python. Dictionary (dict) is an unordered collection of objects which deals with data type key. They are Python’s implementation of data structures and are also known as associative arrays. They comprise key-value pairs, in which each pair maps the key to its associated value.Dictionary is basically a data structure that maps one set of values into another and is the most common mapping in Python.Exception hierarchy of KeyError:->BaseException              ->Exception                         ->LookupError                                       ->KeyErrorA Python KeyError is raised when you try to access an invalid key in a dictionary. In simple terms, when you see a KeyError, it denotes that the key you were looking for could not be found.An example of KeyError:>>> prices = { 'Pen' : 10, 'Pencil' : 5, 'Notebook' : 25} >>> prices['Eraser'] Traceback (most recent call last): File "", line 1, in 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.Whenever an exception is raised in Python, it is done using traceback, as you can see in the example code above. It tells why an exception is raised and what caused it.Let’s execute the same Python code from a file. This time, you will be asked to give the name of the item whose price you want to know:# prices.py prices = { 'Pen' : 10, 'Pencil' : 5, 'Notebook' : 25} item = input('Get price of: ') print(f'The price of {item} is {prices[item]}')You will get a traceback again but you’ll also get the information about the line from which the KeyError is raised:Get price of: Eraser Traceback (most recent call last): File "prices.py", line 5, in print(f'The price of {item} is {prices[item]}') KeyError: 'Eraser'The traceback in the example above provides the following information:A KeyError was raised.The key ‘Eraser’ was not found.The line number which raised the exception along with that line.Where else will you find a Python KeyError?Although most of the time, a KeyError is raised because of an invalid key in a Python dictionary or a dictionary subclass, you may also find it in other places in the Python Standard Library, such as in a zipfile. However, it denotes the same semantic meaning of the Python KeyError, which is not finding the requested key.An example of such:>>> from zipfile import ZipFile >>> my_zip_file = ZipFile('Avengers.zip') >>> my_zip_file.getinfo('Batman')Traceback (most recent call last): File "", line 1, in File "myzip.py", line 1119, in getinfo 'There is no item named %r in the archive' % name) KeyError: "There is no item named 'Batman' in the archive"In this example, the zipfile.ZipFile class is used to derive information about a ZIP archive ‘Batman’ using the getinfo() function. Here, the traceback indicates that the problem is not in your code but in the zipfile code, by showing the line which caused the problem. The exception raised here is not because of a LookUpError but rather due to the zipfile.ZipFile.getinfo()function call.When do you need to raise a Python KeyError?In Python Programming, it might be sensible at times to forcefully raise exceptions in your own code. You can usually raise an exception using the raise keyword and by calling the KeyError exception:>>> raise KeyError('Batman')Here, ‘Batman’ acts as the missing key. However, in most cases, you should provide more information about the missing key so that your next developer has a clear understanding of the problem.Conditions to raise a Python KeyError in your code:It should match the generic meaning behind the exception.A message should be displayed about the missing key along with the missing key which needs to be accessed.How to Handle a Python KeyError?The main motive of handling a Python KeyError is to stop unexpected KeyError exceptions to be raised. There are a number of number of ways of handling a KeyError exception.Using get()The get()is useful in cases where the exception is raised due to a failed dictionary LookupError. It returns either the specified key value or a default value.# prices.py prices = { 'Pen' : 10, 'Pencil' : 5, 'Notebook' : 25} item = input('Get price of: ') price = prices.get(item) if price:   print(f'The price of {item} is {prices[item]}')   else:   print(f'The price of {item} is not known')This time, you’ll not get a KeyError because the get() uses a better and safer method to retrieve the price and if not found, the default value is displayed:Get price of: EraserThe price of Eraser is not knownIn this example, the variable price will either have the price of the item in the dictionary or the default value ( which is None by default ).In the example above, when the key ‘Eraser’ is not found in the dictionary, the get() returns  None by default rather than raising a KeyError. You can also give another default value as a second argument by calling get():price = prices.get(item,0)If the key is not found, it will return 0 instead of None.Checking for KeysIn some situations, the get() might not provide the correct information. If it returns None, it will mean that the key was not found or the value of the key in Python Dictionary is actually None, which might not be true in some cases. In such situations, you need to determine the existence of a key in the dictionary. You can use the if and in operator to handle such cases. It checks whether a key is present in the mapping or not by returning a boolean (True or False) value:dict = dictionary() for i in range(50):   key = i % 10     if key in dict: dict[key] += 1 else: dict[key] = 1In this case, we do not check what the value of the missing key is but rather we check whether the key is in the dictionary or not. This is a special way of handling an exception which is used rarely.This technique of handling exceptions is known as Look Before You Leap(LBYL).Using try-exceptThe try-except block is one of the best possible ways to handle the KeyError exceptions. It is also useful where the get() and the if and in operators are not supported.Let’s apply the try-except block on our earlier retrieval of prices code:# prices.py prices = { 'Pen' : 10, 'Pencil' : 5, 'Notebook' : 25} item = input('Get price of: ') try: print(f'The price of {item} is {prices[item]}') except KeyError: print(f'The price of {item} is not known')Here, in this example there are two cases— normal case and a backup case. try block corresponds to the normal case and except block to the backup case. If the normal case doesn’t print the name of the item and the price and raises a KeyError, the backup case prints a different statement or a message.Using try-except-elseThis is another way of handling exceptions. The try-except-else  has three blocks— try block, except block and else block.The else condition in a try-except statement is useful when the try condition doesn’t raise an exception. However, it must follow all the except conditions.Let us take our previous price retrieval code to illustrate try-except-else:# prices.py prices = { 'Pen' : 10, 'Pencil' : 5, 'Notebook' : 25} item = input('Get price of:') try: print(f'The price of {item} is {prices[item]}') except KeyError: print(f'The price of {item} is not known') else: print(f'There is no error in the statement')First, we access an existing key in the try-except block. If the Keyerror is not raised, there are no errors. Then the else condition is executed and the statement is displayed on the screen.Using finallyThe try statement in Python can have an optional finally condition. It is used to define clean-up actions and is always executed irrespective of anything. It is generally used to release external sources.An example to show finally:# prices.py prices = { 'Pen' : 10, 'Pencil' : 5, 'Notebook' : 25} item = input('Get price of: ') try: print(f'The price of {item} is {prices[item]}') except KeyError: print(f'The price of {item} is not known') finally: print(f'The finally statement is executed')Remember, the finally statement will always be executed whether an exception has occurred or not.How to raise Custom Exceptions in Python?Python comprises of a number of built-in exceptions which you can use in your program. However, when you’re developing your own packages, you might need to create your own custom exceptions to increase the flexibility of your program.You can create a custom Python exception using the pre-defined class Exception:def square(x): if x
Rated 4.5/5 based on 1 customer reviews
7589
What are Python KeyError Exceptions and How to Han...

There are times when you have written your code bu... Read More

20% Discount