Python - Coding Infinite https://codinginfinite.com/python/ Your infinite Coding Solutions Sat, 29 Feb 2020 13:57:39 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.3 https://codinginfinite.com/wp-content/uploads/2018/07/CODING-INFINITE-FAVICON.png Python - Coding Infinite https://codinginfinite.com/python/ 32 32 Top Reasons Why Python is Your Go-To Programming Language for Machine Learning https://codinginfinite.com/top-reasons-why-python-is-best-for-machine-learning/ Wed, 05 Feb 2020 08:08:05 +0000 https://codinginfinite.com/?p=4039 Machine learning is the hottest buzzword in modern times. Alexa, Siri, and Google voice assistants have become a part of our daily lives. Isn’t that, right? The upcoming five years will see a drastic change as the value of the worldwide market for AI assistant anticipates touching USD 18 billion. More importantly, we’re now living...

The post Top Reasons Why Python is Your Go-To Programming Language for Machine Learning appeared first on Coding Infinite.

]]>
Machine learning is the hottest buzzword in modern times. Alexa, Siri, and Google voice assistants have become a part of our daily lives. Isn’t that, right? The upcoming five years will see a drastic change as the value of the worldwide market for AI assistant anticipates touching USD 18 billion.

More importantly, we’re now living in a world filled with intelligent assistants.

Machine learning has emerged as one of the core key factors of digital transformation. The adoption of machine learning tools by the majority of the enterprises is set to reach 65% before the current decade ends.

There are newer cases of machine learning problems that are popping, and 55% of the CIOs have concluded stating ML to be their core priority. Python is the primary programming language projects to be the go-to tool for AI experts.

Based on the Stack Overflow developer survey 2019, Python proves itself to stand as the most loved programming language two years in a row. It is also deemed as the fastest-growing language as compared to other languages.

The majority of AI professionals are adopting Python for their machine learning projects.

Top reasons why Python is best suited for machine learning: –

Multi-libraries and frameworks

Python being a popular programming language emerges as one language that provides multiple libraries and frameworks. Based on the kind of projects the user may be able to choose the relevant set of libraries as well as frameworks thus eradicating late deadlines.

Python libraries for AI and machine learning:

  • TensorFlow – this is a popular library for developing machine learning applications like neural networks
  • Keras – majorly used on experimenting neural networks
  • Scikit-learn – this library helps in conjugation with SciPy and NumPy
  • NumPy – data analysis, data cleaning, and data manipulation extremely helps in building machine learning application
  • PyTorch – used for developing deep learning models

Easy to learn

Python, as stated by majority of AI engineersis an easy language to learn in comparison to the other traditional programming language. Simply because it has an approachable learning curve. It is easy to read, and even the syntax is accessible for beginners. Owing to its easy code readability, understanding the syntax gets easier for developers.

Widespread community

Python has been here since the 1990s, and it had a good amount of time to create a supportive community. Because of its vast community, Python users can easily upgrade their skills and knowledge in machine learning. This led to the increased popularity of Python.

Big giants like Netflix, Google, Amazon, Facebook, Instagram, and Quora have already adopted Python in product development.

Documentation

Python has got several documentation and tutorials for developers to learn. Readability becomes a major concern for aspiring AI experts – both for project documentation and code documentation. The community not only provides quick development but also offers a friendly syntax for these users to understand, and rapid prototyping that aids in developing cognitive systems.

Versatile in nature

Python has been around for more than two decades. As time flies, the nature of versatility keeps increasing. It is now implemented majorly for software development, working and managing cloud infrastructure, and for every operation.  

Given its nature of versatility, Python easily supports structured programming, functional programming patterns, and object-oriented programming.  This not only can be applied for machine learning projects or data science, but is highly recommended for development, web frameworks, and gaming, etc.

With Spark as its supporting tool, Python easily manages data handling amounting to the humongous amount of data.

Endnote

The rapid adoption of Python across the tech industry will help the upcoming AI market resolve the lacuna taking place with a shortage of skills. Many enterprises are excited about the business value AI and machine learning will produce in the foreseeable future.


Thank you for reading.

Here’re some more articles of the same interest:

— What Stats & Surveys Are Saying About Top Programming Languages In 2020

— Six Pillars to Become a Senior Level Software Developer

The post Top Reasons Why Python is Your Go-To Programming Language for Machine Learning appeared first on Coding Infinite.

]]>
10 Best Python Books for Absolute Beginners https://codinginfinite.com/10-best-python-books-beginners/ https://codinginfinite.com/10-best-python-books-beginners/#comments Thu, 24 Oct 2019 18:32:09 +0000 https://codinginfinite.com/?p=3747 Python is a powerful programming language. It is easy to learn. It has efficient high-level data structures with a simple and effective approach for object-oriented programming. Python is a general-purpose interpreted language. It can be used for machine learning, web development, data analysis, and stats. The knowledge imparted by a book and official documentation is...

The post 10 Best Python Books for Absolute Beginners appeared first on Coding Infinite.

]]>
Python is a powerful programming language. It is easy to learn. It has efficient high-level data structures with a simple and effective approach for object-oriented programming. Python is a general-purpose interpreted language. It can be used for machine learning, web development, data analysis, and stats.

The knowledge imparted by a book and official documentation is authentic than a tutorial. Books provide basic concepts and how to implement them. Different learners have different learning styles. Choose the learning resource which best fits your learning style.

We have compiled a list of easy to read and follow Python books which you can consider for enhancing your knowledge in the area of Python programming. The ordering of books is based on the ease to follow the content. There is no strict placing. You can follow in any order depending on your previous knowledge.

Starting out with PYTHON BY TONY GADDIS

 PYTHON BY TONY GADDIS

Key Features

  • Tony Gaddis is the principal author of the Starting Out With series of textbooks. Tony has nearly two decades of experience teaching computer science courses, primarily at Haywood Community College.
  • Student friendly introduction to Python and programming constructs
  • Designed for novices
  • Each concept is followed by Coding Example
  • Practice Problems and Programming Challenges available at the end of each chapter.
  • Covers the basics, control structures, repetitions, functions, file I/O, Databases, GUI Programming, Object Oriented Programming

Buy Here:

Python Crash Course: A Hands-On, Project-Based Introduction to Programming

 PYTHON CRASH COURSE: A HANDS-ON, PROJECT-BASED INTRODUCTION TO PROGRAMMING

Key Features

  • Fast paced introduction to python
  • Good for quick learners
  • Project based chapters
  • Covers Data Visualization
  • Web Applications in Python brief introduction is given
  • Gives basic knowledge for consuming an API in Python

Buy Here:

Learn Python the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code (Zed Shaw’s Hard Way)

LEARN  PYTHON THE HARD WAY

Key Features

  • Hands-on based book
  • Contains 53 programming exercises
  • Discusses some data structures as well
  • Good for learners with prior Python knowledge

Buy NOw:

Introduction to Computation and Programming Using Python: With Application to Understanding Data (The MIT Press)

INTRODUCTION TO COMPUTATION AND PROGRAMMING USING PYTHON

Key Features

  • Introduces students with little or no prior programming experience to the art of computational problem solving using Python and various Python libraries
  • Enables the students to make productive use of computational techniques
  • Includes Data Science based tools and techniques
  • The book is based on MIT course
  • Recommended book for university students
  • Includes a variety of programming examples

Buy Now:

Intro to Python for Computer Science and Data Science
Learning to Program with AI, Big Data and the Cloud

INTRO TO PYTHON FOR COMPUTER SCIENCE AND DATA SCIENCE LEARNING TO PROGRAM WITH AI, BIG DATA AND THE CLOUD

Key Features

  • Excellent introduction of Python programming languages
  • Contains various sections and case studies
  • Explains advanced topics in Python
  • Discusses the application of Python in NLP, Web, Data Science
  • Comprehensive Book

Buy Now:

Python Programming: An Introduction to Computer Science (3rd Edition)

PYTHON PROGRAMMING: AN INTRODUCTION TO COMPUTER SCIENCE

Key Features

  • Teaches the art of programming in Python
  • Introduces the students to Computer Science, Programming and other concepts using Python
  • Suitable for beginners with no programming know-how
  • Easy to follow code listings

Buy NOw:

Programming in Python 3: A complete introduction to the Python Language

PROGRAMMING IN PYTHON 3: A COMPLETE INTRODUCTION TO THE PYTHON LANGUAGE

Key Features

  • Best for those who are willing to increase their previous knowledge
  • Teaches advanced concepts in an easy way
  • Includes a good mixture of exercises with various difficulty levels
  • Discusses Threading, Networking in good detail

Buy NOw:

Learning with Python: How to Think Like a Computer Scientist

 LEARNING WITH PYTHON: HOW TO THINK LIKE A COMPUTER SCIENTIST

Key Features

  • Divided into 20 Sections
  • Teaches programming in Python from the grass-root level
  • Includes good hands-on examples
  • Easy to follow along

Buy NOw:

Think Python

think python

Key Features

  • A good introduction of Python
  • Case Study based
  • Discusses the difficult topics by chunking them
  • Easy to follow for beginners

Buy Now:


Thank you for reading. If you have read any great book & want to add in the above list, please let us know in the comment section below.

Here’re some more article you might be interested:

— Best Python IDE and Code Editors

— Top 5 Python Web Frameworks to Learn

— Developing Chat Application in Python with Source Code

The post 10 Best Python Books for Absolute Beginners appeared first on Coding Infinite.

]]>
https://codinginfinite.com/10-best-python-books-beginners/feed/ 1
Sending SMS using Python and Twilio API – Tutorial https://codinginfinite.com/sending-sms-using-python-and-twilio-api/ Sun, 22 Sep 2019 19:13:37 +0000 https://codinginfinite.com/?p=3427 Send SMS using Python, we will create a simple GUI to send SMS using Python. We will use the Twilio API to send a message. Twilio is not a free service but they provide a trial account with some credit that we can use to demonstrate how powerful it is. Python is a famous scripting...

The post Sending SMS using Python and Twilio API – Tutorial appeared first on Coding Infinite.

]]>
Send SMS using Python, we will create a simple GUI to send SMS using Python. We will use the Twilio API to send a message. Twilio is not a free service but they provide a trial account with some credit that we can use to demonstrate how powerful it is.

Python is a famous scripting language and we can write scripts to do whatever we want. Python has rich community support due to which we have a huge number of libraries and APIs available to achieve our tasks. This makes Python a versatile and popular language.

In order to get started, we need to make an account in Twilio. Twilio provides communication APIs for SMS, Audio, Video, and Authentication.

Create a Twilio account

Goto Twilio Registration Page. Complete the registration steps by providing the required details.

After creating an account. Head towards the Twilio Console. You will see a page like the following.

Twilio Console View

As I have already taken the trail number, but you will see a Get a Trail Number button. Click on it, get your number. Then you need to copy 3 pieces of information:

  • Account SID
  • Auth Token
  • Trial Number

Save these somewhere else as we will be using it in our code.

Required Libraries

In order to follow along, you need the following libraries:

  • tkinter module (built-in)
  • twilio library

You can install the Twilio library using pip.

pip install twilio

Or you can add this library to your project using PyCharm.

Create pycharm project

  1. Open PyCharm and create a simple Python project.
  2. Goto Files>Settings or press CTRL+Alt+S
  3. Locate Project:[Your-Project-Name] > Project Interpreter
  4. Click on the + button.
  5. In the search bar, type Twilio and install it.

After adding the library, create a file named app.py

Creating GUI for sending SMS

Now that you have created an account on Twilio. Let’s leverage it. Now, we are going to create a simple Tkinter GUI app to send the message. The widgets we are adding to our GUI are:

  • A label to show as the header.
  • Top Frame and Bottom Frame
  • Widget for entering the receiver number
  • Entry widget to write SMS
  • A button to send SMS

Here is the code.

import tkinter
import tkinter.messagebox
from twilio.rest import Client
class SMSGUI:
    def __init__(self):
        #Create root window
        self.root = tkinter.Tk()
        #Set title of root window
        self.root.title("SMS CLIENT")
        #Create top frame
        self.top_frame = tkinter.Frame(self.root)
        #Create bottom frame
        self.bottom_frame = tkinter.Frame(self.root)
        #Create a label
        self.header = tkinter.Label(self.top_frame, text = "SMS Sending App")
        #Pack the label
        self.header.pack(side = 'top')
        #Label for TO number
        self.to = tkinter.Label(self.top_frame, text = "To: ")
        self.to.pack(side = 'left')
        #Create an entry widget for TO: number
        self.toNumber = tkinter.Entry(self.top_frame, width = 20)
        self.toNumber.pack(side = 'left')
        #Create an entry widget
        self.message = tkinter.Entry(self.bottom_frame, width = 150)
        #Create button
        self.send = tkinter.Button(self.bottom_frame, text = "Send SMS", command = self.sendSms)
        #pack message entry and send button
        self.message.pack(side = 'left')
        self.send.pack(side = 'left')
        #pack frames
        self.top_frame.pack()
        self.bottom_frame.pack()
        tkinter.mainloop()

The above given piece of code will create a simple GUI through which we will send SMS.

Adding event listener (Call Back Function) for button

Now that we have created the GUI for our SMS app. Let’s add code to bring it to life. For this, I am writing a method named sendSms. Add the following method to the class SMSGUI.

    def sendSms(self):
        account_sid = 'your-sid'
        auth_token = 'your-auth-token'
        client = Client(account_sid, auth_token)
        msg = str(self.message.get())
        rec = str(self.toNumber.get())
        message = client.messages.create(body=msg,from_='your-trial-number',to= rec
        )
        print(message.sid)
        tkinter.messagebox.showinfo('Success', 'Message sent successfully')

Replace account_sid with your Twilio’s account_sid. Similarly, replace auth_token with your Twilio’s auth token on line # 2 and 3 respectively.
On Line # 5 and line # 6, we get the text from the entry widgets of the message and recipient number by using the entry widget’s get() method. Then, we are using Twilio’s client module’s method to create message. There are three parameters:

  1. body – which represents the body of the message
  2. to – represents the recipient’s phone number. Make sure you use the “to” number as the same number with which you have registered on Twilio. Otherwise, you can verify the number from console first and then use. This limitation is only for a free account.
  3. from – is the number which Twilio has given to you when you have clicked Get a Trial Number.

Demo

Sending SMS

Here is the SMS I have received.

twilio test python

You can see how easy it is to write scripts with Python. Stay tuned for some interesting scripts.

Here’re some more related Articles:

— Best Python IDE and Code Editors

— Make A Command-line Based Image Re-sizer In Python 3 Using Pillow

— Developing Chat Application in Python with Source Code

The post Sending SMS using Python and Twilio API – Tutorial appeared first on Coding Infinite.

]]>
Building a Chatbot in Python using Flask – Tutorial https://codinginfinite.com/chatbot-in-python-flask-tutorial/ https://codinginfinite.com/chatbot-in-python-flask-tutorial/#comments Sun, 22 Sep 2019 12:07:44 +0000 https://codinginfinite.com/?p=3382 In this article, we will build a simple chatbot in Python programming language. The pre-requisites of this article is familiarity with the Flask microframework. Before getting into the development part, let’s see some basics first. What is a chatbot? A chatbot is a computer program which conducts the conversation between the user and a computer...

The post Building a Chatbot in Python using Flask – Tutorial appeared first on Coding Infinite.

]]>
In this article, we will build a simple chatbot in Python programming language. The pre-requisites of this article is familiarity with the Flask microframework. Before getting into the development part, let’s see some basics first.

What is a chatbot?

A chatbot is a computer program which conducts the conversation between the user and a computer by using textual or auditory means. It works as a real-world conversational partner.

You have seen different chatbots in your life Siri, Cortana, Alexa and so forth. As per a review, the chatbot is required to finish around 80% of all work in the coming decades. Presently, chatbots are practically finishing 30% of the tasks. With the expanding boom, it has turned out to be imperative to learn Machine Learning and Artificial Intelligence.

chatbot tasks

The tasks being done by chatbot are like:

  • Present some information
  • Make bookings
  • Make calls etc.

Types of CHatbots

There are two main types of chatbots:

  1. Self Learning Chatbots
  2. Rule-based Chatbots

Self Learning Chatbots

Self learning chatbots use machine learning and artificial intelligence techniques. Such chatbots save the input from the users and use them later.

Rule-based Chatbots

Rule-based chatbots used some predefined set of rules. The responses of the chatbot are based on these rules. It means the solutions such chatbots provide are based on the rules defined.

Chatterbot in python

ChatterBot is a Python’s library for chatbots. Consider the following things when you want to make a chatbot:

  • Who is the target audience?
  • What is the natural language of communication?
  • Provide the responses for the target audience.

Chatterbot is a library in Python which generates responses for the users. It uses a number of machine learning algorithms to produce a variety of responses. It is easy to make chatbots using the Chatterbot library in Python. The chatbot should be designed to be language-independent. It should be trained in multiple languages. The chatbot is trained by the data provided by the user.

WOrking of chatterbot

The chatterbot works in the following manner:

  1. Get the input from the user.
  2. Process the input.
  3. Returns the value that is generated with the highest confidence value.
  4. Return the response to the user.

Training the chatbot

You have made a chatbot. Now, how it would produce the responses that you want. For this, there is a library called chatterbot-corpus. It basically has all the responses. We use it to train the bot. Then, it generates the relevant responses that we want.

Developing a chatbot using flask

We will make a Flask chatbot. Flask is a microframework used for web development. We will follow the process given below:

  1. Make a web app using the flask.
  2. Make a directory for the templates.
  3. Train the bot.
  4. Make conversation with the bot.

Project and Libraries setup

I will be using PyCharm to develop this simple chatbot. Create a Flask project using PyCharm. Following libraries are required:

  • chatterbot
  • chatterbot-corpus
  • pytz
  • sqlite3

You can easily install these libraries by going into File>Settings>Project Interpreter.

I have already written the HTML template and CSS. You can just copy and paste it.

index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="proxy.php?url=https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="proxy.php?url=/static/style.css">
    <script src="proxy.php?url=https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
    <h1 class="jumbotron text-center">Chatterbot in Python using Flask Framework</h1>
<div class="container">
    <div class="row">
        <div class="col-sm-6 offset-sm-3">
            <div id="chatbox" class="border border-success">
                <p class="botText"><span>Hi! I'm Chatterbot</span></p>
            </div>
            <div id="userInput">
                <input id="textInput" class="form-control" type="text" name="msg" placeholder="Type Your Message Here">
                <input id="buttonInput" class="btn btn-success form-control" type="submit" value="Send">
            </div>
        </div>
    </div>

<script>
    function getResponse() {
        let userText = $("#textInput").val();
        let userHtml = '<p class="userText"><span>' + userText + '</span></p>';
        $("#textInput").val("");
        $("#chatbox").append(userHtml);
        document.getElementById('userInput').scrollIntoView({block: 'start', behavior: 'smooth'});
        $.get("/get", { msg: userText }).done(function(data) {
        var botHtml = '<p class="botText"><span>' + data + '</span></p>';
        $("#chatbox").append(botHtml);
        document.getElementById('userInput').scrollIntoView({block: 'start', behavior: 'smooth'});
});
}
    $("#textInput").keypress(function(e) {
    //if enter key is pressed
        if(e.which == 13) {
            getResponse();
        }
    });
    $("#buttonInput").click(function() {
        getResponse();
    });
    </script>
    <script src="proxy.php?url=https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="proxy.php?url=https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
    <script src="proxy.php?url=https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</div>
</body>
</html>

style.css

#textInput {
    border: none;
    border-bottom: 3px solid aqua;
}

.userText {
    color: white;
    font-family: monospace;
    font-size: 17px;
    text-align: right;
    line-height: 30px;
}
.userText span {
    background-color: #009688;
    padding: 10px;
    border-radius: 2px;
}
.botText {
    color: white;
    font-family: monospace;
    font-size: 17px;
    text-align: left;
    line-height: 30px;
}
.botText span {
    background-color: #EF5350;
    padding: 10px;
    border-radius: 2px;
}

And here is the core of the app.

app.py

#imports
from flask import Flask, render_template, request
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer

app = Flask(__name__)
#create chatbot
englishBot = ChatBot("Chatterbot", storage_adapter="chatterbot.storage.SQLStorageAdapter")
trainer = ChatterBotCorpusTrainer(englishBot)
trainer.train("chatterbot.corpus.english") #train the chatter bot for english

#define app routes
@app.route("/")
def index():
    return render_template("index.html")

@app.route("/get")
#function for the bot response
def get_bot_response():
    userText = request.args.get('msg')
    return str(englishBot.get_response(userText))

if __name__ == "__main__":
    app.run()

The above piece of code creates an English language chatbot. It is trained for the language English. The chatterbot has knowledge about literature, money, politics, science, etc. Let’s see a demo.

Chatterbot Demo

Thank you for reading this article, comment below if you find any difficulty.

Here’re some more related Articles:

— Sending Sms Using Python And Twilio API

— Make A Command-line Based Image Re-sizer In Python 3 Using Pillow

— Developing Chat Application in Python with Source Code

The post Building a Chatbot in Python using Flask – Tutorial appeared first on Coding Infinite.

]]>
https://codinginfinite.com/chatbot-in-python-flask-tutorial/feed/ 3
Creating GUI Application in Python – TKINTER Tutorial https://codinginfinite.com/gui-application-in-python-tkinter-tutorial/ Sat, 21 Sep 2019 13:07:17 +0000 https://codinginfinite.com/?p=3332 Graphical User Interface A GUI (pronounced like “gooey”) allows the user to interact with the operating system using graphical elements such as icons, buttons, dialog boxes, inputs, etc. The interactions with GUI are mostly done with the help of small windows called dialog boxes. One part of the user interface consists of hardware devices such...

The post Creating GUI Application in Python – TKINTER Tutorial appeared first on Coding Infinite.

]]>
Graphical User Interface

A GUI (pronounced like “gooey”) allows the user to interact with the operating system using graphical elements such as icons, buttons, dialog boxes, inputs, etc. The interactions with GUI are mostly done with the help of small windows called dialog boxes. One part of the user interface consists of hardware devices such as mouse and keyboard. The other part of the user interface is the way the computer’s operating system accepts commands from the user. Interactive programs use GUI to take input from the user and display output.

The other way to interact with the computer’s operating system is by using commands. The user types the command in order to interact. It is done with the help of Command Line Interface (CLI).

Three Components of GUI Programming

There are mainly three components or fundamentals of GUI programming in Python:

  1. What to place on the screen? (Widgets)
  2. Where to place on the screen? (Geometry Management)
  3. How do widgets work? (Events and callback functions)

These three components are the core of making a simple GUI app in Python.

Let’s start learning how to develop GUI apps in Python.

Python’s tkinter module

Python provides a library to create GUI programs. tkinter is one of the libraries which provides a number of graphical components to implement GUI based programs. It is a library which means the Python language does not have GUI features built into the language, however, it is provided through a library.

In a GUI program, there is a window with various graphical widgets/components with which the user can interact. The Tkinter module provides 15 such components.

Tkinter Widgets

WidgetDescription
ButtonA button performs action when clicked
CanvasCanvas is a rectangular area which is used to display graphics
EntrySinglie line input widget
FrameActs as a container to hold other widgets
LabelDisplays line of text or an image. It is a read only widget, a user cannot interact with it
ListboxIt is a list from which user can select an item
MenuA list of menu choices. It is displayed when the user clicks the Menubutton widget
MenubuttonA menu displayed on the screen. and can be clicked by the user.
Message Message widget displays multiple textual lines
RadiobuttonActs as a switchthat can be either selected or deselected
ScaleA slider to select a value by sliding along the track
ScrollbarProvides the scrolling ability
TextMultiple lines text input widget
ToplevelA container which is displayed in its own window

Root Window – Simplest GUI

The root window is just like a piece of paper on which you can draw graphical objects. The actual UI construction is pretty standardized. You create a root window, add widgets and then add functionality to widgets. Let’s bisect it in a bit more detail.

Following are the steps you are required to follow:

  1. Create a root window
  2. Add widgets to the root window
  3. Customize widgets
  4. The geometry of the widgets
  5. Bind event handlers to widget events
  6. Start the main event loop

Creating an empty window

Creating an empty window or root window or main window is very simple.

import tkinter
def main():
    #Create a root window
    root = tkinter.Tk()
    #Call the event loop
    root.mainloop()
#Call the function main
main()

The above-given piece of code will display the following output:

GUI Application in Python
The main window/root window – Empty GUI

Let’s dissect the code line by line.

  • On line # 1, there is an import statement which imports Python’s tkinter module. It imports all the methods, classes, and attributes of tkinter module into the current workspace.
  • Then we defined a function named main() on line # 2.
  • Inside the function’s body, on line # 4, we created an instance of tkinter’s Tk class which is a root window and assigned it to the variable root. Simply speaking, it is Tk class’s constructor method to create the main window.
  • Line # 6 executed the mainloop function. This function runs like an infinite loop until you close the main window.

Adding widgets to root window

We have created our main or top-level or root window. Now we’ve to add components within it. These components, as previously described, are called Widgets. The basic syntax of creating widgets is as follows:
Syntax:
<var_name for widget> = WidgetName(its container window, its configuration options)

Adding a button

In this example, we will add a button to the root window/frame.

import tkinter

def main():
    #Create a root window
    root = tkinter.Tk()
    #Call the event loop
    root.mainloop()
    #create a button widget
    button = Button(root, text = "Click Me")
    button.pack()

#Call the function main
main()

button = tkinter.Button(root,text = “Click Me”)

button.pack()

Line#1: The code added a new instance(for the sake of simplicity I will call it an object) named button for the Button widget. The first parameter defined root as its container. The second parameter is a configuration parameter which configured its text option as “Click Me”

Line#2: We used the pack() method which is required to position the button widget within the window. A widget created must be packed.

Adding functionality to a button

We will write a callback function to add behavior to our button. A callback function is also known as an event handler because it handles the event that occurs when the user clicks the button.

After writing the event handler or callback function, we register it with the button. We provide one more configuration option while creating a button.

#callback function
def do_something():
    #the following line of code show messagebox
    tkinter.messagebox.showinfo('Response', 'You have clicked the button')
#create button
#add one more configuration option
#command = yourCallBackFunctionName
button = tkinter.Button(root, text = "Click Me", command = do_something)

Display Text with labels

You can use the Label widget to display text. Consider the following piece of code:

import tkinter

def main():
    #create the root window
    root = tkinter.Tk()
    #Create the label widget
    label = tkinter.Label(root, text = 'Hello World')
    another_label = tkinter.Label(root, text = 'This is GUI')
    #Call the pack method
    label.pack()
    another_label.pack()
    #enter the main loop
    tkinter.mainloop()

main()

The above code creates a label in the root window. pack() method accepts an optional argument named side. You can specify the side for the widget.

Organizing widgets using frames

A Frame acts like a container that can hold other widgets. You can use frames to organize the widgets in a window.

import tkinter

def main():
    #create root window
    root = tkinter.Tk()
    #Create two frames
    #One frame for the top of the window
    #Another frame for bottom of the window
    top_frame = tkinter.Frame(root)
    bottom_frame = tkinter.Frame(root)
    #Create three labels
    label1 = tkinter.Label(top_frame, text = 'This label is in top frame')
    label2 = tkinter.Label(top_frame, text = 'This label is in top frame')
    label3 = tkinter.Label(top_frame, text = 'This label is in top frame')

    #pack the labels that are in top frame
    #use side = 'top' to stack them on top of each other
    label1.pack(side = 'top')
    label2.pack(side = 'top')
    label3.pack(side = 'top')

    #create three labels for bottom_frame
    label4 = tkinter.Label(top_frame, text = 'This label is in bottom frame')
    label5 = tkinter.Label(top_frame, text = 'This label is in bottom frame')
    label6 = tkinter.Label(top_frame, text = 'This label is in bottom frame')

    #pack the labels that are in top frame
    #use side = 'left' to arrange them horizontally from left to right
    label4.pack(side = 'left')
    label5.pack(side = 'left')
    label6.pack(side = 'left')

    #Now pack the frames also
    top_frame.pack()
    bottom_frame.pack()

    tkinter.mainloop()
main()

The above given code is explained line by line in the comments. It would produce the following output:

Python gui
Organizing content with frames

Getting input with the entry widget

An Entry widget is a rectangular area that the user can type input into. You use the Entry widget’s get method to retrieve the data that has been typed into the widget.

We will create a simple Kilometers to Miles converter app. We will use object-oriented approach to create this app.

import tkinter
class KiloConverter:
    def __init__(self):
        #create root window
        self.root = tkinter.Tk()
        #Create two frames
        #One frame for the top of the window
        #Another frame for bottom of the window
        self.top_frame = tkinter.Frame(self.root)
        self.bottom_frame = tkinter.Frame(self.root)
        #Create two labels
        self.prompt_label = tkinter.Label(self.top_frame, text = 'Enter distance in Kilometers: ')
        self.entry = tkinter.Entry(self.top_frame, width = 10)
        #Pack top frame widgets
        self.prompt_label.pack(side = 'left')
        self.entry.pack(side = 'left')
        #Create the button widgets
        self.calc_button = tkinter.Button(self.bottom_frame, text = 'Convert', command = self.convert)
        #root.destroy exits/destroys the main window
        self.quit_button = tkinter.Button(self.bottom_frame, text = 'Quit', command = self.root.destroy)
        #Pack the buttons
        self.calc_button.pack(side = 'left')
        self.quit_button.pack(side = 'left')
        
        #Now pack the frames also
        self.top_frame.pack()
        self.bottom_frame.pack()

        tkinter.mainloop()
        #This method converts kilometers into miles
    def convert(self):
        kilo = float(self.entry.get())
        miles = kilo * 0.6214
        tkinter.messagebox.showinfo('Results', str(kilo)+ ' kilometers is equal to ' + str(miles) + ' miles')
gui = KiloConverter()      

The convert method is the Convert button’s callback function. The statement in line 32 calls the entry widget’s get method to retrieve the data that has been typed into the widget. The value is converted to a float and then assigned to the kilo variable. The calculation in line 33 performs the conversion and assigns the results to the miles variable. Then, the statement in lines 34 through 35 displays the info dialog box with a message that gives the converted value.

These are some of the basics of GUI in Python.

Here’re some more related Articles:

— Best Python IDE and Code Editors

— Building A Chatbot In Python Using Flask

— Developing Chat Application in Python with Source Code

The post Creating GUI Application in Python – TKINTER Tutorial appeared first on Coding Infinite.

]]>
Make A Command-line based Image Re-sizer in Python 3 using Pillow https://codinginfinite.com/command-line-based-image-re-sizer-python-3-pillow/ Sat, 21 Sep 2019 04:51:21 +0000 https://codinginfinite.com/?p=3361 Python is a general-purpose programming language. It is so popular in software developers and has a vast number of plugins available to play with. It has a huge community to support new learners. In this article, we will see one of its plugin called “Pillow”. Pillow is an Imaging Library used o work with images,...

The post Make A Command-line based Image Re-sizer in Python 3 using Pillow appeared first on Coding Infinite.

]]>
Python is a general-purpose programming language. It is so popular in software developers and has a vast number of plugins available to play with. It has a huge community to support new learners.

In this article, we will see one of its plugin called “Pillow”. Pillow is an Imaging Library used o work with images, such as resizing, applying filters and playing with colours in the image. We’ll develop a small, command-line based application which will able to resize all the images in a folder. The user will have the choice to pass different arguments while running the application, the choice to save resized images as a copy or to replace the original files and the choice to choose the type of resize from simple resize or force resize. The force resize is used when the size of the original image is less than the new resize, in this case, we will simply make an empty image with a background of white colour and then paste the original image on it. Now, let’s start developing.

We will use Python 3 to develop our application. Either version of Python 3 will work but I will recommend you to use the Python 3.6 as it is the most stable version of Python 3, but the latest version Python 3.7.2 (at the time of writing) should work flawlessly. If you have not already installed the Python 3, then first download and install it. Make sure you have set up the path for the language. The Pillow is not bundled with Python and we have to install it manually using pip. The pip is the package manager which install along with the Python. To download Pillow, open command line and type pip install pillow, wait for few seconds and let it install. Now we are ready to actually develop our application.

Make a new folder somewhere on your PC or Mac. Now open your favourite text editor or IDE and save a blank file, let’s name it script.py, also create a new folder with name images inside the folder which contains the script file.

Now, let’s define our command-line arguments which we will use while running our application. The application will have five command-line parameters. The first parameter will be the program file name (script.py is our case), the second parameter will be used for mode, there will be two types of mode, the first is replace, which will replace the resized images with the original images, the second is copy, which will save the resized images with a prefix “resized”, the third parameter will be used for type, there will be two types, one is normal which means that the program will simply resize the images and will skip those images which will have less size than passed by user as parameter, the second will be forced, which will paste the image on a blank background to match the size passed by user, the fourth and fifth parameter will be used for width and height respectively. See the examples below of passing command-line arguments to the application.

General syntax: “python name-of-script mode type width length”
Example 1: “python script.py copy normal 1600 1200”
Example 2: “python script.py replace forced 1024 768”

Let’s start writing the code now, we will need three imports in our script, the “import os” which will be used to work with directories and files, the “import sys” which will be used to work with the command line arguments and  “from PIL from Image” which will be used to work with images.

Next, we have to check if the number of parameters is exactly five in length. For this, we will use the built-in “len” function of Python. The following lines of code will import three libraries we discussed above and also checks if the length of the parameter is five in length.

import os
import sys
from PIL import Image
arg_param_valid = True
if len(sys.argv) != 5:
arg_param_valid = False

Now, we will take the command-line parameters in different variables. Also, we have to tell the application that in which folder our images are placed.

if arg_param_valid:
arg_mode = sys.argv[1]
arg_type = sys.argv[2]
arg_width = int(sys.argv[3])
arg_length = int(sys.argv[4])
folder = "./images"

As you can see, I have taken the mode from command-lines first index, because the name of the script is in 0th index, and we don’t want the name. The 6th line is telling the application that our images are placed in the images folder.

Now, see the following lines of code.

for file in os.listdir(folder):
newName = file
if arg_mode == "copy":
newName = "resized_" + file
current_file = os.path.join(folder, file)
current_image = Image.open(current_file, 'r') 
current_image_width, current_image_height = current_image.size
current_file = os.path.join(folder, newName)

Here is the explanation of the above lines. The first line is used to loop on all files placed in the images folder. The second line is to get the name of the current file in “newName” which is currently being processed. The third line is checking if the mode is “copy“, if so, then it will add the prefix “resized” to the “newName”. The fifth line is to get the relative path of the image being processed, the sixth line is opening the current image, the seventh line is getting the width and height of the image, and lastly, the eighth line is updating the current_file to reflect the change in newName if the mode is “copy“.

It is now time to apply actual magic. The following lines of code will normally resize or forced resize the images.

if arg_type == "normal":
if arg_width <= current_image_width and arg_length <= current_image_height:
save_normal(arg_width, current_image_width, arg_length, current_image_height, current_file)

The above code is checking that if the type is normal, then simply resize and save the image after verifying if the width and height we passed as command-line arguments is equal or less than the width and height of the image. We have to make this check because we will not forcibly resize the images in normal mode. We will do this in forced mode. The following is the implementation of “save_normal” method.

def save_normal(arg_width, current_image_width, arg_length, current_image_height, current_file):
new_image = current_image.resize((arg_width,arg_length), Image.ANTIALIAS)
new_image.save(current_file)

The method is simply resizing the image and then save it. The Image.ANTIALIAS is used to tell the resize method to save as best possible quality. You can read further about it here. Make sure to write this method just below the from PIL import Image.

The following lines will process the forced mode. Write then just below the 

if arg_type == "normal":
elif arg_type == "forced":
if arg_width <= current_image_width and arg_length <= current_image_height:
save_normal(arg_width, current_image_width, arg_length, current_image_height, current_file)
else:
save_forced(arg_width, current_image_width, arg_length, current_image_height, current_file)

The if-part is exactly the same as normal mode. We just have to see the else-part here. Write the implementation of “save_forced” just below the “save_normal” method.

def save_forced(arg_width, current_image_width, arg_length, current_image_height, current_file):
new_image = Image.new('RGB', (arg_width, arg_length), (255, 255, 255, 255))
offset = ((arg_width - current_image_width) // 2, (arg_length - current_image_height) // 2)
new_image.paste(current_image, offset)
new_image.save(current_file)

The method above is simply making a blank image with white background, calculating the centre of this newly created blank image and then pasting our image which we want to resize in the centre, then simply save it. The complete code is written below.

import os
import sys
from PIL import Image

def save_normal(arg_width, current_image_width, arg_length, current_image_height, current_file):
new_image = current_image.resize((arg_width,arg_length), Image.ANTIALIAS)
new_image.save(current_file)

def save_forced(arg_width, current_image_width, arg_length, current_image_height, current_file):
new_image = Image.new('RGB', (arg_width, arg_length), (255, 255, 255, 255))
offset = ((arg_width - current_image_width) // 2, (arg_length - current_image_height) // 2)
new_image.paste(current_image, offset)
new_image.save(current_file)

arg_param_valid = True
if len(sys.argv) != 5:
arg_param_valid = False
if arg_param_valid:
arg_mode = sys.argv[1]
arg_type = sys.argv[2]
arg_width = int(sys.argv[3])
arg_length = int(sys.argv[4])
folder = "./images"
for file in os.listdir(folder):
newName = file
if arg_mode == "copy":
newName = "resized_" + file
current_file = os.path.join(folder, file)
current_image = Image.open(current_file, 'r') 
current_image_width, current_image_height = current_image.size
current_file = os.path.join(folder, newName)

if arg_type == "normal": 
if arg_width <= current_image_width and arg_length <= current_image_height:
save_normal(arg_width, current_image_width, arg_length, current_image_height, current_file)
elif arg_type == "forced":
if arg_width <= current_image_width and arg_length <= current_image_height:
save_normal(arg_width, current_image_width, arg_length, current_image_height, current_file)
else:
save_forced(arg_width, current_image_width, arg_length, current_image_height, current_file)
else:
print("The length of parameter is not valid.")

Now, we will look into all four possibilities to run the application.

I have placed 4 wallpapers and two logos in the images folder.

python image resize 1

1. python script.py copy normal 1024 768

The output of folder after running:

python image resize 2

You can see that the logos are not resized because their resolution is less than the resolution we passed as the argument.

2. python script.py copy forced 1024 768
The output of folder after running:

python image resize 3

You can see that the logos are forcibly resized.

3. python script.py replace normal 1024 768
The output of folder after running:

python image resize 4

You can see that wallpapers are resized and replaced the original images, but logos are not resized.

4. python script.py replace forced 1024 768
The output of folder after running:

python image resize 5

You can see that the images are replaced along with the two logos.
This is the end of the article, see you in the next python article.

Here’re some more related Article:

— Best Python IDE and Code Editors

— Developing Chat Application in Python with Source Code

— Top 5 Python Web Frameworks to Learn

The post Make A Command-line based Image Re-sizer in Python 3 using Pillow appeared first on Coding Infinite.

]]>
Database Constraints in SQLite using Python Code by Querying https://codinginfinite.com/database-constraints-sqlite-python-querying/ Wed, 04 Sep 2019 05:58:55 +0000 https://codinginfinite.com/?p=3220 This article is the continuation of the previous article in which we have seen how to create and query a simple database. In this article, we will learn the following: Database Constraints in SQLite (PRIMARY KEY, NOT NULL, UNIQUE, FOREIGN KEY) Querying Database We will follow the following relational schema to create the database. Create...

The post Database Constraints in SQLite using Python Code by Querying appeared first on Coding Infinite.

]]>
This article is the continuation of the previous article in which we have seen how to create and query a simple database. In this article, we will learn the following:

  1. Database Constraints in SQLite (PRIMARY KEY, NOT NULL, UNIQUE, FOREIGN KEY)
  2. Querying Database

We will follow the following relational schema to create the database.

relational schema to create the database

Create Database

As we have learnt in the previous article, first of all we will create a database.

import sqlite3
conn = sqlite3.connect('company.sqlite ')

Before creating our tables, let’s see how to define primary and foreign keys in SQLite.

Primary Key in SQLite

A primary key is defined as a column or a combination (group) of columns which is used to uniquely identify a row in a table.

Each table can have only one primary key. The primary key column must not contain NULL values. It means that the primary key column has an implicit NOT NULL constraint.

How to define primary key in SQLite?

There are two ways to define primary key in SQLite:

Column Constraint

If the table has only one column which is to be defined as a primary key, then you can use the PRIMARY KEY column constraint to define the primary key.

CREATE TABLE tableName(
	column_1 NOT NULL DATATYPE PRIMARY KEY,
	...
);

Table Constraint

If the primary key consists of more than 1 columns, then you use the table constraint PRIMARY KEY to define the primary key.

CREATE TABLE tableName(
	column_1 NOT NULL DATATYPE,
	column_2 NOT NULL DATATYPE,
	...
	PRIMARY KEY(column_1, column_2,…)
);

Foreign Key in SQLite

In order to link two or more tables based on column or group of columns in a database, the foreign key constraint is used. It works as a cross-reference between tables because it references the primary key of another table which actually establishes the link between the tables.

How to define foreign key constraint in SQLite?

In order to define the foreign key, we use the FOREIGN KEY constraint.

Syntax

After defining the columns of the table columns we define the foreign key constraint.

CREATE TABLE tableName(
	…
	FOREIGN KEY (column_name) REFERENCES table2_name (column_2_name)
);

NOT NULL Constraint

NOT NULL constraint is used to prevent a column for having NULL value.

column_name dataType NOT NULL,

DEFAULT Constraint

DEFAULT constraint is used to insert a default value in the column if the value is not provided.

Syntax

column_name dataType DEFAULT DEFAULT_VALUE,

CHECK Constraint

CHECK constraint is used to add a condition for value to be inserted. If the inserted value satisfies the condition then the value will be inserted, otherwise, it won’t be inserted.

Syntax

column_name dataType CHECK(condition),

Now that we have seen some of the constraints. Let’s create our tables as described in the schema figure.

Create Tables

First of all, create the table department, which has three attributes, name of the department, department number as primary key, and manager’s ssn (we will add this column later in order to learn how to alter table).

#Before creating table, drop if it exists
cur.execute('DROP TABLE IF EXISTS department')
#Create table department
cur.execute("""CREATE TABLE department
    (
	name TEXT NOT NULL,
 	deptno INTEGER NOT NULL PRIMARY KEY
    )
""");

As you can see in the code above, deptno is the primary key. This is how we define a single column (column level) primary key.

Now, we create an employee table.

#Before creating table, drop if it exists
cur.execute('DROP TABLE IF EXISTS employee')

#Create table department

cur.execute("""CREATE TABLE employee
	(
		name TEXT NOT NULL,
		ssn TEXT NOT NULL PRIMARY KEY,
		bdate TEXT,
		address TEXT,
		salary INTEGER CHECK(salary > 1000),
		dno INTEGER NOT NULL,
		FOREIGN KEY (dno) REFERENCES department (deptno)
	)
   """);

In the code snippet above, two new constraints are added. CHECK constraint is added on salary column. It means that the value of the salary must be greater than 1000. And FOREIGN KEY constraint is added. dno is a foreign key in the table employee which references the department number (deptno) in the department table.

Now, we create the deptlocations table. In deptlocations table, there is a composite primary key, a primary key which is a combination of two or more columns and is defined as a table-level constraint.

#Before creating table, drop if it exists
cur.execute('DROP TABLE IF EXISTS deptlocations')

#Create table deptlocations
cur.execute("""CREATE TABLE deptlocations
	(
		dnumber INTEGER NOT NULL,
		dlocation TEXT NOT NULL,
		PRIMARY KEY (dnumber, dlocation),
		FOREIGN KEY (dnumber) REFERENCES department (deptno)
	)
""");

Now, the rest of the tables are created.

#Before creating table, drop if it exists
cur.execute('DROP TABLE IF EXISTS project')

#Create table project
cur.execute("""CREATE TABLE project
	(
		pname TEXT NOT NULL,
		pnumber INTEGER NOT NULL,
		plocation TEXT NOT NULL,
		dnum INTEGER NOT NULL,
		PRIMARY KEY (pnumber, plocation),
		FOREIGN KEY (dnum) REFERENCES department (deptno)
	)
""");

#Before creating table, drop if it exists
cur.execute('DROP TABLE IF EXISTS works_on')

#Create table works_on
cur.execute("""CREATE TABLE works_on
	(
		essn TEXT NOT NULL,
		pno INTEGER NOT NULL,
		hour INTEGER NOT NULL,
		PRIMARY KEY(essn,pno),
		FOREIGN KEY (essn) REFERENCES project (employee),
		FOREIGN KEY (pno) REFERENCES project (pnumber)
	)
""");

One last thing, now we want to ALTER our department table to add new column mgr_ssn as shown in the schema.

cur.execute("""ALTER TABLE department
          ADD COLUMN mgr_ssn TEXT REFERENCES employee(ssn);
""");

Now that we have created the database using the DDL (Data Definition Language), you can read the previous article (Getting Started with SQLite with Python) to see how to insert and query data.


— Best Python IDE and Code Editors

— Developing Chat Application in Python with Source Code

— Top 5 Python Web Frameworks to Learn

The post Database Constraints in SQLite using Python Code by Querying appeared first on Coding Infinite.

]]>
Best Python IDE and Code Editors | Top 10 https://codinginfinite.com/best-python-ide-code-editors-top-10/ https://codinginfinite.com/best-python-ide-code-editors-top-10/#comments Sun, 01 Sep 2019 19:05:04 +0000 https://codinginfinite.com/?p=3196 As a developer, we always like to choose the best thing among several choices available, especially in the case of Integrated Development Environments (IDEs). Usually, developers and programmers get confused in choosing the best and most suitable IDE or Editor for them. In this article, we will go through some of the best IDEs available...

The post Best Python IDE and Code Editors | Top 10 appeared first on Coding Infinite.

]]>
As a developer, we always like to choose the best thing among several choices available, especially in the case of Integrated Development Environments (IDEs). Usually, developers and programmers get confused in choosing the best and most suitable IDE or Editor for them. In this article, we will go through some of the best IDEs available for Python.

IDE

IDE stands for Integrated Development Environment. It is a Graphical User Interface (GUI) based software which allows the programmers to write, debug, release, and deploy their code. An IDE with minimal functionality consists of at least a source code editor, build tools, and a debugger. An IDE combines all essential tools needed for software development and testing which helps the programmer to produce good output.

Common Features of IDE

1. Code Editor – Code Editor is NOT and IDE

Many of the programmers and specifically the naïve ones do not know the difference between a code editor and an IDE. The code editor is an application that enables the programmer to write and manipulate the source code. Code Editor can also be a standalone application like Brackets, Sublime Text; visual editors like NoviBuilder or they are integrated into IDEs. The code editor only supports the feature of editing the text. On the other hand, IDE is a complete environment where you can create, test and deploy software applications.

2. Syntax Highlighting

Another feature of IDEs is syntax highlighting. Syntax highlighting means that the editor displays the text, more specifically, the source code in different colors according to the programming language being used. It highlights the reserved words in some specific color, function names in some other color and so on. Syntax highlighting is very useful, especially for the beginner programmers. Visual learners find it very useful for remembering the syntax.

3. Auto-Completion / Code Completion

Auto-completion feature, as you have most probably seen in your mobile phones, is used to minimize the time consumption while writing the code. Code completion is for the assistance of a programmer. It identifies and inserts common code components intelligently.

4. Debugger

Debugging is the process of finding and removing bugs from a program. Debugger feature of IDE allows the tester/programmer to test and debug the source code.

5. Compiler

Compilers translate the source code from one language to another. IDEs also contains compilers. 

6. Language Support

Some IDEs support specific language whereas there are other IDEs available with multi-language support.

Now that you know the basic features of an IDE. Let us dive into the best IDEs available for Python.

Top 10 IDEs for Python

10. IDLE

IDLE is a cross-platform open-source IDE which comes by default with Python. IDLE is completely written in Python. IDLE name is used to honour Eric Idle who was one of the founding members of Monty Python, the television show liked by the creator of Python language Guido Van Rossum.

IDLE is simple to use. It is suitable for educational purposes.

IDLE ide

Features

  • Python shell with syntax highlighting
  • Breakpoints
  • Call stack’s clear visibility
  • Multi-window text editor
  • Stepping

Price

Free of cost (Open-Source)

9. Thonny

Thonny is an IDE developed for beginners. It provides assistance to the beginner.

THONNY ide

Features

  • Easy for beginners
  • Visualize variables to see how they change when a program executes
  • Line numbers are available
  • Simple debugger
  • Step through expression evaluation
  • Visualize the function calls
  • Syntax Highlighting
  • Step by step assistance

Price

Open-source

8. Eric Python

Eric Python IDE is full-featured IDE. It is a cross-platform IDE written in Python. Source code of Eric Python is available freely and can be studied and re-created by anyone.

ERIC PYTHON ide

Features

  • Configurable Window Layout
  • Application diagrams
  • Error Highlighting
  • Code folding
  • Class browser available
  • Visualize the function calls
  • Syntax Highlighting
  • Step by step assistance

Price

Open-source

7. Atom

Atom is an open-source cross-platform IDE. It is a desktop application built using web technologies. It is based on a framework built by GitHub named Electron.

ATOM ide

Features

  • Enables support for third-party packages
  • Embedded Git Control
  • Multi Programming Language support
  • Allows installation of packages
  • Package Management
  • Exception reporting package
  • Smart auto-completion
  • Syntax Highlighting
  • Multiple panes

Price

Open-source

6. Wing

The Wing is a cross-platform IDE created by Wingware. It is a lightweight IDE. It is designed to allow quick programming. There are three variants of Wing:

  1. Wing Pro
  2. Wing Personal
  3. Wing 101

Wing Pro is a professional version priced between $95 – $179.

Wing Personal and Wing 101 are simplified free versions available for educational purpose and beginners.

WING ide

Features

  • Automatic multi-process and child process debugging
  • Remote debug process
  • Module browser
  • Refactoring
  • Auto-completion for non Python files also
  • Customizable
  • Extensible
  • Remote development support
  • Syntax highlighting

Price

$95 – $179 Wing Pro

5. Sublime Text

SUBLIME TEXT is a cross-platform IDE that costs $80. It is developed in C++ and Python.

SUBLIME TEXT ide

Features

  • API and Package System
  • Multiple Panes
  • Goto Anything feature
  • Python-based plugin API
  • Allows simultaneous editing (multiple selections)
  • Command Palette
  • Easily Customizable
  • Good Performance
  • Syntax Highlighting

Price

$80

4. Rodeo

Rodeo is an open-source cross-platform IDE for Python. It highly supports Data Science related tasks.

RODEO ide

Features

  • Very easy to load and compare data
  • Data Experimentation
  • Built-in Python Tutorials
  • Cheat sheets are available
  • Easy to use file and package search
  • Simple and lightweight
  • Smart auto-completion
  • Syntax Highlighting
  • Command history

Price

Open-source

3. PyDev

PyDev is an open-source cross-platform third-party package which serves as a plugin for Eclipse IDE. PyDev turns Eclipse for Python development.

PYDEV ide

Features

  • Remote debugger
  • Code Folding (Selectively hide or display sections of code) 
  • Support for Python 2.x and 3.x syntax
  • Error description on hovering
  • Auto-edit feature
  • Plug-in for Eclipse
  • Smart auto-completion
  • Syntax Highlighting

Price

Open-source

2. Spyder

Spyder is an open-source cross-platform IDE designed for data analysis and data science. It is a powerful scientific development IDE written in Python.

SPYDER ide

Features

  • Integrated with many of the scientific libraries of Python
  • Advance support for editing, analysis and data exploration
  • Static code analysis
  • Plug-in system and API help to enhance features
  • Dynamic code introspection
  • Class and function browser
  • Integrated pylint code analysis
  • Debugger
  • Syntax Highlighting

Price

Open-source

1. PyCharm

PyCharm is a cross-platform IDE developed by JetBrains. It comes in two versions:

  1. Community Version (Free)
  2. Professional Version ($199/User)

PyCharm is considered one of the best IDEs due to its remarkable features. It is most widely used.

PYCHARM ide

Features

  • Intelligent Assistance for Code
  • Scientific tools are available
  • Quick switching between files
  • Facilitates Web Developer and Web Development
  • There are more than 1000 plug-ins available
  • Allows the programmer to write own plug-ins
  • Customizable
  • Syntax Highlighting
  • Built-in developer tools

You can read more about Pycharm features on this link.

Price

  1. Community Version (Free)
  2. Professional Version ($199/User)

Comparison Table

Features IDLE Thonny Eric Python Atom Wing Sublime Rodeo PyDev Spyder PyCharm
Code Completion ✔ ✔ ✔ ✔ ✔ ✔ ✔ ✔ ✔
Debugging ✔ ✔ ✔ Package Available ✔ Package Available Remote Debugger ✔ ✔
Built-in Unit Testing ✔ Package Available ✔ Package Available ✔ Plugin ✔
Open Source ✔ ✔ ✔ ✔ ✔ ✔ ✔ Community Edition
Light Weight ✔ ✔ ✔ ✔ ✔ ✔
Refactoring Package Available ✔ Package Available ✔ ✔ ✔

Thanku for reading. We’ll love to know your IDE choice in the comment section below.

Here’re some more Articles, you might be interested:

— Top 5 Python Web Frameworks to Learn

— Developing Chat Application in Python with Source Code

— File I/O in Python – Read and Write Files Tutorial

The post Best Python IDE and Code Editors | Top 10 appeared first on Coding Infinite.

]]>
https://codinginfinite.com/best-python-ide-code-editors-top-10/feed/ 3
Python SQLite Tutorial – Creating Simple Query with Code Example https://codinginfinite.com/python-sqlite3-tutorial-database-operations-examples/ Mon, 29 Jul 2019 18:21:47 +0000 https://codinginfinite.com/?p=2953 In this article, we will start learning to work with a Database using Python. Every useful application either, it is a desktop application, mobile application, or web application, uses some sort of database for the storage and retrieval of the data. In our previous article, we saw that we can achieve data persistence using files...

The post Python SQLite Tutorial – Creating Simple Query with Code Example appeared first on Coding Infinite.

]]>
In this article, we will start learning to work with a Database using Python. Every useful application either, it is a desktop application, mobile application, or web application, uses some sort of database for the storage and retrieval of the data. In our previous article, we saw that we can achieve data persistence using files but it is not the most efficient way. There are many database choices available for Python, but for this series, we will be going to use sqlite3 for a number of reasons:

  • sqlite3 comes with Python. If you have Python installed, it means you have sqlite3. That makes it easy for following the article.
  • sqlite3 is a perfect choice for a wide variety of applications.
  • sqlite3 is reliable, simple, does not require separate database engine
  • sqlite3 is a self-contained, server-less, zero-configuration and fully capable database.
  • Easy to use

What is Database?

A database is a file that is organized for storing the data. It is an organized collection of data used for storing, managing and retrieving information. It is used to persist the data. It is stored on permanent storage.

A database looks like a general spreadsheet with multiple sheets. Three main structures are there:

  1. Tables/Relations
  2. Rows/Tuples
  3. Columns/Attributes
database table example

The yellow highlighted part is called row or tuple.

Creating a Database Table

When we create a database table, we must inform the database in advance the following:

  1. The name of the table
  2. The names of each of the columns in the table
  3. The data type of each of the column in the table

You may see the various available datatypes supported by SQLite by visiting www.sqlite.org/datatypes.html

We will be creating a simple database for this article. The database will keep a record of an Employee. We will capture the employee id, employee name and designation attributes. Let’s start writing the code.

To create a database file and a table named employee with three columns in the database is as follows:

#First of all import sqlite3
import sqlite3
conn = sqlite3.connect('company.sqlite ')

 The connect function makes a connection to the database stored in a file named company.sqlite3 in the current directory. If the file with the same name does not exist in the current directory, then it will be created. For example, after the execution of the above-given statement, the following file will be created.

cur = conn.cursor()
# BEFORE CREATING THE TABLE, DROP IT IF EXISTS
cur.execute('DROP TABLE IF EXISTS employee')
cur.execute('CREATE TABLE employee (empid INT, ename TEXT, designation TEXT) ')
conn.close()

A cursor is just like a file handler that we can use to perform operations on the database. Python provides cursor() function for this purpose to create a cursor for the connected database.

Cursor object has the following four major operations:

  1. xecute()
  2. fetchone()
  3. fetchall()
  4. close()
python cursor function

Once we have the cursor, we can then execute the commands on the database by using the execute() method.

In the above-given code, we are executing 2 SQL (Structured Query Language) commands in our database.

The first command removes the table employee from the database if it already exists.

cur.execute('DROP TABLE IF EXISTS employee')

The second command creates a new table named employees with one INT column and two TEXT columns.

cur.execute('CREATE TABLE employee (empid INT, ename TEXT, designation TEXT) ')

Let’s now create a file named create_database.py that contains the above-given script.

import sqlite3
def main():
	conn = sqlite.connect('company.sqlite')
	cur = conn.cursor()
	cur.execute('DROP TABLE IF EXISTS employee')
	cur.execute('CREATE TABLE employee (empid INT, ename TEXT, designation TEXT) ')
	conn.close()
if __name__ == '__main__': main()

Now that we have created a database with one table. Let’s insert some data in it.

Inserting Data in Database Table

In order to insert data in the table of a database, we will use the SQL INSERT command. The INSERT command is used to insert data (a row/tuple) into a table.

The basic format of INSERT command is:

INSERT  INTO tablename (columns) VALUES (placeholders), (actualvalues)

The INSERT command indicates which table we are using then defines a new row by specifying the fields we want to include followed by the values we want to pass in those fields. We specify the values as a question mark (?,….,?) to indicate that the actual values will be passed as a tuple (value1,…,valueN).

Create a file named insert_data.py

import sqlite3
def main():
	conn = sqlite3.connect('company.sqlite')
	cur = conn.cursor()
	cur.execute('INSERT INTO employee (empid, ename, designation) VALUES (?,?,?)', (210, 'Ahmed', 'Instructor' ))
	
	cur.execute('INSERT INTO employee (empid, ename, designation) VALUES (?,?,?)', (211, 'Kamal', 'Instructor' ))

	cur.execute('INSERT INTO employee (empid, ename, designation) VALUES (?,?,?)', (212, 'Zeeshan', 'Instructor' ))

	cur.execute('INSERT INTO employee (empid, ename, designation) VALUES (?,?,?)', (213, 'Zunaina', 'Instructor' ))

	cur.execute('INSERT INTO employee (empid, ename, designation) VALUES (?,?,?)', (214, 'Qaiser', 'Professor' ))

	cur.execute('INSERT INTO employee (empid, ename, designation) VALUES (?,?,?)', (215, 'Shakeel', 'Assistant Professor' ))
	conn.commit()
	conn.close()

if __name__ == '__main__': main()

In the above piece of code, we have INSERT six rows into our table and use commit() to enforce the data to be written to the database table.  After the execution of the above-given piece of code, the table would look like:

employees database table example

Displaying All Data from a Database Table

In order to display data from a table in a database, SELECT command is used.

SELECT command is used to retrieve the data from a table in the database. It retrieves the rows. Following is the basic structure of SELECT command

SELECT * FROM tablename

The above given general form is used to retrieve all rows with all columns. However, we can choose rows with specific columns to be retrieved for that purpose, the general form is like the following:

SELECT column1,column2,…,columnN FROM tablename

Create a file named, display_data.py in which we will display all rows with all columns.

import sqlite3
def main():
    conn = sqlite3.connect('company.sqlite')
    cur = conn.cursor()
    print('Data')
    cur.execute('SELECT * FROM employee')
    for row in cur:
            print(row)
    conn.close()
if __name__ == '__main__': main()

The output of the above piece of code will be:

python salite database data

Create another file named display_idnames.py. In this, we will write a piece of code to display specific columns.

import sqlite3
def main():
    conn = sqlite3.connect('company.sqlite')
    cur = conn.cursor()
    print('Data')
    cur.execute('SELECT empid,ename FROM employee')
    for row in cur:
            print(row)
    conn.close()
if __name__ == '__main__': main()

The output of the above piece of code will be:

python salite data

In the upcoming article related to database, we will see some more concepts like constraints, projection, selection, where clauses, group functions etc. Stay tuned.


Here’re some more Articles, you might be interested:

— File I/O in Python – Read and Write Files Tutorial

— Developing Chat Application in Python with Source Code

— Top 5 Python Web Frameworks to Learn

The post Python SQLite Tutorial – Creating Simple Query with Code Example appeared first on Coding Infinite.

]]>
File I/O in Python – Read and Write Files Tutorial https://codinginfinite.com/file-input-output-python-read-write-tutorial/ https://codinginfinite.com/file-input-output-python-read-write-tutorial/#comments Thu, 18 Jul 2019 05:40:50 +0000 https://codinginfinite.com/?p=2929 The simple Python programs we write do not use persistent memory. Variables and objects we create in such programs are stored in the volatile memory (RAM). The data is erased when the program is closed. Most of the time, the program needs the data for later use. It must be somehow stored somewhere in the...

The post File I/O in Python – Read and Write Files Tutorial appeared first on Coding Infinite.

]]>
The simple Python programs we write do not use persistent memory. Variables and objects we create in such programs are stored in the volatile memory (RAM). The data is erased when the program is closed. Most of the time, the program needs the data for later use. It must be somehow stored somewhere in the memory. In this tutorial, we will use Files to Read & Write data in Python. Once the data is saved, it can be retrieved and used later.

Basic Terminology related to File I/O

File

A File can be defined as a set of bytes written on the persistent memory, say hard drive. A has two important attributes:

  1. A file has a name
  2. A file has an extension

Writing data to File

The process of saving data in a File is called writing data to the file. When some data from a program is written to a file, then it is copied from RAM (Random Access Memory) to the file which resides in the hard disk. And such a File is called an output file because of the program stores output on it.

In the figure above, we have a file saved on a hard drive named output.txt. Here, the output is the name of the file and .txt is the extension of the file. We have a variable named x and a variable named y that references to the strings “Intel” and “hp” respectively. These variables reside inside RAM. They are written on persistent memory as you can see in the figure.

Reading data from File

The process of retrieving data from the file is called reading data from the file. When some data is read from a File, it is copied from the file stored on persistent memory to RAM. Such a file is called the input file because the program gets the input from it.

As you can see in the above picture, data is copied from File to RAM and stored in variables named x and y.

Common Way to Write Something

In our daily life we use writing pads, registers etc. to note down things. What we do is as follows:

  1. Open a file
  2. Process the file (WRITE / READ)
  3. Close the file

In a similar manner, we process files in programming. Let’s get started.

There are always three steps when we want the program to use a File for input/output.

  1. Open the file: In order to create a connection between a file and the program we open the file. Opening an output file usually creates a file on the disk if it already doesn’t exist and allows the program the write data to it. Opening an input file allows the program to read data from it.
  2. Process the file: At this stage, the program either write to the file or read from the file or can do both depending upon the nature of the program.
  3. Close the file: A file must be closed when a program finished processing it. When we close a file, it gets disconnected from the program.

File Access Methods

There are mainly two ways to access data stored in a file programmatically.

1. Sequential Access

            In sequential access, you access the File data from the beginning of the File to the end of the File. If you need a piece of data that is stored near the end of the file then you have to go through all the data before it i.e. you have to read all the data and you cannot jump directly to the desired data. It is just like a cassette tape player.

2. Direct Access

            Direct access file is also known as random access file. You can directly jump to the desired data without reading the data that comes before it.

In this article, we will use a sequential access file. Sequential access files are easy to handle.

File Object

In order to work with a file in a Python program, you must create a file object. A file object is an object associated with a specific file to work with programmatically.

That’s enough jargon. Let’s start coding.

Opening a File

Python provides open() function to open a fileopen()creates a file object and associates it with a file on your hard drive. The general syntax is:

fileVariable = open(filename, mode)

fileVariable is the name of the variable that references the file object.

filename is a string specifying the name of the file.

mode is a string specifying the mode (read, write etc.) in which file will be opened.

Suppose that we have a file named customers.txt. To open this file following statement is used:

file = open(“customers.txt”) – default mode is read mode

file = open(“customers.txt”, ‘w’) – file opened in write mode

file = open(“customers.txt”, ‘a’) – file opened in append mode

file = open(“customers.txt”, “r+”) – file opened in read-write mode

Once a file is opened then we can read/write/append data to it.

Writing Data to File

In order to write the data to a File open the file in write or append mode. To write the data, you will use the file object and its methods.write() method is used to write data to a file. A file must be closed after performing operations. close() method is used to close the file.

The general syntax is:

fileVariable.write(string)

Example

Suppose we have a file named customers.txt

myFile = open("customers.txt", 'w')
myFile.write("Customer 1  Qaiser  555\n")
myFile.write("Customer 2  Fakhar  556\n")
myFile.close() # this will close the file

The above-given piece of code will write a single line on file. You can write as many time as you want.

After the above-given piece of code runs, the customers.txt file will contain

Writing Records to File

We can also write records to a File. For example, you have listed and you want it to be written on a File. It can be done easily. Create a file writing.py.

#open a file with write mode
file = open("brands.txt",'w')
#We have some list and data of type string
brands = ['Samsung', 'Apple','Nokia', 'Huawei', 'Oppo']
with file as f:
    for i in range(0, len(brands)):
        f.write(brands[i]+"\n")

Python provides a with clause. It ensures that the file gets closed whenever the code inside the with clause executes. When we use with clause, we do not have to call the close() method.

Writing Numeric Data to a file

Strings can be written directly to a File but the numbers must be converted into strings before they can be written. We can use Python’s built-in function str that converts the value to a string.

Create a file called write_numeric_data.py.

def main():
    #Open a file for writing
    outputFile = open("numbers.txt","w")
    
    #Get three numbers from the user
    num1 = int(input("Enter first number:"))
    num2 = int(input("Enter second number:"))
    num3 = int(input("Enter third number:"))
    
    #Wrtie the numbers to file
    outputFile.write(str(num1) + "\n")
    outputFile.write(str(num2) + "\n")
    outputFile.write(str(num3) + "\n")
    
    #Close the file
    outputFile.close()
    print("Data written")
    
#Call the function
main()

Reading Data from File

In order to read the data from the File, we will use the read() method. If the File is opened with ‘r’ access mode then we can read the whole content using read() method.

read() method returns the entire contents of a file as a string.

readLine() method reads an entire line from a file. It returns the line as a string with newline escape character ‘\n’.

Reading All Contents of File

Create a file called read_all.py. Suppose we have a file named users.txt that contains some names.

def main():
    #Open a file for reading
    #the access mode is r
    inputFile = open("users.txt","r")
    
    #read the contents from a file using read method
    data = inputFile.read()
    
    #print the data on console
    print("The Data of file is: \n")
    print(data)
    
    #close the file
    inputFile.close()
    
#Call the function
main()

Reading a whole line

Suppose we have a File with the following data

We can read this data line by line.

Create a file named readlines.py.

#Open a file for reading
    #the access mode is r
    inputFile = open("data.txt","r")
    
    #read the line 
    data = inputFile.readline()
    
    #print line data
    print(data)
    
    #read another line
    data = inputFile.readline()
    
    #print
    print(data)

    #close the file
    inputFile.close()
      
#Call the function
main()

Let’s write a program that reads numbers from a File and write the prime numbers on another File. We have a file named numbers.txt that contains first 2000 consecutive numbers. We will write a naïve function to check whether the number is prime or not. If the number will be prime, we will write it on another file named primes.txt.

Create a file fileio_example.py

#import math library
import math as m
#write a function called isPrime that accepts a number as 
#argument and returns true if the number is prime
#otherwise returns false
def isPrime(number):
    sqrt = int(m.sqrt(number))
    for i in range(2,sqrt+1):
        if(number % i == 0):
            return False
    return True

def main():
    #Open file to read data
    infile = open("numbers.txt", "r")
    
    #output file to store primes
    outfile = open("primes.txt","w")
    
    #iterate through each line in file
    for line in infile:
        num = int(line)
        isprime = isPrime(num)
        if isprime:
            outfile.write(str(num) + '\n')
    
    infile.close()
    outfile.close()
    
main()

Thank you for reading the Tutorial. I hope It will be helpful. Comment If you find any difficulty.

Here’re some more Articles, you might be interested:

— Python Sqlite3 Tutorial – Database Operations With Code Example

— Developing Chat Application in Python with Source Code

— Top 5 Python Web Frameworks to Learn

The post File I/O in Python – Read and Write Files Tutorial appeared first on Coding Infinite.

]]>
https://codinginfinite.com/file-input-output-python-read-write-tutorial/feed/ 1