Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
23 views

Programming with Python - An Easy to Understand Beginners Guide to Coding with Python

This document is a beginner's guide to programming with Python, highlighting its ease of use, versatility, and applications across various fields such as web development, data analysis, and ethical hacking. It outlines the necessary skills and hardware/software requirements for learning Python, along with examples of basic code sequences to help new programmers get started. The author emphasizes Python's readability and community support, making it an ideal first programming language for aspiring developers.

Uploaded by

Brett Crompton
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Programming with Python - An Easy to Understand Beginners Guide to Coding with Python

This document is a beginner's guide to programming with Python, highlighting its ease of use, versatility, and applications across various fields such as web development, data analysis, and ethical hacking. It outlines the necessary skills and hardware/software requirements for learning Python, along with examples of basic code sequences to help new programmers get started. The author emphasizes Python's readability and community support, making it an ideal first programming language for aspiring developers.

Uploaded by

Brett Crompton
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

PROGRAMMING WITH PYTHON

An Easy to Understand Beginner’s Guide to Coding


with Python

Marc Stanford

Copyright © 2019 Aculeatus Limited


All rights reserved
Contents

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/

Visual Studio Code

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

Python is the programming language of choice for scores of


ethical hackers. Indeed, a good handle of Python is considered
essential for advancement in a cybersecurity career. One of the main
draws is that you get a powerful language in a very easy-to-use
package. Python is flexible and functional while being intuitive and
easily readable. It’s ideal for scripting small programs, which is a
huge part of the role of ethical hackers. Plus, when you start using
Python, you join a huge community of dedicated fans. This means
that should you need any tips or advice or run into some issues, there
are plenty of resources - including documentation and forums - to
turn to. Aside from cybersecurity, Python can be an invaluable
language as part of a knowledge foundation in other careers too.
Those interested in web development and testing, big data, game
development, artificial intelligence, or smart device development can
benefit from Python coding skills.

Banking

Most web platforms analyzing cryptocurrencies and blockchain


applications are built using Python. Python is often the main
language used to build pricing, risk, and trade management platforms
for investment banks. This can then be used to trade stocks,
commodities, FX, ETFs, etc.
There is a variety of already developed solutions and a wide
selection of libraries that can be used to apply the best practices. This
feature saves a lot of time because one can use already existing
libraries instead of writing the code from scratch. These libraries, for
example, help to simplify the development process by visualizing the
massive amounts of data thus enabling easy statistical calculations
based on this information. It is also used to write software for
Cashpoints/ ATMs as well as to enhancing payment processing.
According to the investment banking tech guru, Kirat Singh
“Everyone at J.P. Morgan now needs to know Python and there are
around five-thousand developers using it at Bank of America. There
are close to ten million lines of Python code in Quartz and we got
close to three-thousand commits a day.” Python, by the way, is the
core language for Bank of America’s Quartz program.

Statistical Analysis

Python has many data analysis, statistics, and visualization


packages as well as machine learning packages. Furthermore, there
are powerful mathematical and statistical data science packages
available.
Users can import and use those packages and can process data
analysis and prediction, statistics from the dataset. For example,
pandas, the Python Data Analysis Library, used for everything from
importing data from Excel spreadsheets to processing sets for time-
series analysis. SciPy is the scientific equivalent of NumPy, offering
tools and techniques for analysis of scientific data. Python
visualization packages support generating wonderful and various
charts from datasets.

Software Engineering

The first start is important in programming. If programmers


succeed in writing and running simple code for the first time after
installing Python, then they can surely speed up language grasp,
soon. Variables and function definitions in Python are much simpler
and easier than in other languages, making it easier to understand
languages.
To process complex information such as image processing or
encryption, it is possible to perform a massive and complicated
process in only a few lines by installing a necessary package and
calling a library function. If software developers are familiar with the
language and gain experience by importing packages, calling library
functions, and using user-defined functions, such as file management
and simple processing, then they can rapidly move on to new higher
levels of programming with Python.
It is an easy task to implement the knowledge of the theory of
machine learning, the methods of image processing, data analysis,
statistics, and encryption in Python code. Besides, there are plenty of
solutions available on the Internet, often offered with almost limitless
example codes.

♦♦♦
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.

Python interpreter screen

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

Python supports the usual logical conditions from mathematics.


Equals: a == b
Not Equals: a! = b
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
These conditions can be used in several ways, most commonly
in “if” statements and loops. An “if” statement is written by using
the “if” keyword.
>>> a = 33
b= 200
>>> if b > a:
>>> print(“b is greater than a”)
>>> else:
>>> print(“a is greater than b”)
# b is greater than a

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

A “for” loop is used for iterating over a sequence (that is either


a “list”, a “tuple”, a “dictionary”, a “set”, or a “string”). It is
unlike the “for” keyword in other programming languages and works
more like an iterator method as found in other object-orientated
programming languages. With the “for” loop, you can execute a set
of statements, once for each item in a list, tuple, or set.
>>> fruits = [“apple”, “banana”, “cherry”]
>>> for x in fruits:
>>> print(x)
# apple
# banana
# cherry

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

An “iterator” is an object that contains a countable number of


values. An iterator is also an object that can be iterated upon,
meaning that you can traverse through all the values.
Technically, in Python, an “iterator” is an object which
implements the iterator protocol, which consists of the
methods __iter__() and __next__(). Lists, tuples, dictionaries, and
sets are all iterable objects. They are iterable containers which you
can get an “iterator” from. All these objects have an iter() method
which is used to get an “iterator”.
>>> mytuple = (“apple”, “banana”, “cherry”)
>>> myit = iter(mytuple)
>>> print(next(myit))
>>> print(next(myit))
>>> print(next(myit))
# apple
# banana
# cherry
➢ RegEx
A “RegEx”, or Regular Expression, is a sequence of characters
that forms a search pattern. “RegEx” can be used to check if a string
contains the specified search pattern.
Python has a built-in package called “re”, which can be used to
work with Regular Expressions. An example is the
“Import re” module.
>>> import re
>>> mystr = “The rain in Spain”
>>> x = re.findall(“ai”, myster)
>>> print(x)
# [‘ai’, ‘ai’]
>>> x = re.split(“ “, mystr)
>>> print(x)
# [‘The’, ‘rain’, ‘in’, ‘Spain’]
➢ File Handling
The key function for working with files in Python is the “open
()” function. The “open ()” function requires two
parameters; “filename”, and “mode”. There are four different
methods (modes) for opening a file:
“r” - Read - Default value. Opens a file for reading, error if the
file does not exist
“a” - Append - Opens a file for appending, creates the file if it
does not exist
“w” - Write - Opens a file for writing, creates the file if it does
not exist
“x” - Create - Creates the specified file, returns an error if the
file exists
Also, you can specify if the file should be handled as binary or
text mode
“t” - Text - Default value, text mode
“b” - Binary - Binary mode, e.g. images
>>> schema.txt
>>> dn: cn = schema
>>> objectClass: top
>>> f = open(“schema.txt”, “rt”)
>>> lines = str(f.read()).split(“\n”)
>>> index = 0
>>> for line in lines:
>>> print(str(index), “ – “, line)
>>> index += 1
––––– Result ––––—
= - dn: cn=schema
1 – objectClass: top

Read/Write CSV file

To read/write a csv file easily, you can import a “csv package”.


>>> import csv
>>> row = [‘2’, ‘Marie’, ‘California’]
>>> with open(‘data.csv’, ‘r’) as readFile:
>>> reader = csv.reader(readFile)
>>> lines = list(reader)
>>> lines[2] = row
>>> with open(‘data.csv’, ‘w’) as writeFile:
>>> writer = csv.writer(writeFile)
>>> writer.writerows(lines)
>>> readFile.close()
>>> writeFile.close()

Read/Write Excel file

Python provides the openpyxl module for operating with Excel


files. How to create Excel files, how to write, read, etc. can be
implemented by this module. For installing openpyxl module, we can
write this command in command prompt.
# Program to extract number
# of rows using Python
>>> import opnpyxl
# Give the location of the file
>>> Wb = openpyxl.load_workbook(‘data.xlsx’)
>>> sheet = wb[‘Data]
>>> for i in range(4):
>>> dt = sheet.cell(i+1, 1).value
>>> sheet[‘B’ + str(i + 1)].value = “okay”
# Extracting number of rows#´
>>> print(dt)
>>> wb.save(‘res.xlsx’)
➢ Functions
A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function. A function
can return data as a result.

Creating a Function

In Python, a function is defined using the “def” keyword.


>>> def my_function():
>>> print(“Python Function”)

Calling a Function

To call a function, use the function name followed by a


parenthesis.
>>> def func1():
>>> print(“Python Function”)
>>> func1()
Parameter

Information can be passed to functions as a parameter.


Parameters are specified after the function name, inside of
parentheses. You can add as many parameters as you want, just
separate them with a comma. The following example has a function
with one parameter (fname).
>>> def my_function1(fname):
>>> print(fname + “Refsnes”)
>>> def my_function2(country = “Norway”):
>>> print(“I am from” + country)
>>> def my_function3(food):
>>> for x in food:
>>> print(x)
>>> my_function1(“Emil”) # Emil Refsnes
>>> my_function2(“Sweden”) # I am from Sweden
>>> my_function2() # I am from Norway
>>> fruits = [“apple”, “banana”, “cherry”]
>>> my_function3(fruits)
apple
banana
cherry
When the function is called, you pass along a first name, which
is used inside the function to print the full name. You can use a
default parameter value, too. If we call the function without a
parameter, it uses the default value. You can send any data types of a
parameter to a function (string, number, list, dictionary, etc.), and it
will be treated as the same data type inside the function.
➢ Classes/Objects
Python is an object-oriented programming language. Almost
everything in Python is an “object”, with its properties and methods.
A “class” is like an object constructor or a blueprint for creating
objects.

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)

The __init__() Function

The example above shows classes and objects in their simplest


form which are not suitable in real-life applications. To understand
the meaning of classes you have to understand the built-in __init__()
function. All classes have a function called __init__(), which is
always executed when the class is being initiated.
Use the __init__() function to assign values to object properties
or other operations that are necessary to do when the object is being
created.
>>> class Person:
>>> def __init__(self, name, age):
>>> self.name = name
>>> self.age = age
>>> p1 = Person(“John”, 36)
>>> print(p1.name)
>>> print(p1.age)

Object Methods

Objects can also contain methods. Methods on objects are


functions that belong to the object. For example, insert a function that
prints a greeting, and execute it on the p1 object.
>>> class Person:
>>>def__init__(self, name,age):
>>> self.name = name
>>> self.age = age
>>> def myfunc(self):
>>> print(“Hello my name is “ + self.name)
>>> p1 = Person(“John”, 36)
>>> p1.myfunc()

The self-Parameter

The “self-parameter” is a reference to the current instance of


the class and is used to access variables that belong to the class. It
does not have to be named self, you can call it whatever you like, but
it has to be the first parameter of any function in the class.
For example, use the words “mysillyobject” and “abc” instead
of self.
>>> class Person:
>>> def__init__(mysillyobject, name,age):
>>>mysillyobject.name = name
>>>mysillyobject.age = age
>>> def myfunc(abc):
>>>print(“Hello my name is “ + abc.name)
>>> p1 = Person(“John”, 36)
>>>p1.myfunc()

Delete Object Properties

You can delete properties on objects by using the keyword


“del”. For example, delete the age property from the object p1.
>>> del p1.age

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.

You might also like