Python, first Steps
Python, first Steps
First Steps
IT Learning Adventure
© Copyright 2021 by IT Learning Adventure - All rights reserved.
This document is geared towards providing exact and reliable information in
regards to the topic and issue covered. The publication is sold with the idea
that the publisher is not required to render accounting, officially permitted, or
otherwise, qualified services. If advice is necessary, legal or professional, a
practiced individual in the profession should be ordered.
The trademarks that are used are without any consent, and the publication of
the trademark is without permission or backing by the trademark owner. All
trademarks and brands within this book are for clarifying purposes only and
are the owned by the owners themselves, not affiliated with this document.
Table of Contents
Introduction
Computer Programming
How to Program
Python
Install Python
Python Variables
Python Operators
Functions
Conditionals
Exercises
Conclusion
Preview of “Insert Book Title”
Check Out My Other Books
Bonus: (Name of Bonus)
Introduction
Hello everyone and welcome to Python, First Steps, a simple easy entrance to
the programming word. From IT Learning Adventure we want to thank you
for download our first book and join us on this training journey that we hope
to be helpful and valuable to you.
With this book, we want present to everyone the reader a concise guidance on
the terms, theory, and elements that you should know and be familiarized in
the applications development word. For this reason, inside this book, you will
not find just the first step on Python but on programming. We start talking
about what is programming, where it comes from, which are its fundamentals
and how start to apply. After that, we present Python to you, from its basic’s
elements, along with some figures, number of examples and few exercises.
The main idea is that you advance step by step, getting a clear understanding
on all content.
You will find an easy reading language from chapter one. The examples are
adjusted to reality, so, you can work them directly on your computer while
you read the book. It is important to mention that Python is a great tool with
hundreds (or thousand) of possibilities. We are creating a three book series to
give the reader an easy, concise, clear, and reliable path to know, understand
and use this language. After you complete Python, First Steps, you will be
able to use it on a Windows computer, use the basic math operators, create
functions and work with conditional structures.
We want to thank you again for purchasing this book, we are confident that
you will enjoy it and the most important, on each step, you will develop new
skills that will help you.
COMPUTER PROGRAMMING
WHAT IS PROGRAMMING?
Programming or computer programming, in the simplest form, is the creation
of instruction to the computer for completing some unique task. Just as in our
everyday living, where most of the things we do are programmed, that is,
have a pattern we do them, same is for computer programming. Programming
means creating a set of instructions for a computer to carry out an operation
or operations, to achieve a task or a group of them.
Computer programming follows a pattern. The computer obeys instructions
according to the pattern they are written. If the instructions are not written in
the right pattern, then the result of the task it is to carry out will be a mess.
To create this set of instructions, you need a programming language the
computer understands, just as humans understand their own languages, like
English, French, Latin, etc. This language is known to both the program
creator (programmer) and the computer operating system. Programming is
usually aimed for a computer to achieve and complete tasks that help people
to be more efficient, saved time, be more secured or make it easier for them
to access to goods and services.
The first computer programming was created in the 19th century. Ada
Lovelace worked on Charles Babbage's Charles’s early mechanical computer:
“Analytical Engine,”. During 1842–1843, she translated the memoir of Italian
mathematician Luigi Menabrea about Charles Babbage's machine; she
supplemented the memoir with notes that specified in detail a method for
calculating Bernoulli numbers with the Analytical Engine, recognized by
most of historians as the world's first published computer program. The
innovation of Ada helped Babbage perfect his design for his mechanical
computer, and in the process, the idea of programming was invented. Ada
Lovelace is usually pinned with the accolade of being the first programmer.
As different needs have arisen within two centuries, new devices have been
invented, and new programming languages have been developed as well.
COMPUTER LANGUAGE
In simple terms, computer language is the language the computer
understands, used to write codes in a program or application to provide
instructions to the computer. There are five generations to classify computer
languages.
Machine Language: The machine language (also referred to as machine
code or object code) is a low-level language. It's the native language of the
machine and the only one directly understood by the central processing unit.
In this language, the input is directly written in binary (this is a set of 0s and
1s) which are easily read and interpreted by a computer system but not for
human. The computer’s operating system is used to identify the main
machine language used for that computer. The operating system is the
interface program between the user and the hardware, along with other basic
functions, provides services for applications software. These applications can
be written in programming languages other than the machine language, such
as Python, just that the computer cannot directly understand it and would
need a program that can convert these programs to machine language. For
this, compilers and interpreters are needed to convert programs written in
Python (or other programming languages) to machine language. Example of
machine language for the text “Hello World”: 01001000 0110101 01101100
01101100 01101111 00100000 01010111 01101111 01110010 01101100
01100100.
Assembly Language: Also known as assembly code, the assembly language
is also a low-level language for the central processing unit and other
programmable devices. As the machine language is the first-generation
language, assembly code it is considered as a second-generation language.
Short mnemonic codes are used for instructions and programmers can
introduce names for blocks of memory that hold data.
The assembly language is popularly used to write system software such as the
operating system and other application software used for direct hardware
access. Programmers use assembly language to carry out the following
operations: memory management, registry access, and click cycle operations.
The command and structure of the assembly language is the same with that of
the machine language but it uses names in place of numbers, a programmer
might write “add item1, item2” instead of 010001 10001 011101 for an
instruction to add two values.
High-Level Language: Aside the fact that machine and assembly languages
were hard to understand for humans, another issue faced by programmers in
writing programs in the older language is the issue of portability, programs
written in one machine cannot be transferred to other machines. These and
some other reasons led to the development of high-level language. The high-
level language is easy to understand, user friendly and codes can be written
easily. Portability is another advantage, programs written in high-level
language is not dependent on the computer system, the codes can be
transferred and used on other machines. The high-level of language focuses
on programming language rather than focusing on computer hardware
components like register utilization or memory utilization.
High-level language tends toward the users. Programmers can write programs
that can be easily understood by any user. The Syntax and programming style
of the high-level language can be easily understood by humans when it is
compared to low-level language. Just that, high-level language needs a
compiler because the program written in high-level language is not
understood by the computer. Some examples of high-level language are
FORTRAN, C++, Java, BASIC, etc.
Very High-Level Languages: These are fourth-generation languages and the
one Python belongs. They are mainly shorthand programming languages.
Operations that required tens of lines in high-level languages will require just
several lines in very high-level languages. Generally, very high-level
languages are still difficult to describe.
Some of the characteristics of very high-level languages are: they are
basically non-procedural. A procedural language tells the computer how an
operation should be carried out: add this, do this if this is true, compare that
to, and so on. In non-procedural, the instructions are different. Programmers
only tell the computer what they want done, and not how to do it. They’re
easier and faster, and this leads to an improved productivity. Some other
examples of this kind of languages are Perl and Ruby.
Natural Languages: These are fifth generation languages. And just as the
very high-level languages, they are more ill-defined. They're called natural
languages because they have a resemblance with the “natural” English
language. Instead of programmers being forced to input correct commands in
correct order, a programmer can just tell the computer what to do by typing in
his or her own words. The natural language translates human instructions into
codes the computer understand. If it's not sure what the programmer has in
mind, it asks for further clarifications.
Compilers and Interpreters: Since the computer cannot understand high-
level language, there is need for a program to serve an intermediate between
the computer and the language. Compilers and interpreters are programs that
do the job of converting the high-level language into machine language for
the computer to understand. Different programming languages have their
preferred converter between compilers and interpreters. As compilers scans
the entire program and translates the whole of it into machine code at once,
interpreters translate just one statement of the program at a time into machine
code, taking very less time to analyze the source code .
HOW TO PROGRAM
Programming is a process. Even if you're writing for fun or practice, there
must be a focus. You must have plans of what you aim to achieve writing the
program. Most importantly, there might be a problem you want to get solved
using the program. Below is a step that will aid you on writing a program.
Define the Problem: This is the very first step to writing a program, you
must specify the problem (need). What is the need? Suppose you want to
write a program to grade and pass or fail students according to their grades,
it’s this need that will inform the lines of instructions you will write to arrive
at your desired result.
Plan the Solution: There are two common ways of planning the solution:
you either draw a flowchart or write pseudocode (or both). A flowchart is a
pictorial representation of the steps of solutions to a problem. Pseudocode is
written English-like language. Pseudocode allows you to state your solution
with a bit less precision than is required when using a programming
language. In figure 1, you will find a simple example of a flowchart and a
pseudocode for a simple task as add two numbers.
Code the Program: After you have planned the solution, the next step is for
you to write the solution in a programming language. You'll translate the
solution in the flowchart or pseudocode to a programming language. You can
use a text editor to create a file for your program or you simply write it out on
a paper. You can use any programming language that suite your needs most.
Test the Program: After coding your program, your must test if on the
computer, if it serves its purpose without mistakes. Testing your program
involves some steps. First is you desk-check. Desk-checking is just like
proofreading an article. You will go through the whole program to see if
there are mistakes and make corrections. The second is translating. You'll
make use of a translator. A translator is a program that checks the syntax and
points to lines there are syntax errors; then translate the program into machine
language for the computer to understand. Third is debugging. Debugging
involves you testing the program to be it's free from mistakes. These mistakes
here are not mistakes in coding but mistakes like not writing the program to
effectively solve the problem.
Figure 1
PYTHON
Python is a general purpose high-level interpreted programming language
developed by Guido Van Rossum at the National Research Institute for
Mathematics and Computer Science in the Netherlands. Python is a simple
programming language, very suitable for beginners to learn without facing
any difficulties. Python is a very easy program to learn and understand since
it's a high-level program. It is available, portable, and can run on a number of
operations systems such as Mac, Windows, Unix, etc.
Python is an interpreted programming language and does not need to be
translated into machine code for the computer's processor before it can run.
This makes the development cycle to be quicker because codes are run as
they are typed without compilers intermediating.
HISTORY OF PYTHON
The idea of Python was initially birthed and developed by Guido Van
Rossum in 1989 as a member of National Research Institute of Mathematics
and Computer Science. At first, it was developed as a successor to the ABC
programming language that was widely used in the Netherlands. It was
mainly developed with emphasis on the ability for codes to be easily
understood, and its syntax allowing programmers to use fewer lines of codes
to express their concepts.
Guido started the development Of Python as a hobby in December 1989. He
built Python to succeed the ABC programming language, which had the
interfacing with the Amoeba operating system with the feature of exception
handling. He was part of the developers of ABC, and had seen its pros and
cons, he liked most of its pros though. He took the Syntax of ABC, and some
of its good features, fixed the issues completely, and created a good scripting
language that removed all the flaws of ABC.
The programming language was finally released in February 1991. It used
fewer codes to express the concepts compared with languages like C++ and
Java. Its main objective was to provide the understandability of codes.
Python was not named after a snake, as its name would suggest. Rather, it
was named after the British TV show, “Monty Python’s Flying Circus,” as
Guido has been a fan of the TV show, plus he wanted a slightly mysterious
name for his invention.
Python, like every other programming language, has been through numerous
versions. Python 0.9.0 was the maiden version released.
In January 1994, Python 1.0 was released. In addition to exception handling,
Python included classes, lists, and strings. More importantly, it included
lambda, map, filter and reduce, which aligned it heavily in relation to
functional programming. Several other versions of Python 1.x were released.
In October 2000, Python 2.0 was released. This version of Python was more
of an open-source project from members of the National Research Institute of
Mathematics and Computer Science. This version of Python included list
comprehensions, a full garbage collector, and it supported Unicode. Several
other versions of Python 2.x were also released.
Python 3.0 was the next version and was released in December of 2008. Ever
since, several other versions of Python 3.x have been released (the latest
version of Python is 3.9.2). Although Python 2 and 3 are similar there are
subtle differences. Perhaps most noticeably is the way the print statement
works, as in Python 3.0 the print statement has been replaced with a print ()
function.
The two widely and most used versions of Python are Python 2.x and 3.x.
Python has come a long way to become one of the most popular and widely
used programming languages in the world. It's been 3 decades
already since the first release in January 1991. Python has developed scores
of versions during this period.
Figure 2
FEATURES OF PYTHON
Python has many features, just as every other programming language. Some
of the most notable features are:
Open Source and Free: A program is open source if it allows for
contribution by others to its development. Python is open source, anyone can
create and contribute to its development. In addition to this, Python is free to
download and can be used in any operating system, either it is Windows,
Linux or Mac.
Easy to Code: Python is very programmer-friendly. Anyone can learn to
code in it within a couple of days. When compared with other object-oriented
programming languages like C, C++, Java, Python is still the easier to learn.
High-Level Language: Python is designed to be a high-level language, you
don't need to be aware of the coding structure, or architecture, or memory
management when you code.
Integration: Python is an integrated language. Its interpreter executes codes
one line after the other. Unlike many other object-oriented programming
languages that use compiler. Python doesn't use compiler, which makes
debugging process easier and efficient.
Support for GUI: Python has support for a wide array of graphic user
interface (GUI) that are easily imported into the interpreter. GUI is a key
aspect of any programming language because it can add flair to codes and
make what comes out more visual.
Object-Oriented Approach: Python recognizes the concept of class and
object encapsulation, this allows programs to be efficient in the long run.
Portable: You can write your voice a Windows system, and shift the same to
another system with a different operating system. You don't have to worry
about changing codes when you use python.
Dynamic: Python is one of the most dynamic programming languages
available. Variables are decided at the run time and not in advance. Variable
type does not need to be specified during coding. This saves time and
increase efficiency.
Extensive Array of Library: Python comes with many libraries that can be
used in a specific program at any time. Libraries saves programmers the
stress of having to rewrite codes every time by just importing already written
codes from the library.
Support for Other Languages: Python supports the execution of code
written in other programming languages such as Java, C#, and C, making it a
versatile language.
INSTALL PYTHON
In Python, First Steps, we will work with Python installation on Microsoft
Windows 10. Windows does not come with a Python by default, unlike some
Linux operating systems. Installing it however, on your Windows won't break
a sweat, you can do it on your own in just some few easy steps.
This section, we will be installing Python on Windows 10. The prerequisites
are: a system running on Windows 10 with admin rights; command prompt
(it comes with Windows); an internet connection. We are good to start.
Step 1: Choose the version of Python to install
The version you want to install will depend on your need. If you are a
beginner and learning code in Python, it is advisable you download the latest
version of Python 3. Versions of Python 2 will give the opportunity to work
with older projects or test new ones.
If you are working on a project that is coded in a particular version, let's say
Python 2.3, you will need to download that exact version.
Step 2: Download the Python Executable Installer
Open your web browser and go to the “Downloads for Windows” section of
the official website of Python (www.python.org/downloads). Search for the
version of Python you wish to install. Presently, the latest Python 3 release is
the 3.9.4 version, while that of Python 2 is the 2.7.18 version.
Select a link to download either the “Windows x86-64 executable installer”
for Windows installation is a 64-bit system, or “Windows x86 executable
installer” if your Windows installation is a 32-bit system.
Step 3: Run Executable Installer
- Run the “Python Installer” once you have downloaded it. Make sure
to select the “Install Launcher for all users” and “Add Python X to PATH”
checkboxes. The “Add PythonX to path” puts the interpreter in the execution
path. Older versions of Python do not support the “Add Python” to Path
checkbox. Select “Install Now” – the recommended installation options. “Pip
and IDLE” are included in all recent versions of Python in the recommended
installation option.
- In the next dialog box, you will be prompted to select whether to
“disable path length limit.” Or “Close”. With the first option, Python can
bypass the 260-character MAX_PATH limit, that means Python will be able
to use long path names. Select “Close”.
Step 4: Check to see Python was installed on Windows
You can verify whether the installation was successful by typing “python –
V” in the Command Prompt. It should display the version of Python you
installed.
Figure 3
To execute Python you can go to the directory where was installed on the
computer, the default location is:
“C:\Users\Username\AppData\Local\Programs\Python\PythonX” (you can
also try write Python from the command prompt to start the program), it
should take you to the Command Prompt environment that is the Python
interpreter (Python shell):
Figure 4
Figure 5
Else, you get the output: ’pip’ is not recognized as an internal or external
command, Operable program or batch file.
Step 6: Add Python Path to Environment Variables
This is optional. If your version of Python does not include the “Add Python
to PATH” checkbox, go through these steps (older versions):
- Start the “Run” app at the “Start” menu.
- Type “sysdm.cpl” and click OK. The “System Properties” window
opens.
- Go to the “Advanced” tab and select “Environment Variables.”
- Find and select the “Path” variable under the “System Variables.”
- Click on “Edit.”
- Select the Variable value field. Add the path to the python.exe file
preceded with a semicolon (;).
- Click Ok and close all windows.
Once you set this up, you can run Python scripts like this, “Python script.py
instead of, “C:/PythonX/Python script.py
Step 7: Install virtualnv
This is also optional. Now, you have Python and Pip to help you manage
packages, you need one software package still: virtualnv. Virtualnv allows
you create local virtual environment that can be isolated for your Python
projects. To install virtualnv:
- Open the “Start” menu, then type “cmd.”
- Select the “Command Prompt” application.
- Type this pip command in the console: C:\Users\Username> pip
install virtualenv
Once you have done the above, virtualnv will be installed on your system.
HOW TO EXECUTE PYTHON SCRIPTS
You can run your Python scripts in two ways. The first one is using the
Python interpreter directly (see figure #2). This will allow you to execute
Python elements as a piece of code typed into an interactive session, in this
way, every time you put any statement or expression will be evaluated and
executed right away in memory. Typing an end-of-file character (Control-Z
on Windows) at the primary prompt causes the interpreter to exit with a zero
exit status. If that doesn’t work, you can exit the interpreter by typing the
command: quit(). Once the interpreter is closed all the information will be
lost.
The second way to execute Python scripts is using .py files. For this you can
use any text editor to create a file for your program. When you are ready to
save the file use the extension .py. Them you can open a Command Prompt
console on Windows 10, go to the folder location and execute the file. In the
following example we will navigate to the folder “temp” in drive C:\ and the
execute the file HelloWord.py:
Figure 6
PYTHON KEYWORDS
Python keywords are specially reserved words with specific meanings. They
cannot be used for other proposes aside their specific purpose. These
keywords are available, and you don't need to import them into your code.
Keywords cannot be used for variable names, class names or function names.
As of the latest version of Python, 3.9, there are 36 keywords: False, break,
for, not, None, class, from, or, True, continue, global, pass, _peg_parser_,
def, if, raise, and, del, import, return, as, elif, in, try, assert, else, is, while,
async, except, lambda, with, await, finally, nonlocal, yield. All keywords are
in lower case, except three “False, None and True.” Below is a short
description of each of the keywords.
False: is a Boolean value, result of comparison operation.
break: break out of a loop.
for: used to create a “for” loop.
not: is a logical operator.
None: used to represent a null value.
class: used to define a class.
from: used to import specific part of a module.
or: a logical operation.
True: is a Boolean value, result of comparison operation.
continue: used to continue to the next iteration of a loop.
global: used to declare a global variable.
pass: is a null statement, it does nothing.
_peg_parser_: it is a rename of _new_parser_ keyword.
def: used to define a function.
if: used to make a conditional statement.
raise: used to raise an exception.
and: is a logical operation.
del: used to delete an item.
import: used to import modules and classes into code.
return: used to exit a function and return a value.
as: used to create an alias.
elif: used to make conditional statements, it's the same as else if.
in: used to check if a value is present in a list, set, tuple, etc.
try: used to make a try…except statement.
assert: used for debugging.
else: used to make conditional statements.
is: used to test whether two variables are equal.
while: is used to make a while loop.
async: is used to write concurrent code.
except: used with exceptions, what should be done in case of an
exception.
lambda: used to create anonymous functions.
with: is used to simplify exception handling.
await: is used to write concurrent code.
finally: used with exceptions, gets executed no matter if an
exception occurs or not.
nonlocal: used to declare a non-local variable.
yield: is used in a generator function.
You can see the list of keywords by executing these:
>>>import keyword
>>>print(keyword.kwlist)
PYTHON VARIABLES
NUMBERS
As we have discussed in previous chapters, a variable is a storage location.
We will be discussing how to create variables in Python and assign values to
them. Dos and don’ts applicable in the Python language in creating variables.
Creating Variables and Assigning Values
Creating variables in Python is simple, you just have to specify the variable
name, then assign a value to it:
<variable name> = <value>
In Python, “=” means assignment, always remember that what is on the left
of the assignment operation is a name for the value or the object on the right.
You assign variables from left to right, if you do it the other way, you will get
a syntax error
2 = x => Output: SyntaxError: can't assign to literal
None of python's keywords can be used as a valid variable name.
Rules for variable naming:
a = True # valid
_b = True # valid
You don't need to declare the variable in advance or assign a data type to the
variable, Python interpreter automatically picks the most suited built-in data
type for it while allocating space for the variable in memory. You cannot
declare a variable without assigning an initial value to it, you should use
None for empty value or null data type. Some examples:
>>>a = 5
>>>print(type(a))
# Output: <type 'int'>
>>>f = 3.5
>>>print(type(f))
# Output: <type 'float'>
>>>b = 'A'
>>>print(type(b))
# Output: <type 'str'>
>>>x = None
>>>print(type(x))
# Output: <type 'NoneType'>
You can have more than one variable in a line and assign values for each
variable you have. Just take note that there must be the same number of
values on the right and left sides of the = operator:
>>>x, y, z = 8, 9, 10
>>>print(x, y, z)
# Output: 8 9 10
>>>print( z)
# Output: 10
>>>a, b, c, d, e = 1, 2, 3, 4
=> Traceback (most recent call last):
=> File "<stdin>", line 1, in <module>
=> ValueError: not enough values to unpack (expected 4, got 3)
a, b, c, d = 1, 2, 3, 4, 5
=> Traceback (most recent call last):
=> File "name.py", line N, in <module>
=> a, b, c, d = 1, 2, 3, 4, 5
=> ValueError: too many values to unpack
You can as well assign just one value to many variables at the same time:
a=b=c=d=e=1
print(a, b, c, d, e)
# Output: 1 1 1 1 1
When you use such cascading assignment, note that all five variables a, b, c,
d and e are five different variable names given to the same int object. If you
assign a different object to one of the variables later, doesn't change the
others:
>>>b = 2
>>> print(a, b, c, d, e)
# Output: 1 2 1 1 1 (as expected)
This is also applicable for mutable data types (like list, dict, etc.) just as it is
also applicable for immutable data types (like int, string, tuple, etc.).
Lastly, variables in Python do not have to stay the same type as which they
were first defined, you can assign another value to a variable, and it could be
of a different data type:
>>>a = 5
>>>print(a)
# Output: 5
>>>a = "Another value"
>>>print(a)
# Output: Another value
STRINGS
Strings are made up of characters, and characters are simply symbols, so we
can say, a string is a sequence of symbols. An example is the English
alphabet which has 26 letters (characters).
As we already know that computers don't deal with characters, they rather
deal with numbers, every character we see it's internally stored as a
combination of 0’s and 1’s. The act of the computer converting characters to
numbers is called encoding, and the reverse act is called deciding. Two
popular encoding used are ASCII and Unicode.
In Python, a string consists of Unicode characters. Unicode includes every
character in all languages, and it brings uniformity in encoding. Unicode can
be learnt from Python Unicode.
How to create a string in Python
You can create a string by ticket characters in a single quote or double
quotes. You can even use triple quotes in Python, although it's generally used
to represent multiline strings and docstrings.
>>>my_string = "Hi”
>>>print(my_string)
>>>my_string = '''Hi'''
>>>print(my_string)
The output of the program will appear like this when it is run:
Hi
Hi
Hi
Hi, this is
Python, First Steps
Addition
To add in Python you will using the "+" operator. For example:
>>>x, y = 3, 5
>>>x + y # return = 8
We can import the operator module:
>>>import operator
>>>operator.add(x, y) # return = 8
Possible combinations (builtin types):
- int and int will gives an int
- int and float will gives a float
- int and complex will gives a complex
- float and float will gives a float
- float and complex will gives a complex
- complex and complex will gives a complex
Subtraction
For subtractions in Python you will using the "-" operator. For example:
x, y = 3, 5
y – x # return = 2
If we import the operator module:
>>>import operator
>>>operator.sub(y, x) # return = 2
Possible combinations (builtin types):
- int and int will gives an int
- int and float will gives a float
- int and complex will gives a complex
- float and float will gives a float
- float and complex will gives a complex
- complex and complex will gives a complex
Multiplication
In the case of multiplications, we will use the “*” operator. Let’s see:
>>>x, y = 2, 5
>>>x * y # return = 10
If we import the operator module
>>>import operator
>>>operator.mul(x, y) # = 10
Possible combinations (builtin types):
- int and int will gives an int
- int and float will gives a float
- int and complex will gives a complex
- float and float will gives a float
- float and complex will gives a complex
- complex and complex will gives a complex
You should note that the * operator is also used for repeated concatenation of
strings:
2 * 'xy' # = 'xyxyxy'
2 * ('x', 'y') # = ('x', 'y', 'x', 'y')
Boolean Operators
Boolean operators are the words: “and”, “or” and “not”. Is very common user
this operators with Python comparation operators:
Figure 7
And: Evaluates the program from the first to the second argument, will
declare both arguments true if and only if both arguments are true, if not, it
evaluates to the first false argument and declare the both arguments false as a
single entity. The possible combinations are:
- a = True and b = True # return True
- a = True and b = False # return False
- a = False and b = True # return False
- a = False and b = False # return False
For example:
>>>a,b = 4,8
>>>a>3 and a<7 # return True
>>>a>3 and b<5 # return False
>>>a<3 and b>5 # return False
>>>a>3 and b<5 # return False
Or: The “or” operator evaluates from the first argument to the second and see
if any of both is true. If one of both is true, then it is true; it will be false only
if both arguments are false. The possible combinations are:
- a = True or b = True # return True
- a = True or b = False # return True
- a = False or b = True # return True
- a = False or b = False # return Fales
Some examples using the same variables from above (a,b = 4,8):
>>>a>3 or a<7 # return True
>>>a>3 or b<5 # return True
>>>a<3 or b>5 # return True
>>>a<3 or b<5 # return False
Not: This operator returns the opposite value of the argument. Look the
following statements:
a = True
b = not a # return b= False
b = False
c = not b # return c= True
So, if we continue using the same variables, we can have these examples:
>>>b=a>3 or a<7 # return b=True
>>>c=not b # return c=False
In place Operations
When you are programming, is very common have codes like this:
x=x+1
or
x=x*2
You can write these effectively as in place operations:
x += 1
# and
x *= 2
You can use any mathematic operator before the '=' character to make an in
place operation (assignment operators):
Figure 8
Let’s do an example:
>>>a=2
>>>a-=1 # return a = 1
>>>a+=2 # return a = 3
>>>a*=6 # return a = 18
>>>a/=2 # return a = 9
>>>a//=2 # return a = 4
>>>a%=1 # return a = 1
String Operations
You can perform many operations with strings, this is one of the reasons it’s
one of the most used data types in Python. You con concatenate two or more
strings into a single one, using the “+” operator. Also, you can use the “*”
operator to repeat strings for as many times you want. Let´s see some
examples:
>>>str1 = ' Python '
>>>str2 =', First Steps'
>>>print(str1 + str2) # Return: Python, First Steps
>>>print(str1 * 3) # Return: PythonPythonPython
FUNCTIONS
In Python, functions are used to provide organized, reusable and modular
code to carry out a specific operation. Functions make coding simpler,
prevent unnecessary logic, and make codes easier to follow. Python has many
built-in functions like functions like print(), input(), len(), etc. Aside these
built-in functions, you're free to create your unique functions to carry out
more unique operations – they are user defined functions.
How to Define and Call Simple Functions
The most common way to define a function in Python is by using the “def”
statement. We can use the following syntax:
def function_name(parameters): statement(s)
The function_name is known as the identifier of the function; parameters are
optional list of identifiers, they get bound to the values supplied as arguments
whenever the function is called; statement(s) (also known as the function
body) are a nonempty sequence of statements executed each time the function
is called. This means a function body cannot be empty, just like any indented
block.
Below is an example of a simple function definition that is to print Python,
First Steps each time it’s called:
>>>def book1():
… print("Python, First Steps")
Now let’s call the defined greet() function:
>>>greet() # Return: Python, First Steps
If we define an argument, will get something like this
>>>def book2(title):
… print(title)
After that the book2() function must be called with an argument:
>>>book2("Python, First Steps")# return: Python, First Steps
Also you can give a default value to that function argument:
>>>def book3(title="Python, First Steps"):
… print(title)
Now you can call the function without giving a value:
>>>book3() # Return: Python, First Steps
Another interesting example could be:
>>>def divide(dividend, divisor):
… print(dividend/divisor)
When you call the function, give values for the arguments, listing them in
order
>>>divide(30, 5) # return 6
How to define functions with optional Arguments
You have to assign, using “=” symbol, a default value to the argument name.
The syntax is:
>>>def book4(title='default with no arguments'):
… return action
You can call this function in 3 possible different ways
>>>book4("Python, First Steps") # Output: Python, First Steps
>>>book4(title="Python, First Steps") # Output: Python, First Steps
>>> book4() # Output: default with no arguments
Lambda Functions
This creates an inline function that contains one single expression. The
function returns the value of this expression when it is called.
Look at the function:
>>>def book1():
… return “Python, First Steps” # return Python, First Steps
which, when called as:
print(book1()) # output: Python, First Steps
You can write this as a lambda function as follows:
My_book = lambda: "Python, First Steps"
An inline function with the name My_book is created that returns Python,
First Steps. You don't need to write return when creating a function with
lambda. The value after the “:” is automatically returned.
Once assigned to a variable, it can be used just like a regular function:
print(My_book()) # output: Python, First Steps
Recursive Functions
Recursive function call itself in its definition. An example is the
mathematical function, factorial, which is defined by factorial(n) = n*(n-1)*
(n-2)*(n-3)*...*3*2*1. can be programmed as
>>>def factorial(5):
… if n == 0:
… return 1
else:
return n*factorial(n-1)
the outputs here are:
factorial(0)
#out 1
factorial(1)
#out 1
factorial(2)
#out 2
factorial(3)
#out 6
Factorial(4)
#out 24
Factorial (5)
#out 120
as expected. You will notice that this function is recursive because the second
return factorial(n-1), where the function calls itself in its definition.
You can perform some recursive functions by implementing lambda, the
factorial function using lambda would be something like this:
factorial = lambda n: 1 if n == 0 else n*factorial(n-1)
The function outputs will be the same as above.
Python Built-in Functions
CONDITIONALS
Conditionals which involves keywords such as “if, elif, and else” provide the
Python programming language with the ability to perform a number of
actions depending on a true or false condition.
Truth and False Values
Values will be considered false if they evaluate to false when applied to a
Boolean operator or true if they evaluate to true when applied to a Boolean
operator.
The following represents the false value: None, False, 0, 0.0, 0j, 0L, empty
sequence and mapping ('’, “”, [], (), {}). Every other value in Python that
doesn't represent the false value represent the true value.
If, Elif, Else
In Python, you can define a number of conditionals, you will have to use “if”
to precede the conditions, then “elif” for the rest, up until the final “else”.
If and elif statements
The “if” statement checks the condition. If the condition evaluates to be true,
it carries out the body of the statement, if not, it skips the body. The “elif”
statement is optional, if is present, the condition will check it only when the
“if” statement evaluates to be false. If the “elif”condition evaluates to be true,
it carries out the body of the statement, if not, it skips the body. We can have
multiple “elif”, the condition will evaluate each of them, only if the previous
evaluates false.
Else statement
The “else” statement will execute only if the preceding conditional statement
or statements are false. Let’s check the some examples:
>>>Number = 10
>>>if number > 7:
… print("Number is greater than 7.")
……elif number < 7: # Optional clause (you can have multiple elifs)
…… print("Number is less than 7.")
… else:
…… print("Number is 7")
Outputs Number is greater than 7
Other example:
a=2
if a > 3,
print “a is greater than 3”
else,
print “a is less than 3”
# Output: a is less than 3.
EXERCISES
Here you will find three exercises to practice all the content cover by Python,
First Steps. The main idea is you to try to resolve this challenges yourself not
just by using the programming language we are studying, but by applying the
programming concepts and fundamentals, so it would be great if you start
these exercises by creating a flowchart, a pseudocode or both!.
For each exercise you will find references of the elements you need to use, so
you review the examples and, if you need, go again through the theory.
Additionally, there will be an Extra Mile challenge if you want to go a step
beyond. Create a .py file for each exercise. All the exercises can be solved
with the content on this book, this does not mean that is the only way to do it,
as you advance in knowledge, you will find other and better ways to
programming. Also, you will find some great web resources where you can
find more information and examples about Python.
Exercise 1
Odd or Even: Ask the user for a number. Find out if the number is even or
odd, print out an appropriate message using “This is an even number” or
“This is an odd number”. Extra mile challenge: once you have determined if
the number is odd or even, let the user decide if want to select one additional
number or end the program.
Exercise 2
Functions: Create a program that asks the user for a country, a state from
that and a city from that state. The output should show this message: “I want
to visit country, to go to state and visit city on my next vacations”. Extra mile
challenge: give user the choice to change the selection once.
Exercise 3
Write a program that asks the user to enter three integers (x,y,z). Now
calculate the following operations and print the results at the end:
a=w+y
b=y-w
c=y%x
d = y // w
e = y ** w
f=w*x
g=y/x
Conclusion
Congratulations! You have successfully completed Python, First Steps.
During this short adventure we presented the most important aspects of
programming, from defining a problem, that needs to be solved, to prepare a
solution that can be taken to a computer to be understood, processed and
executed. We also showed that the concepts of the main elements for
programming such as variables, control structure, data structure, and syntax,
and then we study how to apply those concepts.
Then we started to enter Python, a language of very high-level language,
which, in this first publishes, we broke down into its most basic elements, as
a strategy to facilitate its study, making each chapter a clear, understandable
and coherent, step forward. In addition, we resumed a little piece of history of
programming and Python.
In the last part, we proposed a series of exercises with the intention of
strengthening what we learned during each chapter. Also, we would like
these exercises to be an opportunity for readers to develop their application
development skills.
As its name suggests, Python, First Steps, is just the beginning of this
journey, which we at IT Learning Adventure, plan to do in an organized way,
giving you accurate information that let you grow and improve your skills
constantly.
We hope you enjoyed it and we invite you to stay tuned to our next
publications.