AI and Deep Learning in Python
Current location: Home > Workshops > AI and Deep Learning in Python

Python 1.1 Tutorial for Beginners

Posted:2019-07-13 20:13:38 Click:5873

What is Python?


Python is one of the preferred programming languages for working in Test Automation, Web Scraping, Data Analytics, and Machine Learning domains.

Python is easy to learn, highly readable, and simple to use. It has a clean and English-like syntax which requires less coding and let the programmer focus on the business logic.

The below sections cover Python history, features, domains, why to learn Python, how to install and run Python on platforms like Windows, Linux, and Mac OS X. It will show you how easy to write and run Python programs.

It also shows you the way to practice and learn Python step-by-step, from simple to advance program.

More importantly, to prepare for your trip to learn AI, Machine Learning and Data Mining using Python.





History Of Python





  • Guido van Rossum is a Dutch programmer best known as the author of the Python programming language, for which he was the "Benevolent dictator for life" until he stepped down from the position in July 2018. He is currently a member of the Python Steering Council.
  • In December 1989, Van Rossum had been looking for a "'hobby' programming project that would keep [him] occupied during the week around Christmas" as his office was closed when he decided to write an interpreter for a "new scripting language he had been thinking about lately: a descendant of ABC that would appeal to Unix/C hackers". He attributes choosing the name "Python" to "being in a slightly irreverent mood (and a big fan of Monty Python's Flying Circus)".
  • He has explained that Python's predecessor, ABC, was inspired by SETL, noting that ABC co-developer Lambert Meertens had "spent a year with the SETL group at NYU before coming up with the final ABC design".
  • In July 2018, Van Rossum announced that he would be stepping down from the position of BDFL of the Python programming language.





Main Features of Python


Code Quality

Python code is highly readable which makes it more reusable and maintainable. It has broad support for advanced software engineering paradigms such as object-oriented (OO) and functional programming.


Developer Productivity

Python has a clean and elegant coding style. It uses an english-like syntax and is dynamically-typed. So, you never declare a variable. A simple assignment binds a name to an object of any type. Python code is significantly smaller than the equivalent C++/Java code. It implies there is less to type, limited to debug, and fewer to maintain. Unlike compiled languages, Python programs don’t need to compile and link which further boosts the developer speed.


Code Portability

Since Python is an interpreted language, so the interpreter has to manage the task of portability. Also, Python’s interpreter is smart enough to execute your program on different platforms to produce the same output. So, you never need to change a line in your code.


Built-In And External Libraries

Python packages a large no. of the pre-built and portable set of libraries. You can load them as and when needed to use the desired functionality.


Component Integration

Some applications require interaction across different components to support the end to end workflows. Onc such component could be a Python script while others be a program written in languages like Java/C++ or any other technology.

Python has several ways to support the cross-application communication. It allows mechanisms like loading of C and C++ libraries or vice-versa, integration with Java and DotNET components, communication using COM/Silverlight, and interfacing with USB devices over serial ports. It can even exchange data over networks using protocols like SOAP, XML-RPC, and CORBA.


Free To Use, Modify And Redistribution.

Python is an OSS. You are free to use it, make amends in the source code and redistribute, even for commercial interests. It is because of such openness that Python has garnered a vast community base which is continually growing and adding value.


Object-Oriented From The Core

Python primarily follows the object-oriented programming (OOP) design. OOP provides an intuitive way of structuring your code, and a solid understanding of the concepts behind it can let you make the most out of your coding. With OOP, it is easy to visualize the complex problem into smaller flows by defining objects and how they correlate. And then we can form the actual logic to make the program work.





Areas of Applications



1. Web Application Development

2. Scientific And Numeric Computing

3. GUI Programming

4. Professional Training







Install Python on Windows


1. For installing Python on Windows, go to the Download Python for Windows page, select the desired package and click to download. We recommend Python 3.7.4 as it is one of the most stable packages. Next, launch the downloaded package, follow the steps, and finish the installation.


2. During installation, select the option “Install for all users” and use the destination directory (D:\Python37) as default. Also, remember to click "pip" option for the installation of other packages such as IPython and scikit-learn.




Run Python on Windows


1. Now, you are ready to write your first Python program on Windows. As we stated above, you must use a professional IDE for better development. However, here, we’ll tell you to use IDLE that comes as the default editor for Python.


2. From the “Start” menu, open “All Programs” and select “D:\Python37” (in my case). Click on the “IDLE (Python GUI)” link to launch the editor.


3. Once the IDLE window appears, press CTRL+N to create a new file. Then, name it “world.py” while saving using the CTRL+S.


4. Place the following code in “world.py.”

print("Hello, World!")


5. Save the file and go to [Run >> Run Module] or press F5 to execute your first Python script.


6. Or you can simply launch Python 3.7 from DOS shell by simply run "python.exe" from DOS shell, write your world.py program from ANY text editor and run it by typing "python world.py".


7. Type exit() to exit from Python.





Install Python On Mac OS X


1. The latest version of Mac OS X is 10.13 (High Sierra) which has Python 2.7 pre-installed. Beginners can start to use Python 2 and learn to program. However, professional programmers should upgrade to Python 3.6.


2. For installing Python on Mac, go to the Download Python for Mac OS X page, select the desired package and click to download. Next, launch the downloaded package, follow the steps, and finish the installation.


3. If you are a command line geek and love to use a console for routine system tasks, then run the following commands to install Python.


4. Firstly, open the terminal and install the HomeBrew package manager for Mac OS X.

$ ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Enter the below command to check the Brew installation status.

$ brew --version
Now, use the Brew package manager to install Python 3.x.

$ brew install python3



5.  Installing Python with Brew also installs the PIP tool (pip3). It is a quick update manager to check out the available modules in the Python repository.


Run Python On Mac OS X


1. Since now you have Python installed, it’s time to start coding. But you would need an IDE for professional development. It would turn you more efficient and productive. We recommend the community version of PyCharm and Eclipse with PyDev. Both of these are free and full of features. However, you can read our reviews of the world’s best Python IDEs and choose one for yourself.


2. However, you can also begin with IDLE, the default IDE that comes with Python. Or even use the Python console to run your first few lines of code. In Python, you can do a lot with a single line of code. For example, you can write a function which checks for odd no, call it with input and print the outcome but all of that in one single line. Please see the code below.

print((lambda isOdd: isOdd(3))(lambda x: x % 2 != 0))



If you type the above line on a Python CLI, then it would just take an enter key to execute. However, if you are using IDLE to write this code in a script, then press F5 to run it. In either way, this simple one line of code would print “True” in its output.





Create Your First Program In Python


Usually, it is the “Hello, World!” program which every language recommends as a starting point to learn Programming. It is a simple program which prints the “Hello, World!” message on the standard output.

1. Click "Python IDLE" or using "cmd" to open a DOS shell and type  "python" to run python in DOS shell.

2. Copy "print(“Hello, World!”)" to print "Hello World" on the console.

Like this:


Note:


1. If you copy any text from the browser, sometime the ' " ' character will change to Chinese quotation symbol and cause errors. Simply change it back to English quotation symbols.


2. It obviously would be very trivial if we write it in Python, just one statement as the print(“Hello, World!”). Hence, we’ll use the Interest Calculator program for illustration.


Interest Calculator - Program Description


This program computes the interest accrued over the specified no. of years on the principal amount with one year as a fixed value for the compound interval.


Interest Calculator - Program Source Code


print('Interest Calculator:')
amount = float(input('Principal amount ?'))
roi = float(input('Rate of Interest ?'))
years = int(input('Duration (no. of years) ?'))
total = (amount * pow(1 + (roi/100), years))
interest = total - amount
print('\nInterest = %0.2f' %interest)


Let’s take a look on The Program Step By Step


Step-1:


In the first line, we are calling the print() function to display an informational message. It’s the same as printing like the “Hello, World!”.


Step-2:


In the next three lines, we are using the following variables to store the input provided by the user.

The variable ‘amount’ represents the principal amount borrowed.

Another one is the ‘roi’ which represents the rate of interest levied on the principal amount.

Next, there is ‘years’ which is the no. of years representing the borrowing period.

Also, you must note here that we are using Python’s input() function to prompt the user for entering the values. Furthermore, you can observe that we’ve used Python’s conversion operators (int() and float()) in this code.

int(value) -> It converts any value to a plain integer.

float(value) -> It converts a value to a float type number.

So far, we’ve covered the first four lines. Let’s continue exploring the remainder of the program.


Step-3:


In the fifth line of code, we are using a variable called “total” to store the result of a complex assignment.

The total -> It represents the total amount to be paid after the borrowing period.

But this line is a little different from the previous ones. It is because the first line was an output statement and the next three were the simple assignment operations. Here, in the fifth line of code, we are computing the Total amount including the Interest part with the help of the following formula.



Further to add, this assignment involves the use of the following Python’s arithmetic operators and functions.

+ Addition -> It adds numbers on either side of the operator.

* Multiplication -> It multiplies numbers on either side of the operator.

/ Division -> It divides left-hand operand by right-hand operand.

pow(X, Y, Z) -> It determines [X to the power Y]. If Z is available, then it’ll return X to the power Y, modulo Z.


Step-4:


In the sixth line, we are using Python’s subtraction operator (-) to calculate the interest amount.


Step-5:


Finally, there is a print statement displaying the interest amount. Since it is a float value, so the print()function will show the full number by default. Hence, we are using the floating point format specifier “%0.2f” in print() function so that we can limit the printing up to two decimal points.


Interest Calculator - Create you first Python program

1. In Python IDLE, open a code shell by pressing Ctrl-N. A Python code window will open for you to edit your Python program.


2. Copy the Interest_Calculator Python codes onto the code window.

Like this:



3. Save_As into your Lab1 directory as "Interest_Calcuator.py" file.


4. Run your Interest_Calculator.py file by:

Method 1 (IDLE): Choose "Run" command from the Code window to run the Python program "Interest_Calcuator.py"

Method 2 (cmd DOS shell): In your Lab1 directory, simply type "python InterestCalculator.py" to run the Python file.


You Python window / DOS shell will look like this:

Method 1 - Python IDLE:


Method 2 - Python CMD DOS Shell:



Congratulation! Your first Python program is success.

If you want to learn more about Python. Try the following.






Python Tutorial – Basic To Advanced Concepts











Python Tutorial – Advanced


Install IPython


IPython is a platform for Python development that contains a number of tools and environments for running Python and has more features than the standard interpreter.

It contains the powerful IPython Notebook, which allows you to write programs in a web browser. It also formats your code, shows output, and allows you to annotate your scripts.

It is a great tool for exploring datasets and we will be using it as our main environment for the code in this book. To install IPython on your computer, you can type the following into a command line prompt (not into Python):


pip install ipython[all]


You will need administrator privileges to install this system-wide.

If everything goes smooth, it will be like this.



If you do not want to (or can't) make system-wide changes, you can install it for just the current user by running this command:


pip install --user ipython[all]


This will install the IPython package into a user-specific location—you will be able to use it, but nobody else on your computer can.


If you are having difficulty with the installation, check the official documentation for more detailed installation instructions: http://ipython.org/install.html.


With the jupyter notebook installed, you can launch it with the following:


jupyter notebook


This will do two things.


First, it will create an jupyter notebook instance that will run in the command prompt you just used.


Second, it will launch your web browser and connect to this instance, allowing you to create a new notebook.


It will look something similar to the following screenshot (where home/bob will be replaced by your current working directory):




To stop the jupyter notebook from running, open the command prompt that  has the instance running (the one you used earlier to run the IPython command).


Then, press Ctrl + C and you will be prompted Shutdown this notebook server (y/[n])?. Type y and press Enter and the jupyter notebook will shutdown.






Installing scikit-learn


The scikit-learn package is a machine learning library, written in Python.

It contains numerous algorithms, datasets, utilities, and frameworks for performing machine learning.

Built upon the scientific python stack, scikit-learn users such as the numpy and scipy libraries are often optimized for speed.

This makes scikit-learn fast and scalable in many instances and also useful for all skill ranges from beginners to advanced research users.

To install scikit-learn, you can use the pip utility that comes with Python, which will also install the numpy and scipy libraries if you do not  already have them.

Open a terminal with administrator/root privileges and  enter the following command:


pip3 install -U scikit-learn


If everything goes smooth, you will get this after a while




If you already have a python installation set up, you can use pip to install any of these packages.


$ pip install numpy scipy matplotlib ipython scikit-learn





Next : Essential Python Libraries and Tools ...

到价提醒[关闭]