Programming with Python - An Easy to Understand Beginners Guide to Coding with Python
Programming with Python - An Easy to Understand Beginners Guide to Coding with Python
Marc Stanford
Title Page
INTRODUCTION
REQUIRED SKILLS
NECESSARY HW & SW
A Q&A-SESSION ABOUT PYTHON
APPLICATIONS AND USE OF PYTHON
EXAMPLES OF SHORT CODE SEQUENCES
CONCLUSION
ABOUT THE AUTHOR
INTRODUCTION
Programming languages are created to satisfy the needs of
programmers and users for effective tools to develop application
programs that impact individuals, societies, and economies. They are
expected to make living easier by increasing productivity, enhancing
communication, and improving efficiency.
Python is an open-source, high-level programming language
developed in the late 1980s and presently administered by Python
Software Foundation. It is a powerful and flexible programming
language with characteristic attributes of being fast, easy-to-use,
easy-to-learn, and easy-to-deploy. Python uses concise syntax which
enables programmers to write more codes and develop more complex
programs in much shorter time in comparison with other
programming languages. It is considered as the best suitable
programming language to develop scalable web applications. Twitter,
YouTube, Instagram are all built in Python.
Reading and writing codes in Python is very much like reading
and writing regular English statements. Because they are not written
in an only-machine-readable language, Python programs need to
processed before machines can run them. Python is an object-
oriented language that allows users to manage and control data
structures or objects to create and run programs. Everything in
Python is, in fact, first class. All objects, data types, functions,
methods, and classes take an equal position in Python.
Python is a programming language that has stood the test of
time and has remained relevant across industries and businesses and
among programmers, and individual users. It is the recommended
programming language for those who want to dive into and
experience programming. No wonder it is widely accepted as the
best programming language to learn first.
This book is written with the understanding that the reader is
completely new to Python programming. The author, therefore,
emphasizes looking at this exciting coding adventure from a total
beginner’s point of view.
♦♦♦
REQUIRED SKILLS
The following key abilities are needed to become a successful IT-
programmer.
The ability to learn concepts and apply them to other problems
An example of this would be the concept of writing cascading
style sheets (CSS). The concept is to write styles which apply to the
top level of a site and cascade down to the lower elements in the
site/page. You would then write other style rules for levels below the
top level of the page and they would cascade down too. This means if
there is a general style that you need to change, which is used on
every page, you can change it in one place and the change will
cascade to all pages that use the style and that don’t override the rule
with their own rules.
Basic mathematical skills
In programming, basic math is unavoidable. You need to make
sure that you have at least a basic understanding of algebra and
arithmetic.
A passion for problem-solving
Most of the time, as a programmer, you will be writing a
program to solve a particular problem. If you don’t enjoy solving
problems, you won’t enjoy being a programmer. This might develop
to become a problem at the advanced stages of programming!
Good communication skills
There is a stereotype of developers who sit in the corner on their
own, not talking to anyone and just writing code. Some people are
really like this, but they do still have to communicate. If you don’t
communicate well, problems will arise and this could cause tension
for you or your colleagues. If you don’t like direct interface with
people, and talking face-to-face, become good at written
communication to make up for it.
Good writing skills
Whether you are writing code or documentation, you need to be
able to write in a way that gets your message across clearly. The
ability to explain something complicated to someone non-technical
will help you and your colleagues in your career.
Confidence around a computer
This may seem obvious, but if you are thinking about becoming
a developer, you will need to be confident with a computer. If you are
too timid or afraid that you might break something, it will surely hold
you back and block your professional as well as personal
development.
Resourcefulness
The author often tells people he also received a degree from the
University of Google, because in most cases polishing up the final
result with up-to-date data happens through searching for the answers
in search engines, such as Google. There is an art to searching for
answers on the internet and it is a vital skill for any programmer.
An inquisitive mind
This will help you go far as a programmer. Find out how
something is done and try to find ways to do it better. If you have an
idea that you think will improve things, go away and investigate it.
Of course, not every beginner who wants to learn a programming
language might be perfectly prepared from all sides in the first place.
However, even if you think you have a lack of programming skills,
you can learn easy but powerful programming languages, such as
Python, just by having the right mindset, willingness to learn and by
putting constant effort into trying.
♦♦♦
NECESSARY HW & SW
Python 2.7 will not be maintained past 2020. Originally, there was
no official exact end date. In the meantime, that date has been
updated to January 1, 2020. The author therefore recommends
installing and start learning with Python 3.
➢ Hardware
Processors: Intel Atom® processor or Intel® Core™ i3
processor.
Disk space: 1 GB.
512 MB RAM minimum, 1 GB RAM recommended.
1024x768 minimum screen resolution.
➢ Operating Systems
Windows* 7 or later / macOS / Linux
➢ Software
Recommended Python IDEs and Code Editors are:
Wing IDE-personal
http://wingware.com/downloads/wing-personal
PyCharm
https://www.jetbrains.com/pycharm/download/#section=window
s
Sublime Text
https://filehippo.com/download_sublime_text/
Visual Studio
https://visualstudio.microsoft.com/vs/
https://code.visualstudio.com/download
PyDev
https://www.pydev.org/download.html
Eclipse IDE
https://www.eclipse.org/downloads/
A Q&A-SESSION ABOUT
PYTHON
Python is a general-purpose programming language and can be used
for developing both desktop and web applications. For many
programmers, it is also the coding language of choice for developing
complex scientific and numeric applications. Python is designed with
features to facilitate data analysis and visualization. Here are a bunch
of frequently asked questions about Python and the author’s answers
to them.
Q: Why is Python important?
A: For aspiring data scientists, Python is probably the
most important language to learn because of its rich
ecosystem. Python’s major advantage is its breadth. Programmers
use Python for a variety of application, such as internal tools, logging
tools, build scripts, and system monitoring.
Q: Why is Python getting increasingly popular?
A: First and foremost, the reason why Python is
much popular because it is highly productive as compared to other
programming languages like C++ and Java. Python is also famous for
its simple programming syntax, code readability and English-like
commands that make coding in Python lot easier and efficient.
Python is easy-to-use, powerful, and versatile, thus making it a great
choice for beginners and experts alike. Python’s readability makes it
a great first programming language, it allows you to think like a
programmer and not waste time with confusing syntax.
Q: What are the advantages of Python?
A: Python’s syntax is easy to learn, so both non-programmers
and programmers can start programming right away. Python looks
more like a readable, human language than like coding language
which gives you the ability to program at a faster rate. Python has a
clean object-oriented design, provides enhanced process control
capabilities, and possesses strong integration, as well as text
processing capabilities and its unit testing framework, all of which
contribute to the increase in its speed and productivity.
Q: Comparison of Python to other programming languages?
A: Python programs are generally expected to run slower than
Java programs, but they also take much less time to develop. Python
programs are typically 3-5 times shorter than equivalent Java
programs. Almost everything said for Java also applies for C++, just
more so: where Python code is typically 3-5 times shorter than
equivalent Java code, it is often 5-10 times shorter than equivalent
C++ code. Anecdotal evidence suggests that one Python programmer
can finish in two months what two C++ programmers can’t complete
in a year. Python shines as a glue language, used to combine
components written in C++. PHP has a short learning curve but if we
talk about the long-term, python is more productive than PHP. It is
also more readable than PHP.
♦♦♦
APPLICATIONS AND USE OF
PYTHON
Python is so good that, instead of describing what it can do, it’s
faster to say what Python can’t do. Python is good for a little bit of
everything. According to Stack Overflow, Python is the fastest-
growing programming language in the world, and it will continue to
grow even faster. It’s already well-recognized as a very universal,
versatile, stable, and easy to learn programming language.
As a high-level general-purpose programming language, Python
can be applied to address many different classes of problems.
Ethical Hacking
Banking
Statistical Analysis
Software Engineering
♦♦♦
EXAMPLES OF SHORT CODE
SEQUENCES
Let’s start learning Python for beginners! Herein, I will introduce
some basic Python examples for beginners. As a prerequisite, the
author assumes that Python is already installed on your PC.
➢ Your first Python program
You can run python code with several modes. Please run
command prompt and input “python”, then you can see the Python
interpreter.
Type the following text at the Python prompt and press enter.
>>> print (“Hello! Welcome!”)
If you use python 2.x, you can type the code without
parenthesis.
>>> print “Hello! Welcome!”
➢ Script Mode Programming
Invoking the interpreter with a script parameter begins execution
of the script and continues until the script is finished. When the script
is finished, then the interpreter is no longer active. Let us write a
simple Python program in a script. Python files have the
extension *.py.
Type the following source code in a “hello.py” file.
>>> print (“Hello World”)
Set Python interpreter in PATH variable. Now, try to run this
program as follows.
$ python hello.py
This produces the following result:
Hello World
➢ Mathematical operations with numbers
The interpreter acts as a simple calculator. You can type any
expression and it will write the value. Expression syntax is
straightforward: The operators +, -, * and / work just like in most
other languages (for example, Pascal or C), parentheses (()) can be
used for grouping. Division (/) always returns a floating-point real
value or a float. To do floor division and get an integer result
(discarding any fractional result) you can use the // operator; to
calculate the remainder you can use %.
>>> 5 + 3
8
>>> 12 / 4
3.0
>>> 11 * 3
33
>>> 12 – 5
7
>>> 15 // 4
3
>>> 18 % 7
4
>>>
With Python, it is possible to use the ** operator to calculate
powers.
>>> 2 ** 8
256
>>> 11 ** 2
121
The equal sign (=) is used to assign a value to a variable. The
result is displayed before the next interactive prompt. Please note:
(=) is an assignment operator, and (==) is a comparison operator.
>>> cube_x = 3
>>> cube_y = 5
>>> cube_z = 6
>>> cube_x * cube_y * cube_z
90
➢ Basic String Operations
Assigning a string to a variable is done with the variable name
followed by an equal sign and the string.
>>> greetings = “Hello!”
>>> print (greetings)
Hello!
You can assign a multiline string to a variable by using three
quotes.
>>> a = “”” Lorem ipsum dolor sit amet,
… consectetur adipiscing elit,
… sed do eiusmod tempor incididunt
… ut labore et dolore magna aliqua. “””
>>> print (a)
Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.
Like many other popular programming languages, strings in
Python are arrays of bytes representing Unicode characters. However,
Python does not have a character data type, a single character is
simply a string with a length of 1.
Square brackets can be used to access elements of the string.
You can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon, to
return a part of the string.
>>> b = “Hello, World!”
>>> print(b[2:5])
llo
Use negative indexes to start the slice from the end of the string.
>>> b = “Hello, World!”
>>> print(b[-5:-2])
orl
You can easily repeat strings or its concatenation with the *
operator.
>>> “88abc12399” * 4
88abc1239988abc1239988abc1239988abc12399
There are many other string-related functions such as:
lower (), upper (), replace (), strip (), len (), and split ().
>>> mystring = “He said to her, ‘Nice to meet you again!’”
>>> mystring
“He said to her, ‘Nice to meet you again!’”
>>> print(len(mystring))
41
>>> print(mystring.split(“ ’ ”))
[‘He said to her, ‘, ‘Nice to meet you again!’, ‘ ‘]
>>> print(mystring.replace(“ ‘ “, “ * “)
He said to her, *Nice to meet you again!*
>>> print(mystring.upper())
HE SAID TO HER ‘NICE TO MEET YOU AGAIN!’
>>> print(mystring.upper().lower())
he said to her, ‘nice to meet you again!’
➢ Lists, Tuples, Sets, JSON
Python has a great built-in list type named “list”. List literals
are written within square brackets [ ]. Lists work similarly to
strings — use the len() function and square brackets [ ] to access
data, with the first element at index 0.
# List
>>> fruits = [“apple”, “banana”, “cherry”]
# Add new item into array
>>> fruits.append(“orange”) #[‘apple’, ‘banana’, ‘cherry’,
‘orange’]
# Pop last item from the aray
>>> fruits.pop() #[‘apple’, ‘banana’, ‘cherry’]
# Remove any element from the array
>>> fruits.remove(‘banana’)
# [‘apple’,’cherry’]
>>> print(fruits.index(‘cherry’))
#1
A “tuple” is a sequence of immutable Python objects. “Tuples”
are sequences, just like “lists”. The differences between “tuples” and
“lists” are, the “tuples” cannot be changed unlike “lists” and
“tuples” use parentheses, whereas “lists” use square brackets.
Creating a “tuple” is as simple as putting different comma-separated
values. Optionally you can also put these comma-separated values
between parentheses.
# Tuple
# A tuple is a collection which is ordered and unchangeable.
# In Python tuples are written with round brackets.
>>> thistuple = (“cherry”, “orange”, “kiwi”, “melon”,
“mango”)
>>> print(thistuple[-4:-1])
# (‘orange’, ‘kiwi’, ‘melon’)
# Join 2 tuples
>>> tuple_number = (1, 2, 3)
>>> print(thistuple[:3] + tuple_number)
# (‘apple’, ‘banana’, ‘cherry’, 1, 2, 3)
>>> print(thistuple.index(‘cherry’))
#2
A “set” is an unordered collection of items. Every element is
unique (no duplicates) and must be immutable (which cannot be
changed). However, the “set” itself is mutable. We can add or
remove items from it. “Sets” can be used to perform mathematical
“set” operations like union, intersection, symmetric difference, etc.
# Set
# A set is a collection which is unordered and unindexed
# In Python sets are written in curly brackets
>>> thisset = {“apple”, “banana”, “cherry”}
# Add new item to this set
>>> thisset.add(“orange”)
# {‘orange’, ‘cherry’, ‘banana’, ‘apple‘}
>>> thisset.update([“orange”, “mango”, “grapes”])
# {‘mango’, ‘orange’, ‘cherry’, ‘banana‘, ‘grapes’,‘apple‘}
>>> thisset.remove(“mango”)
# {‘grapes’, ‘cherry’, ‘apple‘, ‘orange’,‘banana‘}
>>> list1 = [11,12,22,23,11,22,44,55,66,23]
>>> print(set(list1))
# {66,11,12,44,55,22,23}
>>> set2 = {1,3,4,5}
>>> print(thisset.union(set2))
# {1, ‘apple’, ‘banana’, 3, 4, ‘orange’, ‘grapes’, ‘cherry’, 5}
“JSON” (Java Script Object Notation) is a popular data format
used for representing structured data. It’s common to transmit and
receive data between a server and web application in “JSON”
format. In Python, “JSON” exists as a string.
# JSON
>>> import json
# some JSON:
>>> x = ‘{“name”, “John”, “age”:30, “city”:”New York”}’
# parse x
>>> y = json.loads(x)
# the result is a Python dictionary:
>>> print(y[“age”])
# 30
➢ Datetime
The date contains the year, month, day, hour, minute, second,
and microsecond.
The “datetime” module has many methods to return information
about the date object.ä
>>> import datetime
# Get the current datetime
>>> x = datetime.datetime.now()
# 2019-09-25 08:36:25.412002
>>> print(x.year, x.month, x.day, x.strftime(“%A”), x.hour, “:”,
>>> x.minute, “:”, x.second)
#2019 9 25 Wednesday 8 : 39 : 54
➢ Statements
If…Else
While Loops
The “while” loop executes a set of statements as long as a
condition is true.
>>> i = 1
>>> a = [“a”, “b”, “c”, “d”, “e”, “f”]
>>> while i < 6:
>>> print(i, a[i])
>>> i += 1
#1b
#2c
#3d
#3e
#5f
For loop
Try Except
The “try” block lets you test a block of code for errors.
The “except” block lets you handle the error. The “finally” block lets
you execute code, regardless of the result of the “try” and “except”
blocks. When an error occurs, or exception as we call it, Python will
normally stop and generate an error message. These exceptions can
be handled using the “try” statement.
>>> array = [“a”, “1”, “b”, “2”, “3”, “c”]
>>> for I in array:
>>> try:
>>> print(int(i) / 8)
>>> except:
>>> print(i)
#a
# 0.125
#b
# 0,25
# 0,375
#c
Iterators
Creating a Function
Calling a Function
Create Object
Now you can use the class named “myClass” to create objects.
Create an object named p1, and print the value of x.
>>> p1 = MyClass()
>>> print (p1.x)
Object Methods
The self-Parameter
Delete Objects
You can delete objects also by using the keyword “del”. For
example, delete the object p1.
>>> del p1
Please bear in mind that even the most complex Python
programs are written as a combination of the building blocks shown
in this chapter. However, providing further examples of more and
more complicated code sequences would mislead the aim and
purpose of this book, namely: proving an easy-to-understand and fast
introduction into the fascinating world of Python Programming.
♦♦♦
CONCLUSION
Thank you for making it through to the end of Programming with
Python: An Easy to Understand Beginners Guide to Coding with
Python. Let’s hope it was informative and able to provide you with
all the tools you need to achieve your goal of getting familiar with
Python. The author’s intention for writing this Beginner’s Guide to
Python Programming was to open a gate to the readers and allow
them to enter into the Python programming world.
The book presented an overview of Python programming and
utilities using Python to develop applications. The book also
presented the basic programming syntax of Python for absolute
beginners with no background in programming. The basic data
structures and the use of most fundamental libraries NumPy and
Pandas were also mentioned. The author sincerely hopes that it was
an interesting reading experience and you would continue using this
book as a guide on your journey of becoming an expert Python
programmer.
ABOUT THE AUTHOR
Marc Stanford holds a Master’s degree in Advanced Computer
Science. During his professional career, he specialized, among others,
in artificial intelligence and complex data modeling. Although
already experienced in tutoring and lecturing, writing technical books
is his newest passion.
He lives and works in Palo Alto, CA, USA.