COMPUTER PROGRAMMING:

2 BOOKS IN 1

PYTHON FOR BEGINNERS

+

RASPBERRY PI

Mastering Python Step By Step and Unlock Powerful Hacks of Using Raspberry Pi

JOHN SNOWDEN

© Copyright 2020 by John Snowden

All rights reserved.

This document is geared towards providing exact and reliable information with regard 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. - From a Declaration of Principles which was accepted and approved equally by a Committee of the American Bar Association and a Committee of Publishers and Associations.

In no way is it legal to reproduce, duplicate, or transmit any part of this document in either electronic means or in printed format. Recording of this publication is strictly prohibited, and any storage of this document is not allowed unless with written permission from the publisher. All rights reserved. The information provided herein is stated to be truthful and consistent, in that any liability, in terms of inattention or otherwise, by any usage or abuse of any policies, processes, or directions contained within is the solitary and utter responsibility of the recipient reader.

Under no circumstances will any legal responsibility or blame be held against the publisher for any reparation, damages, or monetary loss due to the information herein, either directly or indirectly. Respective authors own all copyrights not held by the publisher.

The information herein is offered for informational purposes solely and is universal as so. The presentation of the information is without contract or any type of guarantee assurance.

CONTENTS

PYTHON FOR BEGINEERS

Welcome To Python

Advantages Of Becoming A Programmer

Why Choose Python?

Programming Languages

What Is A Programming Language?

Programming Languages Structure

Low And High-Level Languages

What Languages Exist For Programming?

The Python Language

Project: Hello World

Basic Types

Numeric Types

Boolean Types

String Types

Collections

Lists

Tuple

Set

Dictionaries

Flow Control

Conditional Control Structures

Iterative Control Structures

Functions

How To Define A Function In Python

Control Flow

Arguments And Parameters

Modules And Packages

Modules

Packages

Object-Oriented Programming

Elements And Characteristics Of Oop

Heritage

Polymorphism

Method Overload

Encapsulation

Functional Programming

Higher-Order Functions

Lambda Functions

Text Files

About Files

Read From A Text File

Append Text To An Existing Text File

Binary Files

Regular Expressions

Metacharacters

Sets

Regex Module

Databases

Database Peculiarities

Creating A Database Table

Sql Basics

Error Handling In Python

Syntax Errors

Exceptions

Records

Python Web Development

Contributions Of Python To Web Development

Web Frameworks For Python

Using Django

Website Project: Blog

Final Words

RASPBERRY PI

Introduction

Part I: The Board

Chapter One

The Raspberry Pi

The Raspberry Pi Components

Configuring The Raspberry Pi 4

Why Pick A Raspberry Pi?

Distributions Of Linux For Raspberry Pi

Why Choose The Raspberry Pi And Not Anything Else?

Olpc, Sweets From Cotton, And Arduino

What Are The Raspberry Pi 3's Specs?

How Can I Use My Raspberry Pi 3 To Get The Most?

Chapter Two

Getting Started With The Raspberry Pi

Pi Drawbacks

Raspberry Pi Benefits

Set Up & Launch Your Raspberry Pi

Applications Of Raspberry Pi

Chapter Three

Linux System Administration

An Overview

Introducing Raspbian

Pi Safe Shutdown

Chapter Four

Setting Up The Troubleshooting

Chapter Five

Configuring The Network

Networking (Wired)

Wireless Networking

Wi-Fi2

Chapter Six

Tool For Raspberry Pi Configuration

User Account Update

Options For The Network

Options For Booting

Choices For Internationalisation

Advanced Options Section

Chapter Seven

Advanced Raspberry Pi Configuration

Part II: Building A Media Centre Or Productivity Machine

Chapter Eight

The Pi: A Home Theatre Pc

Get The Relevant Hardware

Cases With Raspberry Pi

Raspberry Pi Add-Ons Optional

Chapter Nine

The Pi As A Productivity Machine

How Critical Is The Cloud?

Part III: Programming The Pi

Chapter Ten

An Introduction To Scratch

Understanding The Scratch Editor: Scratch Coding Functions Like This

Programming With Scratch: An Example Of A Simple Projec

"Blue Sky" Backdrop Of Scratch

Easy Commands Introduction (15 Minutes)

Introduction To A Command Sequence (15 Minutes)

Introduction (15 Minutes) Of Iteration

Chapter Eleven

An Introduction To Python

Python Syntax Compared To Other Programming Languages

Features Of Python Programming Language

Chapter Twelve

Minecraft Pi Edition

Tips For Keeping The Process As Fluid As Possible

Part IV: Hardware Hacking

Chapter Thirteen

Learning To Hack Hardware

A Short Soldering Guide

How To Properly Solder

Protection Checklist For Soldering

During Welding:

Chapter Fourteen

The Gpio Port

Pins From Gpio

Chapter Fifteen

The Raspberry Pi (Camera Module)

Chapter Sixteen

Add-On Hardware

Raspberry Pi Case Official

Hat Meaning

Part V: Appendixes

Appendix A: Python Recipes

Appendix B: Camera Module Quick Reference Of Raspberry Pi

Shared Options

Raspivid Options

Appendix C: Hdmi Display Modes

PYTHON FOR BEGINNERS

A Practical Guide For The People Who Want to Learn Python The Right and Simple Way

Welcome to Python

Hi! This book is made for all those people who like to work with computers and who want to enter this world at a deeper level through the programming language, which is the means of communication between us and the technology that we use. allows to eliminate the barriers between the digital world and ours, taking control through orders, consecutive actions, data and algorithms that control the physical and logical behavior of a machine. Programming possibilities are unlimited. We can observe it from something as every day as the apps on our cell phone to incredible creations in robotics and artificial intelligence. If you are reading this, it is because you have discovered the potential that programming has as a professional career in a world that, due to various circumstances.

Advantages of Becoming a Programmer

If you are here out of curiosity, because you have already found some information about the programmer's world, but have not yet decided if you want to master a programming language, I will tell you that being a programmer brings many attractive benefits. Among the reasons that exist to be a programmer, we can mention these ten:

•

We are in the best time to be programmers. The technological world is growing all the time, and everyday technology is becoming more important in all types of organizations. It will not go out of style or go anywhere. It is here to stay, and every day, its use will be as natural as possible. This continuous and accelerated growth is easy to observe and important, which guarantees a promising future.

•

Therefore, the labor field is quite extensive since there is a great demand for programmers in companies of all kinds, who have understood that only through the use of available technological tools will they be able to add value and compete in the market satisfactorily. In addition, there are many ramifications in programming, which means that there will always be a field that is ideal for you. Programming does not necessarily have to be tedious. If you find your ideal specialization, it will be something that you always enjoy, which will be a source of pride and satisfaction.

•

In addition to being relatively easy to find work, programming projects are well paid worldwide, as there are not enough professionals in this industry yet. This means that salaries are above average, in some cases by a fairly high margin, and it is very likely that your employer or your clients will offer you attractive benefits to retain your talent if they manage to understand each other well.

•

You can work from home. Programming does not necessarily have to be carried out in an office environment, since you will be providing the service of creating intangible products, which can be easily shared between computers, avoiding the need for main meetings. In fact, most companies prefer it this way since most are not specifically dedicated to technology, and it is not feasible for them to have plant personnel who are 100% dedicated to it. A freelancer goes hand in hand with a programmer. Tired of complicated bosses? Can't find a schedule that suits your needs? Do you want to start? Scheduling is for you.

•

You will exercise your brain since "computational thinking" is excellent for learning to process any type of information properly. You will also to solve problems more efficiently and effectively. Your mind will be much more structured, and that will provide different perspectives. That is, you will see the world with different eyes.

•

Being a programmer will awaken your creative side. With very basic knowledge, you can do the most diverse things. A small idea could easily become a great project by contributing to your portfolio or even selling for a large sum of money. As Mark Zuckerberg put it: "Programming allows you to create something new entirely from scratch."

•

Scheduling lets you create and take control in a digitized world. You will no longer have to worry about them threatening your privacy or because they sell your data; if you do not want it, you will have enough information to put security locks where you need it.

•

Python is the language of the future. Although we have been educated to focus on traditional languages, such as English, Spanish, French, Chinese, among others, what really keeps everyone connected is the language used by computers.

•

You don't need a degree. Programming is about dedication and effort, and with the application of knowledge that you can acquire in a very short time, you can create projects that show your potential clients what you are capable of.

•

And finally, what we will show you in this book: anyone can learn! Just like learning a new language, playing an instrument, or practicing a sport, you don't need any specific prior knowledge. All we will require is your determination to become a programmer and follow the steps that we provide in this book with their respective topics and exercises.

If you are already convinced, I invite you to continue reading this book. I promise you that the more you go into each of the topics presented, you will discover all the potential that programming has in a practical way and that you are capable of doing much more than you imagined. Scheduling is not difficult when you invest the right amount of time, are persistent, and value selflearning. You will find that solving the challenges faced during code development is rewarding, and when you can visualize your creations after a day of study, you will feel motivated to continue and eager to know more.

Why Choose Python?

Let's start by understanding why we choose the programming language that we will be learning. Python 32 is a high-level, clean, elegant, agile, and simple programming language. Unlike many of the great successes that exist in the market, Python was created by Guido Van Rossum, who developed all the components of this language but does not alone receive the merit of what we have today, as thousands of programmers and other anonymous professionals have contributed to its improvement and expansion. The creation of Python occurred under these circumstances according to the words of the creator himself:

“In December 1989, I was looking for a 'hobby' programming project that would keep me busy during Christmas week. My office (…) would be closed, but I had a computer at home and not much else in my hands. I decided to write an interpreter for the new scripting language I had been thinking of lately: a descendant of ABC that would appeal to Unix / C hackers. I chose Python as a working title for the project, being in a slightly lighter mood. irreverent (and a huge Monty Python's Flying Circus fan).”

Guido created Python keeping in mind that he wanted this to be an easy and intuitive language, be open-source so that everyone could contribute to its development, be a code as understandable as English itself, and be allowed to develop in a short time to achieve every day usage.

Python has common expressions that make it require fewer lines of code to perform basic tasks than others that exist on the market. Some even define this programming language as minimalist. Python's syntax is very friendly and is its most prominent element.

At first, it was designed for Unix. Later, it was included in other operating systems, so that today we can use it on Windows and Mac OS as well. There will never be a problem with performance as long as the correct interpreter is used. It is also multiparadigm (a paradigm indicates the way to solve a problem) since it allows you to create programs with more than one programming style. Allowing programmers to choose the best paradigm for each project, since all problems require specific solutions, makes it more effective and efficient. It is also multipurpose as it has a multipurpose nature. For example, R is good for data science and Machine Learning, but not in web development. With Python, you can do everything at once.

As if this were not enough, it has a standard library provided by the official Python website, which provides many free resources. It also has a multitude of unofficial libraries, which allows them to execute complex functions more easily than other languages. All of this thanks to the act that it is an open code, which allows the general public to modify it according to their needs and that. In addition, the code is constantly improving, which means that your learning will be low cost, you will be able to work Without the need for a lot of investment each project and therefore, and you will turn programming into a very profitable activity. You will never be alone! Python has a community of developers looking to contribute, share, and develop new software,

Python brings together the best of all languages through a simple language that offers speed and great performance. For all this, the learning curve will be very short, and in a short time you will be ready to perform in areas such as games, web development, graphic design, scientific computing, data processing, financial applications, artificial intelligence, software development, among others. With Python, everything is possible because it offers the best versatility.

Programming Languages

What is a Programming Language?

Let's start by understanding what a language is. This is a very convenient method to express information and later create sequences of actions necessary to perform a task. In our environment, there are two types of language:

•

Natural language: Natural language is what we use in our daily lives. That is, it refers to the language we speak (English, Spanish, French, Chinese ...). It has the advantage that we learn it gradually thanks to exposure, observation, and practice, for which it is given the name of natural. However, it has disadvantages, such as limited comprehension since it is difficult to understand people when they speak a different language. There is sometimes ambiguity or imprecision because, in most languages, there are synonyms or the words change their meaning according to their context.

•

Symbolic language: It is a set of artificially created symbols to express specific meanings that can be universally understood and avoid ambiguities. Therefore, this type of language can be understood internationally, and each symbol will always have the same meaning regardless of where it is used.

Therefore, a programming language is a clear example of a language that occupies an intermediate position between natural language, used particularly by humans, and the precise symbolic languages that allow us to interact with a machine. In this regard, we should be particularly grateful to the progressive evolution of translation languages that allow us to convert instructions from a programming language to a machine language, making the programming process that we carry out today look the same every time more to natural languages, making the task easier.

Programming languages use Western alphabet characters and numbers as symbols. This set or sets of characters are programmed by the user and interpreted by the computer. Nowadays, we can distinguish between codes due to their use and popularity: ASCII (American Standard Code for Information Interchange) and EBCDIC (Extended Binary Coded Decimal Interchange Code). The first uses 7 bits for each character to represent, which translates into a total of 27 different characters to represent. In its extended version, it uses 8 bits, making it consist of 256 characters. This code is the standard on all personal computers. On the other hand, the second code always uses 8 bits per character, making it 256 in total. This type of code is used primarily in mainframe computers (commonly used to process data for corporate and scientific research functions) and mid-range computers (business-oriented).

Programming Languages Structure

A language is made up of a set of symbols and words (vocabulary and lexicon) and a set of rules (syntax and semantics) that allow symbols to be grouped to form the language's sentences. The programming language has a set of special rules that allow it to build a program. We will understand by a program, a set of commands or instructions based on a programming language that a computer interprets to solve a problem or execute a specific function.

Although the terms "programming language" and "computer language" are often used as if they were synonyms, it does not have to be that way, since computer languages encompass programming languages and others, such as HTML (language for the markup of web pages that is not properly a programming language).

A programming language allows one or more programmers to specify precisely what data a computer should operate on, how this data should be stored or transmitted, and what actions it should take under a wide range of circumstances. All this, through a language that tries to be relatively close to human or natural language. A relevant characteristic of programming languages is that more than one programmer can have a common set of instructions that can be understood among them to carry out the construction of the program in a collaborative way.

The basic elements of language are the lexicon, syntax, and semantics. Within the lexicon, we can distinguish the following components:

•

Identifiers: symbolic names that will be given to certain programming elements (e.g., names of variables, types, modules, etc.).

•

Constants: data that will not change its value throughout the program.

•

Operators: symbols that will represent operations between variables and constants.

•

Instructions: special symbols that will represent processing structures and the definition of programming elements.

•

Comments: text that will be used to document the programs.

The rules (syntax) or productions specify the symbol sequence that make up a sentence in the language.

Finally, semantics defines the meaning of the syntactic constructions of the language and of the expressions and data types used.

Low and High-Level Languages

Programming languages can be classified into low-level and high-level languages depending on how close or far they are from the architecture of the machine on which they will operate.

Low-level languages take their fundamentals from the Von Neumann machine, so they are at a level very close to the machine. The instructions are different in each computer, so they are difficult to program and are costly. They are classified into machine language and assembly language.

In contrast, high-level languages are based on abstract machines, and that makes it easier for people to understand them. Their instructions are more flexible and have greater power than the previous language types, but a translator is necessary to convert the program to machine language. Even so, as it does not depend on the processor, the same program works for different computers.

High-level languages have several philosophies for programming, also called paradigms, of which we can highlight the following:

•

Imperatives: they are languages controlled by commands or instructions. It is created through statements that, when executed, make the interpreter change the value of one location or more in its memory; in other words, it causes a change of state. The successive change of states is what causes the achievement towards the goal or the creation of a solution. Examples of languages of this type are C, C ++, FORTRAN, ALGOL, PL / I, Pascal, Ada, Smalltalk, and COBOL.

•

Applications: Also known as functional, these look at the desired result instead of the available data. This means that the states through which the machine must go to obtain a response are not examined. Rather, the function that must be applied to the state of the machine is identified through access to the set of variables and the creation of combinations in specific forms to get an answer.

•

Rule-based languages: They are executed by verifying the presence of a condition that enables the execution of appropriate action. It is similar to an imperative language, with the difference that the sentences are not sequential. Conditions are made with logical expressions. Therefore, they are also known as logical programming languages. Among these languages, Prolog is the main representative.

•

Object-oriented programming: Complex data objects are created, and then a limited set of functions are designated to operate on that data. Complex objects are designated as an extension of other simpler objects, inheriting their properties. The programs created with these languages are as efficient as those created with imperatives and are as flexible and reliable as those created with application languages.

Whenever a high-level language is being used, an interpretation or translation process will be necessary, which helps to convert the programming language to machine language so that it can be executed. The process of translating and converting into a program is different depending on the compiler or interpreter used. A compiler is a program that is only responsible for carrying out a translation, not the program, while an interpreter is designed to both translate and execute.

This gives rise to two types of errors. Compilation errors are produced in the compilation or interpretation phase of a program, when the syntactic or semantic rules are not met. Execution errors are produced during the program’s execution. These error messages are not produced by the compiler, but by a piece of code that the compiler adds to the program. The third type of error can occur when no reference is made to either of these two. This problem can be observed when the program does not give any error, but the results are not as expected. It may be because the algorithm has been incorrectly implemented or because the algorithm was poorly made.

In short, when we refer to a programming language, we are talking specifically about a set of commands or commands that describe the desired process. Each language has its own instructions and statements, and the combination of both allows us to build computer programs. It is important to emphasize that a programming language is not an application or the program itself, but rather the tool that allows us to create and modify them.

What Languages Exist for Programming?

In 1945, the mathematician and chemist Jonh (Janos) Von Neumann presented the general principles that a general-purpose machine should follow. The first language in which computers were programmed was that of the processor, that is, instructions analogous to those present in Von Neumann's machine. However, it was necessary to take into account the machine’s details in order to perform any calculation, and it was also very tedious to introduce the program into the computer.

In 1951, just seven years after Von Neumann introduced the concept of the stored-in-memory program, Wilkes, Wheeler, and Gill describe a program loader that converts from decimal to binary values to allow for greater convenience in encoding instructions and addresses. In order to simplify programming, assemblers gradually became richer until they became translators of symbolic representations (mnemonics) from machine language (assembly languages) to machine language itself. Assembly languages are still close to machine languages and, although they considerably simplify the programming process, they maintain two of their main drawbacks.

That is why an attempt was made to create a new language that was not based directly on the machine's own instructions (that did not depend on the specific machine) but rather on an abstraction of these, and that was more comfortable for the programmer. In the same way, physical devices (registers, memory cells, etc.) would not be used directly, but abstractions of these (variables). In this way, a new concept of programming language arose, where each language has an abstract machine associated with which your code can be run.

If we want to run programs written in a high-level language on a specific computer, we must translate them into other equivalents in a specific machine code (manually or through a process called compilation) or have a tool that reads the program and interprets it step by step the meaning of each sentence in the program (interpretation process). Working in this direction, between 1954 and 1958, John Backus led a working group that aimed to carry out a machine code translator of mathematical formulas that would express calculations. The result was both the specification of a high-level language, Fortran, and the realization of a compiler that translated said language into the machine code of a specific computer (IBM 704).

Around 1960, three decisive languages were created: Algol 60, Cobol, and Lisp. In 1958, Lisp, designed by John McCarthy, was a very innovative language in the sense that it is far removed from the Von Neumann concept of the machine. It is based almost exclusively on the use of functions and lambda calculus, and its main purpose was symbolic calculus. It was the precursor of so-called functional languages. This language has been widely used in the field of artificial intelligence. In 1959, the US Department of Defense commissioned the Cobol. Its objective was clearly practical, and although it was carried out without taking into account some of the advances made at the time in the design of programming languages, it was innovative in the treatment of data. It was also the first standardized language, which favored its later use. In 1960, Algol 60 was primarily an academic language where numerous innovative concepts were introduced and adopted by many later languages. The language was fully specified with the BNF notation, a formalism equivalent to non-contextual grammars. Already in 1964, the Basic was born. This language was designed from the user's point of view. That is, the language was intended to be easy to learn and use. This language was quite successful in teaching and especially in the programming of the first microcomputers, but it was hardly used in the professional environment. Given the above, Simula was developed in 1967, based on the Algol 60.

Pascal was born around 1970 after the software crisis. Niklaus Wirth created a simple and clear language that allowed us to face the increasing complexity of the programs of the time. It is the first language based exclusively on structured programming, and thanks to its simplicity, it has been the ideal language on which to develop the semantics of languages and formal verification, whose beginnings also date back to these years. In addition, Pascal has been a good progenitor of later languages. In this sense, Wirth later designed the Modula-2 language built on many concepts introduced in Pascal, although he emphasizes the construction of the program understood as a set of independent modules. After Pascal, a multitude of languages were developed, including C, which at the cost of a lower level of abstraction, provided great flexibility and control over the machine’s resources. The concept of concurrent programming also appeared around this time. The first logic programming language, Prolog, was developed in 1975 by the Kowalski and Colmerauer groups. However, unlike what happened with other languages, its gestation was quite long. It can be considered that the beginnings of Prolog are from 1960. Like Lisp, Prolog is far from the Von Neumann machine’s concept, and it is based almost entirely on first-order logic. Prolog has an important advantage over other languages that the verification of programs is almost immediate due to its logical base; however, it has the counterpart that it is usually quite inefficient. it was developed in 1975 by the Kowalski and Colmerauer groups. Prolog has such an important advantage over other languages that the verification of programs is almost immediate due to its logical base; however, its counterpart is usually quite inefficient.

In 1983, Ada was created, a language developed under the US Department of Defense’s auspices. It is largely based on Pascal, although it is more complex. It allows us to adequately address concurrent programming and exception handling and introduces the concept of overload.

Currently, there are a large number of new languages (C ++, Java, Modula-3, Oberon, Delphi, Eiffel ...). Most of the evolutions of those presented here, to which some of the concepts discussed above have been added such as object orientation, exception handling, overhead, modularity, etc.

Python is one of the most widely used programming languages today, and the trend continues to rise. It has it all: it is open-source, simple, and easy to understand syntax, thus saving time and resources. It is one of the best to start with in the world of programming. Python is a versatile language that can have multiple applications such as Artificial Intelligence, thanks to libraries like Keras or TensorFlow. It can also be useful for Big Data applications, due to data processing libraries. This programming language is also used in web development, especially thanks to its Django or Flask frameworks. To give a few examples, the SemRush or Reddit websites are developed with Python.

The Python Language

It is a high-level programming language (far removed from machine language). It is a platform independent and object-oriented scripting language prepared to carry out any type of program, from Windows applications to network servers or even web pages. It is an interpreted language, which means that it is not necessary to compile the source code to execute it, which offers advantages such as the speed of development and disadvantages such as lower speed.

The creator of the language is a European named Guido Van Rossum. Van Rossum's goal was to cover the need for a user-friendly object-oriented language that could be used to deal with various tasks within the programming that is usually done in Unix using C. Python’s development lasted several years, during which he worked for various United States companies. By 2000, it already had a fairly complete product and a development team with which it had even partnered on business projects. He currently works at Zope, a content management platform and application server for the web, of course, completely programmed in Python.

Its general purpose is to create all kinds of programs. It is not a language created specifically for the web, although among its possibilities is the development of pages. Python versions are available on many different computer systems. It was originally developed for Unix, although any system is compatible with the language as long as there is an interpreter programmed for it. It is an interpreted language, which means that the code must not be compiled before its execution. When a compilation is done, it is done in a transparent way for the programmer. In certain cases, when code is first executed, some bytecodes are produced that are saved in the system, serving to speed up the implicit compilation that the interpreter performs each time the same code is executed. Python has a command-line interpreter where you can enter statements. Each statement is executed and produces a visible result, which can help us understand the language better and test the results of executing portions of code quickly.

Object-oriented programming is supported in Python; in many cases, it is an easy way to create programs with reusable components. It has many functions incorporated in the language itself, for the treatment of strings, numbers, files, etc. In addition, there are many libraries that we can import into programs to deal with specific topics such as window programming or network systems or things as interesting as creating compressed files in .zip. It is remarkable that Python has a very visual syntax, thanks to an indented notation (with margins) that is mandatory. In many languages, elements such as curly braces or the begin and end keywords are used to separate portions of code. To separate the portions of code in Python, you must tabulate inwards, placing a margin to the code that would go inside a function or a loop. This helps all programmers adopt the same notations and ensures that everyone's programs look very similar.

Preparing the Work Environment

There are several different implementations of Python: CPython, Jython, IronPython, PyPy, etc. CPython is the most used, the fastest, and the most mature. When people talk about Python, they usually mean this implementation. In this case, both the interpreter and the modules are written in C. Jython is the Java implementation of Python, while IronPython is its C # (.NET) counterpart. By using these implementations, it is possible to use all the libraries available to Java and .NET programmers. PyPy, lastly, is a Python implementation of Python.

Installing Python is very simple. How can you learn a programming language if you don't have access to it? Python 2 tends to come pre-installed on most Apple computers, but you're better off with Python 3. Python 2 is still used by many companies for one simple reason: they built their websites with Python 2 years ago, and they haven't yet updated to Python 3. Python 3 is a major update to the language, with significant changes that make the transition from 2 to 3 very complicated. That's why many companies that have made their page with Python 2 choose to stay with it. The option is that, or rebuild the entire page. New websites are almost always made with Python 3. In the next few years, companies that have stuck with Python 2 will make the switch to Python 3, since everyone is moving to Python 3,

Installing Python on Mac OS X

To start using Python on Mac, we will first resort to the command line. To access this terminal, we can follow two routes:

•

Click on Spotlight and type "Terminal."

•

Or, open the "Applications" folder, then the "Utilities" folder, and finally "Terminal."

Once the terminal is open, try typing the following command and hitting the Enter key:

Jot - 125

This should open and print a list of all the numbers from 1 to 25. With this, we have practiced how to use a terminal.

Now we will acquire Homebrew, a manager of packages that will allow us to install and manage software packages written in Python. To obtain it and leave it functional, we will follow the steps below:

1. View the page https://brew.sh

2. Copy the installation command indicated on the page into your terminal. It should look something like this:

/ bin / bash -c "$ (curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)".

3. A new text will open for you. Once this happens, press the "Enter" key. This will prompt you for a password, type in your computer's password, and press "Enter" again.

4. A new text will open for you. Go to the final lines, and if you read the text “Installation successful,” the process has been a success.

Now we will proceed to install Python; the steps for this will be as follows:

1. Type the following in your terminal:

brew install python3

2. In the new text that will open, the "Summary" line will indicate that you have finished, and it worked.

To check that everything is indeed in order, we will carry out a test as follows:

1. Open your terminal and write the following line to check which version you are working with:

Python3 - version

2. The text you should see after you post the above command is as follows:

Python 3.xx

3. If the above text appears, it means that Python 3 is finally installed and available to be used.

Installing Python on Windows

To get everything ready, we will carry out three processes. The first corresponds to the Python installation. To achieve this, we will follow the following sequence of steps:

1. Visit the page https://www.python.org/downloads/ to install Python 3.5.2.

2. Click on the installer to start the download.

3. Once the installation starts, be sure to click ADD Python to 3.5 paths.

4. Click install now. If the installation was successful, it will indicate this phrase in the installer.

The following process corresponds to the installation of a more suitable terminal so that we can program. Said terminal would be Git Bash:

1. Download Git & Git Bash through the page https://git-scm.com/download/win

2. Accept the license.

3. Allow it to be installed in the default folder and do not make any changes to the configuration.

4. A screen will appear, indicating that the installation is complete.

To perform a test and verify that everything is in order, you must do the following:

1. Go to the start menu and open Git Bash.

2. Confirm that Python is available by typing: Python - -Version and hitting the Enter key.

3. You should see the text Python 3.xx. If not, it means you have Python 2.7 installed.

4. If you have an older Python installed, uninstall it and restart Git Bash. This way, you should be able to view the previously mentioned text.

Now you must install Pip, a package manager that will allow us to install and manage software packages written in Python:

1. In your terminal, run the following:

curl https://bootstrap.pypa.io/get-pip.py> get-pip.py

2. Once done, write this other line, which will install Pip:

Python get-pip.py

Ready! Now we have Python, a terminal, and a manager installed.

How to Get Python Support

After 20 years of support, Python ended support for Python 2. On January 1, 2020, support for version 2.7 of the Python programming language officially ended. The Python Software Foundation, led by the language's creator, Guido van Rossum, announced that it would no longer receive security updates and bug fixes in the future. This is not something too serious, since the launch of its successor, Python 3, took place no less than 14 years ago, in 2006. In fact, support for Python 2.7 should have ended in 2015. However, the huge popularity of this version (it is still the default version of Python on many Linux distributions) convinced the foundation of the need to support both branches of development and to postpone the "death" date of Python 2.7.

The aforementioned is yet another reason why we suggest you learn Python 3 from scratch. However, you are never alone with either Python 2 or Python 3 since the developer community is large and united. Great software is supported by great people. The user base is enthusiastic, dedicated to encouraging the language’s use, and committed to making it diverse and friendly.

The official Python page is https://www.python.org , which provides all the information related to this programming language; among its main contents, you can find:

•

Beginners Guide: Which is available both for those who want to start programming from scratch (like you!). to veterans who wish to review or update themselves on this topic.

•

Downloads: Even though we have provided you with a very specific guide to get started, you can also explore the Python reads and their corresponding files on the official page.

•

Documentation: Here, you will find the standard library, along with additional tutorials and guides. Knowledge is power!

•

Community: The phrase on the Python page is, “Python community is vast; diverse & aims to grow; Python is Open." It does justice to what is observed in reality. On the same official page, it is possible to have access to the community, where you can have access to FAQs, conferences, and support groups to solve all the doubts that may arise both in your learning process and in your programming career. Some prominent pages where you can connect with the community are:

- PYSLACKERS: This is a community open by Python for programming enthusiasts. It contains learning resources, libraries, and resources, rules, and codes shared by the community itself. Meet this community on the page: https://pyslackers.com/web .

- Python Discord: The place that organizes the community through events and challenges (with prizes!). The ideal place to interact more directly with other developers to learn, obtain resources, collaborate, and solve problems, you will never get stuck. Meet this community on the page: https://pythondiscord.com .

- Python forum: in this place, topics of all kinds are discussed: new information, tips and advice, projects of all kinds (game development, web development ...), tasks (for those who are studying), and you can even share your own developments to get feedback from other people and improve your project. Meet this community on the page: https://python-forum.io

Your learning will not end with this book; being a programmer is a continuous learning process that each of the projects that you will carry out in the future has its own peculiarities, but you will never be alone or adrift. Python puts at your disposal all the tools you could need along the way. Your community will always offer help to those who have less knowledge or are facing too great a challenge. So if you ever encounter difficulties, don't be discouraged and visit the pages shared here, as they will surely be something of value in your new career as a programmer.

Project: Hello World

At last, the time you have been waiting for has arrived. The first program that we are going to write in Python is the classic "Hello, world!" And in this language, it is as simple as:

print ("Hello world")

Run Python and type the above line, and hit Enter. The response you should receive in the console is the text:

Hello world

What we have done here is use the function built-in print() to print the string Hello, world! On our screen. A string is a sequence of characters. In Python, these are enclosed inside quotes, double quotes, or triple quotes.

Next, we will proceed to create a text file with the previous code so that we can distribute our great little program among our friends. Open your preferred text editor and copy the previous line. Save it as "hello.py," for example.

Running this program is as simple as telling Python the name of the file to run:

python hello.py

If you use Windows, the .py files will already be associated with the Python interpreter, so doubleclick on the file to run the program. However, as this program does nothing more than print a text on the console, the execution is too fast to be seen. To remedy this, we are going to add a new line that waits for the user to enter data. This way, a console will display the text "Hello, world!" until we press Enter.

print "Hello world" raw_input ()

We could also run the program from the console as if it were executable in all operating systems:  ./hello.py

Basic Types

Data types are handled in any high-level programming language. Data types define a set of values that have certain characteristics and properties. Let's think for a moment when we were in math class. Surely you had a class in which they taught you the different sets of numbers. The natural ones (1, 2, 3, 4…), the integers (…, -2, -1, 0, 1, 2…), the real ones (… -1.1, -0.3, 2.1…), etc. Well, in programming (and of course in Python), each of those sets would be what we call a data type.

In Python, every value that can be assigned to a variable has a data type associated with it. In Python, everything is an object. So the data types would be the classes (where the properties are defined and what can be done with them), and the variables would be the instances (objects) of the data types. In short, a data type establishes what values a variable can take and what operations can be performed on them.

The basic Python data types are numeric (integer, floating-point, and complex), Booleans, and strings.

Numeric types

Python defines three basic numeric data types: integers, reals, and complex numbers.

Integer numbers

Whole numbers are those positive or negative numbers that do not have decimals (other than zero). In Python, they can be represented by the type int or the type long. Python's int type is implemented low-level by a long type of C. And since Python uses underneath C, like C, and unlike Java, the range of values it can represent is platform dependent.

In most machines, the long of C is stored using 32 bits; that is, by using a Python int type variable, we can store numbers from -231 to 231 - 1, or what is the same, from -2,147,483,648 to 2,147,483,647. On 64-bit platforms, the range is -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Python's long type allows you to store numbers of any precision, being limited only by the memory available on the machine.

When assigning a number to a variable, it will become int unless the number is so large as to require the use of the long type. We can also tell Python that a number is stored using long by adding an L at the end:

# type (whole) return whole long = 23L

We can also represent whole numbers in the binary format octal or hexadecimal.

The numbers octal are created by prepending “0o” to a sequence of octal digits (from 0 to 7):

ten_octal = 0o12

print (ten_octal)

To create an integer in hexadecimal , "0x" must be prepended to a sequence of hexadecimal digits (from 0 to 9 and from A to F).

ten_hex = 0xa

print (ten_hex)

Looking at the numbers in binary , "0b" is prepended to a sequence of binary digits (0 and 1).

ten_binary = 0b1010

print (ten_binary)

Real Numbers

Real numbers are those with decimals. In Python, they are expressed by the type float. In other programming languages, like C, we also have the type double, similar to float but with higher precision (double = double precision). Python, however, implements its float type at a low level by means of a double type variable of C, that is, using 64 bits, then in Python double precision is always used, and specifically, the IEEE 754: 1-bit standard is followed for the sign, 11 for the exponent, and 52 for the mantissa. This means that the values that we can represent range from ± 2.2250738585072020 x 10-308 to ± 1.7976931348623157 × 10308. To represent a real number in Python, the integer part is written first, followed by a period and finally the decimal part:

decimal = 0.2703

You can also use scientific notation and add an e (for exponent) to indicate an exponent in base 10. For example: decimal = 0.1e-3

It would be equivalent to 0.1 x 10-3 = 0.1 x 0.001 = 0.0001

Complex Numbers

Complex numbers are those that have an imaginary part. If you did not know of its existence, it is more than likely that you will never need it, so you can safely skip this section. In fact, most programming languages lack this type, although it is widely used by engineers and scientists in general.

In case you need to use complex numbers, or you are just curious, I will tell you that this type, called complex in Python, is also stored using floating-point because these numbers are an extension of the real numbers. Specifically, it is stored in a C structure, composed of two variables of type double, one of them serving to store the real part and the other for the imaginary part. Complex numbers in Python are represented as follows:

complex = 2.1 + 7.8j

Boolean Types

In Python, the class that represents boolean values is bool. A Boolean variable can only have two values: True or False. These values are especially important for conditional expressions and loops.

These are the different types of operators with which we can work with Boolean values, the socalled logical or conditional operators:

Boolean values are also the result of expressions that use relational operators (comparisons between values):

By default, any object is considered true with two exceptions:

•

That implements the method _bool_ (), and this returns False.

•

That implements the method _len_ (), and this returns 0.

Furthermore, the following objects/instances are also considered false:

•

None.

•

False.

•

The zero value of any numeric type.

•

Sequences and empty collections.

String Types

Once we have finished with the numbers, it’s the letters’ turn. Another essential and basic Python building block are the sequences or character strings. This type is known as a string, although its true class is str. Strings are nothing more than text enclosed in single ('string') or double (“string”) quotes. Inside the quotation marks, you can add special characters escaping them with \, such as \ n, the new line character, or \ t, the tab character.

A string can be preceded by the character or, or the character r, which indicate, respectively, that it is a string using Unicode encoding and a raw string. Raw strings differ from normal strings in that characters escaped by the backslash (\) are not replaced by their counterparts.

Unicode = u ”äóè”

raw = r "\ n"

It is also possible to enclose a string in triple quotes (single or double). This way, we will be able to write the text in several lines, and when printing the string, the line breaks that we entered will be respected without having to resort to the \ n character, as well as the quotation marks without having to escape them.

triple = "" "first line

this will be seen in another line "" "

Strings also support operators such as +, which works by concatenating the strings used as operands, and *, in which the string is repeated as many times as indicated by the number used as the second operand.

a = "one"

b = "two"

c = a + b # c is "onetwo"

c = a * 3 # c is "oneoneone

Collections

A collection of data in programming stores two or more elements in an array with different index numbers, so it helps us to group elements that have something to do with each other. There are four types of data collections in the Python language:

•

List: it is an ordered and modifiable collection. Allow duplicate data.

•

Tuple: it is an ordered and immutable collection. Allow duplicate data.

•

Set: it is a collection that does not have an order or an index. There are no duplicate data.

•

Dictionary: it is a collection without order, modifiable, and indexed. It does not allow duplicate data.

When choosing an arrangement type, it is helpful to understand the properties each one possesses. Choosing the right type for a particular data set could mean retention of meaning and increase the efficiency or safety of the program.

Lists

The lists can contain any type of data: numbers, strings, Booleans, and also lists. It is an ordered and modifiable collection. In Python, these are declared in brackets:

Fruits list = ["Strawberry", "grape", "cherry"]

Print (fruits_list)

If we want to gain access to any element in the list, we will use the following indication, placing the index number (remember that in programming, these start at 0) that we want to print between the brackets.

Fruits list = ["Strawberry", "grape", "cherry"]

Print (fruits_list)

Fruit list = ["Strawberry", "grape", "cherry"]

Print (fruits_list [1])

The use of square brackets to access and modify the elements of a list is common in many languages, but Python has several very pleasant surprises in store for us. A curios thing about the Python [] operator is that we can also use negative numbers. If a negative number is used as an index, it means that the index starts counting from the end to the left; that is, with [-1] we would access the last element of the list, with [-2] the penultimate, with [-3], the penultimate, and so on.

Fruits list = ["Strawberry", "grape", "cherry"]

Print (fruits_list [-1])

Another unusual thing is what in Python is known as slicing or partitioning, and that consists of extending this mechanism to allow selecting portions of the list. If instead of a number, we write two start and end numbers separated by a colon [start: end], Python will interpret that we want a list that goes from the start position to the end position, without including the latter. If we write three numbers (start: end: jump) instead of two, the third is used to determine how many positions to add an element to the list.

Fruits list = ["Strawberry", "grape", "cherry", "watermelon", "cantaloupe", "kiwi", "grapefruit"]

Print (fruits_list [2: 5])

Tuple

A tuple is a collection of data whose order is unalterable. That is, they are elements ordered in a specific sequence and that have importance. In Python, tuples are enclosed in parentheses. Actually the constructor of the tuple is the comma, not the parentheses, but the interpreter shows the parentheses, and we should use them for clarity:

t = 1, 2, 3 >>> type (t) type "tuple"

Also, keep in mind that it is necessary to add a comma for tuples of a single element to differentiate it from an element between parentheses.

t = (1)

type (t)

type "int"

t = (1,)

type (t)

type "tuple"

To refer to elements of a tuple, as in a list, use the [] operator:

my_var = t [0] # my_var is 1

my_var = t [0: 2] # my_var is (1, 2)

We can use the [] operator because tuples, like lists, are part of a type of object called sequences. Allow me a small paragraph to indicate that text strings are also sequences, so it will not surprise you that we can do things like these:

c = "Hello world" "

c [0] # hc [5:] # world

c [:: 3] # hello

Tuples’ difference from lists is that tuples do not have these modification mechanisms through the very useful functions that we talked about at the end of the previous section. They are also immutable. That is, their values cannot be modified once created, and they have a fixed size. In exchange for these limitations, tuples are "lighter" than lists, so if the use that we are going to give to a collection is very basic, you can use tuples instead of lists and save memory.

Set

The set type in Python is the class used by the language to represent sets. A set is a messy collection of unique elements. That is, they do not repeat themselves. The main characteristic of this data type is that it is a collection whose elements do not keep any order and are also unique. These characteristics mean that the main uses of this class are to know if an element belongs to a collection and to eliminate duplicates of a sequential type (list, tuple, or str).

To create a set, enclose a series of elements in braces {}, or use the class constructor set() and pass it as an argument an iterable object (like a list, a tuple, a string ...).

S = {1,2,3,4}

Python distinguishes this type of operation from creating a dictionary by not including a colon. However, a set cannot include mutable objects such as lists, dictionaries, and even other sets.

Dictionaries

A dictionary is a collection without order, modifiable, and indexed. In Python, these are enclosed in braces and have keys and values. This means that there will be different types of values within the same category. For example, let's look at a dictionary of movies and directors:

d = {"Love Actually": "Richard Curtis", "Kill Bill": "Tarantino", "Amélie": "Jean-Pierre Jeunet"}

The first value is the key, and the second is the value associated with the key. As a key, we can use any immutable value: we could use numbers, strings, Booleans, tuples ... but not lists or dictionaries since they are mutable. This is because dictionaries are implemented as hash tables, and when entering a new key-value pair in the dictionary, the hash of the key is calculated so that the corresponding entry can be quickly found later. If the key object were modified after it was entered in the dictionary, obviously, its hash would also change and could not be found.

The main difference between dictionaries and lists or tuples is that the values stored in a dictionary are accessed not by their index, because in fact, they have no order, but by their key, using the [] operator again.

d ["Love Actually"] # return "Richard Curtis"

As in lists and tuples, this operator can also be used to reassign values.

d ["Kill Bill"] = "Quentin Tarantino"

However, in this case, slicing cannot be used, among other things, because dictionaries are not sequences but rather mappings.

Flow Control

A Python program or script is a set of instructions parsed and executed by the interpreter from top to bottom and from left to right. When all the instructions have been executed, the program ends. However, we have tools to alter the program’s natural flow: make a piece of code skip according to this or that condition, repeat a set of instructions, etc.

A control structure is a block of code that allows you to group instructions in a controlled way. To talk about flow control structures in Python, it is essential first to talk about indentation.

In a computer language, indentation is what indents written human language (at the formal level). As for formal language, when one writes a letter, you must respect certain indentations. Computer languages require an indentation. Not all programming languages need an indentation, although it is customary to implement it in order to give the source code greater readability. But in Python’s case, the indentation is mandatory since its structure will depend on it.

A control structure, then, is defined as follows:

Control structure opening:

expressions

Encoding (or coding) is another element of the language that cannot be omitted when talking about control structures. This is nothing more than a directive that is placed at the beginning of a Python file in order to indicate to the system the character encoding used in the file. Utf-8 could be any character encoding. If no character encoding is specified, Python might throw an error if it encounters strange characters:

print "En el Ñágara encontré un Ñandú"

Instead, indicating the corresponding encoding, the file will be executed successfully:

# -*- coding: utf-8 -*-

print "En el Ñágara encontré un Ñandú"

In this section, we will talk about two control structures:

•

Conditional control structures

•

Iterative control structures

Conditional Control Structures

If a program were nothing more than a list of commands to be executed sequentially, one by one, it would not be very useful. Conditionals allow us to check conditions and make our program behave in one way or another, to execute a piece of code or another, depending on this condition.

Conditional control structures are those that allow us to evaluate if one or more conditions are met, to say what action we are going to execute. The condition evaluation can only return 1 of 2 results: true or false.

In daily life, we act according to the evaluation of conditions, much more frequently than we really think: If the traffic light is green, cross the street. If not, wait for the traffic light to turn green. Sometimes, we also evaluate more than one condition to execute a certain action: If the electricity bill arrives and I have money, pay the bill.

To describe the evaluation to be performed on a condition, relational (or comparison) operators are used:

And to evaluate more than one condition simultaneously, logical operators are used:

Conditional flow control structures are defined through the use of three reserved keywords from the language: if , elif Y else .

If

The simplest form of a conditional statement is a if followed by the condition to evaluate, a colon (:), and in the next line and indented, the code to be executed in case this condition is met.

fav = "geekworld.net"

# si (if) fav is equal to “geekworld.net” if fav == “geekworld.net”:

print "You have great taste!"

print "Thank you"

If-else

We are now going to see a somewhat more complicated conditional. What would we do if we wanted certain orders to be executed if the condition was not fulfilled? We could certainly add another if that had the negation of the first as a condition:

if fav == "geekworld.net":

print "You have great taste!"

print "Thank you"

if fav! = "geekworld.net":

print "Wow, it's a pity"

But the conditional has a much more useful second construction. We see in the following example that the second condition can be replaced with an else. If we read the code, we see that it makes a lot of sense: "if fav is equal to mundogeek.net, print this and this; if not, print this other."

if fav == "geekworld.net":

print "You have great taste!"

print "Thank you"

else:

print "Wow, it's a pity"

Elif

There is still one more construction to see, which is the one that makes use of the elif. Our last conditional construction to see is the one that makes use of the elif. Unlike the conditional control structures, the iterative ones (also called cyclical or loops) allow us to execute the same code repeatedly, as long as a condition is met.

if number <0:

print "Negative"

elif number> 0:

print "Positive"

else:

print "zero"

There is also a construction similar to the operator ?. From other languages, which is nothing more than a compact way of expressing an if-else. In this construction, the predicate C is evaluated, and A is returned if it is true or B if it is not true: A if C else B. Let's see an example:

var = "pair" if (num% 2 == 0) else "odd"

Iterative control structures

In Python, there are two cyclic structures:

•

Loopwhile

•

Loopfor

While

The while loop executes a code snippet as long as a condition is met. Let's look at the following example:

age = 0

while age <18: age =

age + 1

print “Congratulations, you have" + str (age)

What we observed previously is that the age variable begins with 0. Since the condition that age is less than 18 is true (0 is less than 18), we enter the loop. Age is increased by one, and the message is printed, informing that the user has reached one year.

Now the condition is reevaluated, and one is still less than 18, so the code that increases the age by one year is rerun and prints the age to the screen. The loop will continue executing until age equals 18, at which point the condition will no longer be met, and the program will continue executing the instructions following the loop.

Now let's imagine that we forgot to write the instruction that increases age. In that case, the condition would never be reached that age was equal to or greater than 18, it would always be 0, and the loop would continue indefinitely writing on the screen. You have reached 0. This is what is known as an infinite loop. However, there are situations where an infinite loop is useful. For example, let's look at a little program that repeats everything the user says until they write goodbye.

while True:

entry = raw_input (">")

if entry == "bye":

break

else:

print entry

To obtain what the user writes on the screen, we use the function raw_input. You don't need to know what a function is or how it works exactly. Just accept for now that in each iteration of the loop, the input variable will contain what the user typed until hitting Enter. We then check if what the user wrote was goodbye, in which case the break command is executed or if it was something else, in which case what the user wrote is printed on the screen. The break keyword exits the loop we are in.

Another keyword that we can find inside the loops is continue. As you may have guessed, it does nothing but goes directly to the next iteration of the loop:

age = 0

while age <18:

age = age + 1

if age% 2 == 0:

continue

print "Congratulations, you have" + str (age)

As you can see, this is a small modification of our congratulations program. This time we have added and if that checks if the age is even, we jump to the next iteration instead of printing the message. In other words, with this modification, the program would only print congratulations when the age was odd.

For

In Python for is used as a generic way to iterate over a sequence. And as such, it tries to facilitate its use for this purpose. This is what a for loop looks like in Python:

sequence = ["one", "two", "three"]

for element in sequence:

print element

Let's look at the following example:

my_list = ['John', 'Anthony', 'Peter', 'Herbert']

for name in my_list:

print name

Another iteration with the loop for can emulate while . In the following example, for each year in the range 2001 to 2013, print the phrase "Year reports":

# - * - coding: utf-8 - * -

for yer in range (2001, 2013):

print "Year reports", str (year)

Functions

Creating functions is inevitable in any type of application. A function is a block of code with an associated name, which receives zero or more arguments as input, follows a sequence of statements which executes the desired operation and returns a value, and/or performs a task. This block can be called when it is needed. Python is a language that gives us a lot of flexibility when creating functions. The use of functions is a very important component of the programming paradigm called structured, and it has several advantages:

•

Modularization: allows segmenting a complex program into a series of simpler parts or modules, thus facilitating programming and debugging.

•

Reuse: allows the same function to be reused in different programs.

Python already defines by default a set of functions that we can use directly in our applications. You have seen some of them in previous tutorials. For example, the function len (), which gets the number of elements in a container object such as a list, tuple, dictionary, or set. We have also seen the function print (), which displays text on the console.

However, as a programmer, you can define your own functions to structure the code in a way that is more readable and to reuse those parts that are repeated throughout an application. This is a critical task as the number of lines in a program grows.

In principle, a program is an ordered sequence of instructions that are executed one after the other. However, when using functions, you can group parts of those instructions as a smaller unit that executes those instructions and usually returns a result.

How to define a function in Python

In Python, functions are declared by typing the keyword def followed by the name of the function and in parentheses, the arguments separated by commas. The def statement is a function definition used to create user-defined function objects. Next, in another line, indented and after the colon, we would have the lines of code that make up the code to be executed by the function:

def my_function (param1, param2):

print param1

print param2

We can also find a text string as the first line of the body of the function. These chains are known by the name of docstring (documentation string) and serve, as the name suggests, as function documentation.

def my_function (param1, param2) :

"" "This function print the two previous values   as parameters "" "

print param1

print param2

It is important to clarify that when declaring the function, all we do is associate a name to the code fragment that makes up the function so that we can execute said code later by referencing it by name. That is, at the time of writing these lines, the function is not executed. To call the function (execute your code), you would write:

my_function ("hello", 2)

The association of the parameters and the values passed to the function is normally done from left to right: as we have given param1 a "hello" value and param2 is 2, my_function would print hello on one line, and then 2. However, it is possible to modify the order of the parameters if we indicate the name of the parameter to associate the value to when calling the function:

my_function (param2 = 2, param1 = "hello")

The number of values that are passed as a parameter when calling the function has to match the number of parameters that the function accepts according to the declaration of the function. Otherwise, Python will complain:

>>> my_function ("hello")

Traceback (most recent call last):

File "", line 1, in

TypeError: my_function () takes exactly 2 arguments (1 given)

To define functions with a variable number of arguments, we put the last parameter for the function whose name must be preceded by a * sign:

def various (param1, param2, * others):

for val in others:

print val

various (1, 2)

various (1, 2, 3)

various (1, 2, 3, 4)

This syntax works by creating a tuple (named others in the example) in which the values of all the extra parameters passed as arguments are stored. For the first call, various (1, 2), the other tuple would be empty since no more parameters than the two defined by default have been passed; therefore, nothing would be printed. In the second call, others would be worth (3), and in the third (3, 4).

You can also precede the name of the last parameter with **, in which case a dictionary would be used instead of a tuple. The keys of this dictionary would be the names of the parameters indicated when calling the function and the values of the dictionary, the values associated with these parameters. The following example uses the dictionary items function, which returns a list of its elements, to print the parameters that the dictionary contains.

def various (param1, param2, ** others):

for i in others.items ():

print i

various (1, 2, third = 3)

It is important to emphasize that defining is not invoking. Let's look at this program:

Def (square (x)

Return x ** 2

If we try to run it, nothing will happen at all; well, at least nothing that appears on the screen. Defining a function just makes Python silently "learn," a calculation method associated with the identifier square. Nothing else. Let's do the test by running the program:

$ Python square.py

Nothing has been printed on the screen. It is not that there is no print, but that defining a function is a process that does not echo on the screen. We repeat: defining a function only associates a calculation method with an identifier and does not imply executing said calculation method.

Control Flow

To ensure that a function is defined before its first use, you need to know the order in which the statements are executed; this is called the control flow or flow of execution. Execution always begins with the first statement in the program. Statements are executed one at a time, in order, until a function call is reached. Function definitions do not alter the flow of program execution but remember that the statements within the function are not executed until the function call is made. Although not common, you can define one function within another. In this case, the inner function definition is not executed until the outer function is called.

Function calls are like a detour in the flow of execution. Instead of going to the next statement, the flow jumps to the first line of the called function, executes all the statements it finds there and resumes execution from where it left off. This sounds pretty simple ... until you remember that one function can call another. While we are in the middle of a function, we might be forced to abandon it and go to execute statements in yet another function. But while we're in this new role, we might as well go out and run yet another role!

Fortunately, Python is good at taking note of where it is so that every time a function completes, the program picks up where it left off in the calling function. When it reaches the end of the program, it ends. What is the moral of this whole story? When you're reading a program, don't read it from top to bottom. Instead, follow the flow of execution.

Arguments and Parameters

When defining a function, the values which are received are called parameters, but during the call, the values that are sent are called arguments. Some of the internal functions require arguments, the values that control how the function performs its task. For example, if you want to find the sine of a number, you have to indicate what number it is. Thus, sine takes a numeric value as an argument. Some functions take more than one argument, such as pow, which takes two arguments: the base and the exponent. Inside the function, the values passed to it are assigned to variables called parameters. Here's an example of a user-defined function, which takes a parameter:

def printDouble (step):

print step, step

This function takes a single argument and assigns it to a parameter called step. The parameter value (at this point, we still have no idea what it will be) is printed twice, followed by a newline character. The name step was chosen to suggest that the name you give to a parameter is up to you, but in general, it is better to choose a more illustrative name than step.

The printDouble function works with any type (of data) that can be printed:

printDouble (Ham)

Ham Ham

printDouble (5)

5 5

printDouble (3.14159)

3.14159 3.14159

In the first call to the function, the argument is a string; in the second, it is an integer, and in the third, it is a floating-point number.

The same composition rules that apply to internal functions also apply to user-defined functions, so you can use any type of expression as an argument to printDouble.

printDouble (Ham * 4)

Ham Ham Ham Ham   Ham Ham Ham Ham

printDouble (math.cos (math.pi))

-1.0 -1.0

As usual, the expression is evaluated before executing the function, so printDouble returns Ham Ham Ham Ham Ham Ham Ham Ham Ham instead of 'Ham' * 4 'Ham' * 4.

We can also use a variable as an argument:

>>> latoya = 'Dafne, half laurel half nymph'

>>> printDouble (latoya) Dafne, half laurel half nymph. Dafne, half laurel half nymph.

Notice an important aspect in this case: the name of the variable that we pass as an argument (latoya) has nothing to do with the name of the parameter (step). It doesn't matter what the value was called in its original place (the place it was invoked from); here at printDouble we call everyone step.

Modules and Packages

Modules

A module allows you to logically organize your Python code. Grouping related code within a module makes the code easier to understand and use. A module is a Python object with arbitrary named attributes that you can bind and reference. Simply, a module is nothing but a file with a .py extension. A module can define functions, classes, and variables. It can also include executable code. Files are their physical counterpart: each Python file stored on disk is equivalent to one module. We are going to create our first module, then creating a small module.py file with the following content:

def my_function ():

print "a function"

class MyClass:

def __init __ (self):

print "a class"

print "a module"

If we wanted to use the functionality defined in this module in our program, we would have to import it. To import a module, use the keyword import followed by the module name, which consists of the file name minus the extension. You can use any Python code file as a module by executing this statement in another Python code file. The import statement has the following syntax:

import you

import re, datetime

When the interpreter encounters an import statement, it imports the module if it is present in the search path. A search path is a list of directories that the interpreter searches before importing a module.

When creating our first module, it must be saved in the same directory as the program that imports it. But in some cases, we may need to import the modules from other directories. When importing a Python module, it goes through all the directories indicated in the PYTHONPATH environment variable in search of a file with the appropriate name. The value of the PYTHONPATH variable can be queried from Python using sys.path import sys sys.path

import sys

sys.path

In this way, for our module to be available to all the system programs, it would be enough to copy it to one of the directories indicated in PYTHONPATH.

The import clause also allows you to import multiple modules on the same line. In the following example, we can see how the modules of the Python os default distribution are imported with a single clause, which includes functionality related to the operating system; sys, with functionality related to the Python interpreter itself and time, in which functions are stored to manipulate dates and times:

import os, sys, time

print time.asctime ()

It is necessary to precede the name of the objects that we import from a module with the name of the module to which they belong, or what is the same, the namespace in which they are located. This allows us not to accidentally overwrite another object with the same name when importing another module. However, it is possible to use the from-import construction to save us having to indicate the name of the module before the object that interests us. In this way, the object or objects that we indicate are imported into the current namespace:

from time import asctime

print asctime ()

Packages

A package is a folder that contains several modules. If modules are used to organize code, packages are used to organize modules. Packages are special types of modules (both are a type of module) that allow grouping related modules. While modules correspond on a physical level to files, packages are represented by directories. Using packages offers us several advantages. First of all, it allows us to unify different modules under the same package name, being able to create hierarchies of modules and sub-modules, or sub-packages. On the other hand, they allow us to easily distribute and handle our code as if they were installable Python libraries. In this way, they can be used as standard modules from the interpreter or scripts without previously loading them.

To make Python treat a directory as a package, you need to create a file __init__.py in that folder. This way, we get Python to understand that it is a package and not a simple folder. In this way, we can access some of the modules of the package. Like modules, import and from-import are also used to import packages to separate packages, sub-packages, and modules:

import package subpackage module

package.subpack.modulo.func ()

Object-Oriented Programming

Object-Oriented Programming (OOP), as we have seen previously, is a programming paradigm. As such, it teaches us a method—proven and studied—which is based on the interactions of objects to solve t a computer system’s needs.

Elements and Characteristics of OOP

The elements of OOP can be understood as the materials we need to design and program a system, while the characteristics could be assumed as the tools that we have to build the system with those materials. Among the main elements of OOP, we can find classes, properties, methods, and objects.

Classes are the models on which our objects will be built. That is the generic area template from which to instantiate the objects, a template that is the one that defines what attributes and methods will have the objects of that class. In Python, a class is defined with the statement class followed by a generic name for the object:

class Object:

pass

Properties, as we have seen before, are the intrinsic characteristics of the object. These are represented as variables, only they are called properties :

class Object ():

color = ""

size = ""

aspect = ""

The methods are functions, technically called methods, that represent their own actions that the object (and not another) can perform:

The methods are functions

class Object ():

color = "gree"

size = "big"

aspect = "ugly"

def float (self):

pass

The classes by themselves are nothing more than models that help us create specific objects.

We can say that a class is an object’s abstract reasoning, while the object is its materialization.  Creating objects is called instantiate a class, and this instance consists of assigning the class as a value to a variable:

class Object ():

color = "green"

size = "big"

aspect = "ugly"

antennas = Antenna ()

eyes = Eye ()

hairs = Hair ()

def float (self):

print 12

et = Object ()

print et.color

print et.size

print et.aspect

et.color = "pink"

print et.color

Heritage

Some objects share the same properties and methods as another object and also add new properties and methods. This is called inheritance: a class that inherits from another. However, the act of inheriting from a class is also often called "extending a class." It is worth clarifying that in Python when a class does not inherit from any other, it must be inherited from an object, which is the main Python class, which defines an object.

Suppose we want to model the musical instruments of a band, then we will have a guitar class, a drum class, a bass class, and so on. Each of these classes will have a series of attributes and methods, but it happens that, by the mere fact of being musical instruments, these classes will share many of their attributes and methods; an example would be the method play().

It is easier to create an Instrument object type with the common attributes and methods and tell the program that Guitar, Drums, and Bass are instrument types, making them inherit from Instrument. To indicate that one class inherits from another, place the name of the class it inherits from in parentheses after the name of the class:

class Instrument:

def __init __ (self, price):

self.price = price

def play (self):

print "We are playing music"

def break (self):

print "You will pay that"

print "Are", self.price, "$$$"

class Battery (Instrument):

pass

class Guitar (Instrument):

pass

As Drums and Guitar inherit from Instrument, they both have a method play() and a method  break(), and are initialized by passing a price parameter. But what if we wanted to specify a new string_type parameter when creating a Guitar object? It would be enough to write a new method __init__for the Guitar class that would be played in place of the Instrument __init__.  This is what is known as overriding methods. Now, it can happen in some cases that we need to overwrite a method of the parent class, but in that method, we want to execute the method of the parent class because our new method does not need more than to execute a couple of new extra instructions. In that case, we would use the SuperClass.method (self, args) syntax to call the method of the same name as the parent class. For example, to call the Instrument __init__method from Guitar, we would use Instrument __ init __ (self, price). Note that, in this case, it is necessary to specify the self parameter.

A class can inherit from multiple classes at the same time. For example, we could have a Crocodile class that inherits from the Terrestrial class, with methods like walk () and attributes like speed_walk, and of the Aquatic class, with methods like swim () and attributes like speed _swim. It is enough to enumerate the classes from which it is inherited, separating them by commas:

class Crocodile (Ground, Aquatic):

pass

In the event that any of the parent classes had methods with the same name and number of parameters, the classes would overwrite the implementation of the methods of the classes further to their right in the definition. In the following example, as Terrestrial is more to the left, it would be the definition of displacement of this class that would prevail, and therefore if we call the displace method of an object of type Crocodile, what would be printed would be “The animal walks":

class Ground:

def move (self):

print "The animal walks"

class Aquatic:

def move (self):

print "The animal swims"

class Crocodile (Ground, Aquatic):

pass

c = Crocodile ()

c.move ()

Polymorphism

It means the ability to take more than one form. An operation can exhibit different behaviors in different instances. The behavior depends on the data types used in the operation. Polymorphism is widely used in the application of inheritance since an object of a derived class is at the same time an object of the parent class, so where an object of the parent class is required, one of the child class can also be used.

In Python, since it is not necessary to explicitly specify the type of the parameters that a function receives, functions are naturally polymorphic. A block of code will be polymorphic when within that code, calls are made to methods that can be redefined in different classes.

Using polymorphism, we can invoke the same method of different objects and obtain different results according to their class. This means that we can call a method exactly the same as another, and the interpreter will automatically detect which of them we refer to according to various parameters, for example, the type of data we pass as an argument when calling it, the class to which it belongs, or we can even specify which method we mean. Polymorphism is a matter of organization and good practice for the programmer who works with many objects and methods.

Allowing the developer not to write, think, and remember many different method names, but instead can call the appropriate object's method with the same name that it would call others.

Polymorphism is used very often, more than we are aware of. Remember that in Python, everything is an object, which makes it very likely that even without resorting to classes, we will use polymorphism. For example, only the print () function prints various types of objects without the need for us to specify anything, and this is also possible thanks to one of Python's properties called "dynamic typing."

Method overload

In Python, method overloading as such does not exist. Those who come from other languages such as Java find some confusion since it is something very common in that language. In Python, overloading is absurd, although there are those who have written about it claiming that it is "good practice in any language."

Method overloading refers to the practice of having different methods with the same name in the same class. In this way, the interpreter or compiler will be able to differentiate them by the types of data that are sent as arguments in the parameters.

In Python, the dynamism that characterizes this programming language causes a conflict by not knowing what type of variables we are referring to. Although it is possible to emulate overloading, we will skip this practice since, although it works well, it is absurd and unnecessary. In Python, you should not have two methods with the same name or call the same method with different types of parameters.

Encapsulation

Encapsulation in programming is a concept related to object- oriented programming and refers to the hiding of a class’s internal state from the outside. In other words, encapsulation consists of making the attributes or methods internal to a class not accessible or modified from the outside, but only the object itself can access them.

In Python, there are no access modifiers, and what is usually done is that access to a variable or function is determined by its name: if the name begins with two underscores (and does not also end with two underscores), it is of a private variable or function; otherwise it is public. Methods whose names begin and end with two underscores are special methods that Python calls automatically under certain circumstances:

Class Student ():

Def_init_ (self.name = ""):

Self.name = name

Self._secret = "asdasd"

a1 = Student ("Josheph")

a1._secret

Traceback (most recent call last):

File “<stdin>”, line 1 in <module>

AttributeError: "Student" object has no attribute "_secret"

Functional Programming

For a few years, it has become fashionable to work with functional programming as if the new generations had re-discovered the advantages over object-oriented programming or began to become aware of the limitations in their way of working.

The principles of functional programming are as follows:

•

Using functions: As the name suggests, everything is built through functions. This way of working is not only simple, orderly, clear, easy to test, but it is also a practice that great military figures such as Julius Caesar and Napoleon have used. No, they did not use Python (at least there is no record of it), but they applied the concept of: "divide and conquer." And functional programming uses this strategy for just about everything.

•

First-class features: Functions are treated as one more variable. They can even be returned.

•

Pure functions: Fully predictive, the same input data will produce the same output data. You can override the input parameter without disturbing the flow of the program.

•

Recursion: Functions can call themselves, simplifying tasks such as traversing data trees or managing controlled loops.

•

Immutability: There are no variables, only constants. Personally understanding its potential and putting it into practice was like resetting my brain; I had to re-learn how to use a variable. Anecdote aside; Where does software usually fail? In the vast majority of cases, it comes from a variable that has been changed. This causes a block of code to be executed with conditions unforeseen. It is necessary to review each variable in different values until we find the culprit. I make a reflection: What if those variables were never modified? Or, being more practical, what if we create a new constant for each modification? What if… I tell you that at the performance level… it is more efficient? It is a very interesting concept to apply.

•

Lazy evaluation (not strict): In functional programming, we can work with expressions that have not been evaluated, or in other words, we can have variables with operations whose result is not yet known. This is called loose screening. One side effect is increased performance, and another is that we can do crazy things like doing calculations with very complex operations or infinite lists without doing calculations. How is this possible? Because you work with mathematical expressions, the value is only calculated when you need it, for example, when performing a print.

Why use functional programming? Functional techniques facilitate the creation of concurrences, help us to reduce problems since the variables are constant and immutable so that we will not observe the programming error derived from the "Mutable global state." Likewise, testing is a faster process because by knowing what parameters to give to a function, we can know what results to expect. Functional programming is not exclusive. It is combined in an excellent way with imperative and object-oriented programming. Since version 3 of Python, this language has adopted native tools. Finally, we will obtain a compliant code that is easy to assimilate and read since it is more comfortable to understand a function than the structuring of an object.

Before starting with examples, it is worth knowing some of the modules that facilitate functional programming in Python. Among them, we can find the following:

•

Intertools: This module comes already installed with the official distribution of python; it provides us with a large number of tools to facilitate the creation of iterators.

•

Operator: We will also find this module already installed with Python, in which we will be able to find the main operators of Python turned into functions.

•

Functools: Also already included within Python, this module helps us créate Higherorder functions, that is, functions that act on or return other functions.

•

Fn: This module, created by Alexey Kachayev, gives Python additional "batteries" to make the functional style of programming much easier.

•

Cytoolz: This module, created by Erik Welch, also provides several tools for Functional programming, specially oriented to data analysis operations.

•

Macropy: This module, created by Li Haoyi brings to Python characteristics of purely functional languages, such as pattern matching, tail call optimization, Y case classes.

Python, without being a purely functional language, includes several characteristics taken from functional languages such as higher-order functions or lambda functions (anonymous functions).

Higher-Order Functions

The concept of higher-order functions refers to the use of functions as if it were any value, making it possible to pass functions as parameters of other functions or to return functions as a return value. This is possible because, as we have already insisted on several occasions, in Python, everything are objects. And functions are no exception.

In the following lines, we can see an example of the above:

def greet (lang):

def greet_es ():

print "Hello"

def greet_en ():

print "Hi"

def greet_fr ():

print "Salut"

lang_func = {“es”: greet_es,

"En": greet_en,

"Fr": greet_fr}

return lang_func [lang]

f = greet ("is")

F()

As we can see, the first thing we do in our little program is called the greet function with a parameter it is. In the greet function, several functions are defined: greet_es, greet_en, and greet_fr, and then a dictionary is created that has as keys text strings that identify each language, and functions as values. The return value of the function is one of these functions. The function to return is determined by the value of the parameter lang that was passed as an argument to say hello. Since the return value of hello is a function, as we have seen, this means that f is a variable that contains a function. We can then call the function referred to by f in the way that we would call any other function, adding a few parentheses and, optionally, a series of parameters between the parentheses. This could be shortened since it is not necessary to store the function that is passed to us as a return value in a variable to be able to call it:

greet (“en”) () Hi

greet (“fr”) () Salut

In this case, the first pair of parentheses indicates the parameters of the hello function, and the second pair, those of the function returned by hello.

Using Map, Reduce, Filter, and Zip

One of the coolest things we can do with our higher-order functions is passing them as arguments to the map, filter, and reduce functions. These functions allow us to replace the typical loops of imperative languages with equivalent constructions.

Map

The function map allows us to apply a function on each of the elements of a collection (lists, tuples, etc ...). We will use this function whenever we have the need to transform the value of one element into another. The structure of the function is as follows:

map (functon to apply, iterable object)

The function to be applied must return a new value. It is from these new values that we will obtain a new collection. Let's see an example:

def square (element = 0):

return element * element

list = [1,2,3,4,5,6,7,8,9,10]

result = list (map (square, list))

print (result)

As of version 3, the map function returns a map object, which we can easily convert to a list. In this case, as the function that we apply on the elements, we can replace it with a lambda function. The code could be as follows:

Result = list (map (lambda element: element * element, list))

Filter

The filter function is perhaps one of the most used functions when working with collections. As its name indicates, this function allows us to filter the elements of the collection. The structure of the function is as follows:

Filter (function to apply, iterable object)

The function to apply will be applied to each of the elements of the collection. This function should always return a Boolean value. All those elements that result in True a fter applying this function, it will be the elements that pass the filter. From these elements, a new collection will be created. Let's see an example:

def greater_than_five (element):

return element> 5

tuple = (5,2,6,7,8,10,77,55,2,1,30,4,2,3)

result = tuple (filter (greater_than_five, tuple))

result = len (result)

print (result)

As of version 3, the filter function returns a filter object that we can easily convert to a tuple.

Reduce

We will use the reduce function when we have a collection of elements, and we need to generate a single result. Reduce will allow us to reduce the elements of the collection. We can see this function as an accumulator. The structure of the function is as follows:

reduce (function to apply, iterable object)

Here, the important thing is to detail the function to apply . This function must necessarily have two parameters. The first parameter will refer to the accumulator, a variable that will change its value for each of the elements in the collection. On the other hand, the second parameter will refer to each element of the collection. The function must return a new value. It will be this new value that will be assigned to the accumulator. This may sound confusing, but it will improve with a couple of examples. Let's start with an imperative approach:

list = [1,2,3,4]

accumulator = 0;

for element in list:

accumulator + = element

print (accumulator)

As we can see, to solve the problem, we had to declare a variable accumulator that starts with the value of 0. As we go through the list, the value of our variable increases. Its new value is the current value plus the value of the item in the list. So far, I don't think there is any doubt. Now let's look at the same example using the reduce function:

from functools import reduce

list = [1,2,3,4]

def function_accumulator (accumulator = 0, item = 0):

return accumulator + element

result = reduce (function_accumulator, list)

print (result)

For each element of the collection, the function is executed, function_accumulator . The function returns the sum of the parameters. This value is stored in our accumulator. At the end of the iteration of all the elements, reduce will return the value of the accumulator.

Zip

The built-in function (i.e., it doesn't need to be imported) zip() takes as argument two or more iterable objects (ideally each one with the same number of elements) and returns a new iterable whose elements are tuples that contain one element from each of the original iterators.

countries =["China", "India", "United States", "Indonesia"]

population = [1391, 1364, 327, 264]

list (zip (countries, populations))

[("China", 1391), (“India”, 1364), (“United States”, 327), (“Indonesia”, 264)]

This function is especially useful in for loops to access the elements of two or more iterables simultaneously:

for country, population in zip (countries, population):

print("{}: {} million inhabitants.". format (country, population))

China: 1391 million inhabitants.

India: 1364 million inhabitants.

United States: 327 million inhabitants.

Indonesia: 264 million inhabitants.

Lambda Functions

The lambda operator is used to create anonymous functions online. As they are anonymous functions, that is, without a name, they cannot be referenced later. Lambda functions are constructed using the lambda operator, the function parameters separated by commas (attention, no parentheses), a colon (:), and the function code. This construction could have been useful in previous examples to reduce code. The program we use to explain filter, for example, could be expressed like this:

l = [1,2,3]

12 = filter (lambda n: n% 2.0 == 0, 1)

Let's compare it to the previous version:

Def is_pair (n):

Return (n% 2.0 == 0)

l = [1,2,3]

12 = filter (is_pair, 1)

Lambda functions are restricted by syntax to a single expression.

Text Files

About Files

Python makes working with files and text very easy. Let's start with the files.

Let's start with a short discussion about terminology. In a previous lesson, depending on the operating system of your computer, Mac or Windows, you saw how information is sent to the "exit command" window in your text editor by using the command print Python:

print (Hello world)

The Python programming language is of the object-oriented type. This means that it is built around a special type of entity, an object, which contains both data as well as a series of methods for accessing and altering the data. Once an object is created, it can interact with other objects.

In the example above, we saw one type of object, the string "Hello world." The string is the sequence of a series of characters enclosed in quotation marks. You can write a string in three different ways:

Message1 = 'Hello world'

Message2 = "Hello world"

Message3: "" "Hello

Hello

Hello world ”” ”

What is important here is to note that, as seen in the first two examples, you can use single or double quotes, but you should never mix the two types in the same string. In the third message, double quotation marks repeated three times indicate a string that spans more than one line.

Therefore the following messages contain errors:

Message1 = "Hello world"

Message2 ='Hello, world'

Message3 ='His name is John O'Connor'

Counts the number of single quotes in the message 3. For this to work correctly, we will have to save the apostrophe. Or rewrite the phrase as:

Message3 = 'His name is John O \ ´Connor'

Print is a command that prints objects in textual form. Combining the print command with a text string produces a statement.

You will use the print command in this way in cases where you want to generate information that needs to be manipulated immediately. Sometimes, however, you will create information that needs to be saved, sent to someone else, or used as input for further processing by another program or set of programs. In these cases, we will want to send information to files on the hard drive instead of sending it to the output command panel. Write the following program in your text editor and save it as file-output.py

f = open ('helloworld.txt', 'wb'

f.write ('Hello, world')

f. close ()

In Python, any line that starts with a pound sign or pound sign (#) is called commentary and is ignored by the Python interpreter. Comments are intended to allow programmers to communicate with each other (or to remind themselves of what the code is doing when they sit in front of it a few months later). In a broad sense, programs are written and formed in a way that makes it easier for programmers to work collectively. The code that is closest to the requirements of the machine is called a low level , while the code that is closest to the language of human beings is called high level . One of the benefits of using a programming language like Python is that it is of a higher level, which makes it easier for us to communicate with you (of course, at a certain cost in terms of computing efficiency).

In this show, f is an object while open, write, and close are methods . In other words, open, write, and close act on the object f, which, in this case, is defined as a .txt text file. This is probably a use of the term "method" that you might expect, and from time to time, you will find that words used in the context of programming have slightly (or completely) different meanings than everyday speech. In this case, remember that "method" means code snippets that perform actions. They run something on one thing and return a result. You can try to imagine this using some real-world referent, such as giving orders to your dog that has been trained previously. Your pet (the object) understands commands (i.e., it has "methods") like "bark," "sit," "lie down," and so on. We will discuss and learn how to use many other methods as we progress.

The name of a variable that we have chosen is f. We could have called him anything. In Python, variable names can be constructed with uppercase letters, lowercase letters, or numbers. But we cannot use the names of the language commands as variables. For example, if we try to name a variable "print," the program will not respond because that is a reserved word that is part of the programming language. Variable names in Python are also case-sensitive, which means that trap, Trap, or TRAP would be representations of different variables.

When you run the program we wrote, the method open tells your computer to produce a new text file called helloworld.txt in the same folder that we created the file-output.py program in. The parameter w indicates that we intend to write content to this new file using Python. Keep in mind that both the file name and the parameter are enclosed in single quotes, so you know that it will be data stored as strings. If you forget to include the quotes, the program will crash. In the next line, your program writes the message "Hello world" (which is another string) in the file and then closes it. Run Python. And although nothing will be written in the output command panel, you will see a status message that will say something like this on Mac:

'/ usr / bin / python file-output.py' returned 0.

While in Windows, you will see:

'C: \ Python27 \ Python.exe file-output.py' returned 0.

Since plain text files include minimal information, they tend to be small in volume, easy to exchange between different platforms (for example, from Windows to Linux or Mac or vice versa), and easy to send from one computer program to another. They can also be read in all text editors.

Read From a Text File

Python also has methods that allow us to get information from files. Write the following program in the text editor and save it as input-file.py . When you click "Run Python," the program will open the text file you just created, read the one-line text it contains, and print the information in the "output command" panel.

f = open ('helloworld.txt', 'r')

message = f.read ()

print(message)

f. close ()

In this case, the parameter r is used to indicate that you are opening a file to read the information it contains. Parameters allow you to choose from a number of different options that a particular method allows. Going back to the pet example, the dog can be trained to bark once if it receives a beef-flavored treat and twice if it receives a chicken-flavored treat. The taste of the prize cookie is the parameter. Each method is different in terms of what parameters it will accept. For example, you can't ask the dog to sing an Italian opera—unless your dog is particularly talented. You can find the possibility of parameters for each particular method on the Python website, or you can even discover them yourself in any search engine by typing the specific method accompanied by the word "Python."

Read is another file method. The content of the file (the single-line message) is copied to the message, which is how we decide to call that text string, and the print command is used to send the content collected in the message to the output command panel.

Append Text to an Existing Text File

A third option is to open an existing file and add more information to it. Note that if you open a file using open and you use the method write, the program will overwrite whatever the file contains. Of course, this is not a problem when creating a new file or when you want to overwrite the contents of an existing file, but it is totally undesirable when you are creating a long list of events or are compiling a large amount of data into an archive. So instead of write, we are going to use the method append, which is designated with a to.

Write the following program in the text editor and save it as file-apend.py. When you run it, this program will open the same helloworld.txt` text file that you created earlier and add a second “Hello world” to the file. The syntax '\ n' represents a new line of text in the file.

f = open ('helloworld.txt', 'a')

f.write ('\ n' + Hello world)

f. close ()

After you've run the program, go to the helloworld.txt file, and open it to see what happened. Close the text file and rerun the file-apend.py program as many times as you like. When you open the helloworld.txt file again, you will see that there will be a series of lines with the message “Hello World” repeated as many times as you run the program.

Binary Files

Not all files are text files, and therefore not all files can be line processed. There are files in which each byte has a particular meaning, and it is necessary to manipulate them knowing the format in which the data is in order to process that information.

To open a file and handle it in the binary form, it is necessary to add a b to the mode parameter.

To process the file bytes instead of lines, use the function content = file.read (n) to read n bytes and file.write (content) to write content to the current position of the file.

The b in the opening mode comes from binary, due to the binary numbering system, since in the computer processor, the information is handled only by zeros or ones (bits) that make up binary numbers.

Although it is not necessary for all systems (in general, the same system detects that it is a binary file without our asking), it is a good habit to use it, even though it serves mainly as documentation.

When handling a binary file, it is necessary to be able to know the current position in the file and to be able to modify it. To obtain the current position, use file.tell (), A that indicates the number of bytes since the beginning of the file.

To modify the current position, use file.seek (start, from), which allows moving a starting amount of bytes in the file, counting from the beginning of the file, from the current position, or from the end.

Regular Expressions

One of the most frequent operations that you have come across is looking for a certain pattern/substring in a list, table, or text file.

This is not difficult if the pattern you are looking for is static, and you know it precisely. For example, if you want to find a certain name in a contact list, just use functions like find () , which are already included in Python.

But what happens when the substring you are trying to find has variants in its writing? For example, suppose that in a certain text, you want to find how many times the name “Händel” appears. Being a Germanic name, in our language, it can be written as "Händel," "Handel" or "Haendel". If you only use functions like find (), you will have to find each variant of the name separately. What if in a binary sequence you want to find all the subsequences of the form 010, 0110, 01110, 011110, and others? Now you can no longer use the find () method once for each case since there are infinite ones. Another way is needed.

This is where regular expressions come into the picture, a very powerful tool that makes it easy to find patterns in text. Regular expressions come from the world of theoretical mathematics, specifically the Theory of Formal Languages, but they are widely used in programming. Without going into mathematical definitions, a regular expression can be thought of as a word, made up of special characters, that serves to identify a set of other words.

I will illustrate it with an example. Let's go back to the beginning when we wanted to find the word Händel in a text. You could search for the three variants ("Handel," "Händel" and "Haendel") separately, or you could find another word that "encodes" these three variants. In this case, the word that is needed would be"H (a | ä | ae) ndel" . The vertical bar is a type of metacharacter used to separate the possible variants for the expression in parentheses. This word is a regular expression, as it identifies a set of other words.

Metacharacters

A regular expression can contain metacharacters, which are symbols that have special meaning when placed inside a regular expression. In the previous section, you have seen the metacharacter |, which is equivalent to the Boolean expression or and is used to separate the alternatives of a word. However, there are many more metacharacters. Before we start with the Python examples, I'm going to show you some of the most common ones.

- The metacharacter '?' indicates "at most one match" of the character that comes immediately before. Thus, the expression "obscure" corresponds to the words "dark" and "obscure." The expression “(re)? Place” would correspond to “place” and “reposition.”

- The metacharacter '*' indicates "zero or more matches" of the character that comes immediately before. Thus, the expression "01 * 0" would correspond to the words 0, 010, 0110, 01110, 011110, etc.

- The metacharacter '+' works similar to the previous one, but indicates "at least one match". The expression "01 + 0" would now correspond to the words 010, 0110, 01110, 011110, etc.

- The metacharacter '{n}' indicates "exactly n matches" of the previous character. For example, the expression “ab {3} a” would correspond to the word “abba”.

- The metacharacter '{n, m}' indicates “between n and m matches”. If the second space is blank, it means "at least n matches". Therefore, the expression "01 {2,4} 0" would correspond to 0110, 01110, 011110, while the expression "01 {2,} 0" would accept the words 0110, 01110, 011110, 0111110, ...

- The metacharacter '.' is a wildcard that can be used in place of any other character. Thus, in a binary alphabet, the regular expression “01.0” would correspond to the words 0100 and 0110.

As you have seen in these examples, the parentheses () are also a metacharacter and are used to group terms and specify the order of operations. The expression “(01) * 0” is not the same as the expression “01 * 0”. The first corresponds to the words 0, 010, 01010, 0101010 and others while the second corresponds to the words 00, 010, 0110, 01110 ...

These are the most common metacharacters that you will find when working with regular expressions, although there are more. It is important to note that the syntax may vary a bit depending on the language and the context in which they are applied. Metacharacters can be combined to form more complex expressions. For example, the expression “fi. * (A | o)” would correspond to the words that begin with “fi” and end with the letter a / o: finite, philosophy, finalize, fixed, physical

Sets

A set is a set of characters enclosed in square brackets [] with a special meaning. Some of the most frequent are:

- [abc]- searches for a match with any of the characters in parentheses. The regular expression "[abc] aa" corresponds to the words aaa, baa, caa. It also works with numeric characters.

- [ak]- searches for a match with any of the alphabetic characters between the first (a) and the last (k). The regular expression "[be] a" corresponds to the words ba, ca, da, ea, while an expression like "[az] aa" would correspond to words that begin with any letter of the alphabet and end in "aa ”.

- [1-9]- is identical to the previous case, but with numeric characters.

- [^ abc]- matches all characters that are NOT inside the brackets. Thus, the regular expression “. * [^ A]” would correspond to any word that does NOT end with the letter “a”.

Regex module

To work with regular expressions in Python, you need the regex module. In the following examples, you will see some of its most basic methods.

To find a pattern in a string, we can use the method search ().

import re

text = "Lorem ipsum pain sit amet, consectetur adipiscing elit"

pattern = "Lorem"

x = re.search (pattern, text) #Searches the pattern inside the text

print (x.span ()) #Writes the initial position and the end of the occurrence

You can also use the method match () , but this only returns a position if the occurrence is at the beginning of the text. This second code will give an error when trying to do the print() of the second match since the "ipsum" pattern is not at the beginning of the text, and therefore, the method match() bring back None :

import re

text = "Lorem ipsum pain sit amet, consectetur adipiscing elit door"

pattern1 = "Lorem"

pattern2 = "ipsum"

x = re.match (pattern1, text) # Searches the pattern inside the text

print (x.span ()) # Writes the initial position and the end of the occurrence

y = re.match (pattern2, text) # Return None

print (y.span ()) #ERROR!

So much match() as search() they only keep the first occurrence found. If you think there may be more than one, you can use the function find iter() to search them all. This code looks for the pattern "pain" in a long text and writes its positions:

import re

text = "" "Lorem ipsum pain sit amet, consectetur adipiscing elit,

sed do eiusmod tempor incididunt ut labor et pain magna aliqua.

Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. "" "

pattern = "pain"

x = re.finditer (pattern, text) #Returns a vector with the occurrences positions

for i in x:

print (i.span ())

In the previous example, we have limited ourselves to searching for a static word in the text, but metacharacters can be used within the pattern to create regular expressions. I will put some examples.

In this first code, the regular expression "01 + 0" is used to find in a binary sequence all the sub-sequences that start and end with zero and only have ones in the middle: 010, 0110, 01110, etc.

import re

text = "010001000100111001"

pattern = "01 + 0"

x = re.finditer (pattern, text)

for i in x:

print (i.span ())

Of course, metacharacters can be combined to create more complex regular expressions. This code asks the user for a binary sequence and checks if it is capicua. The regular expression '(0. {3} 0) | (1. {3} 1)' accepts sequences that start and end with 0 or 1, with any three characters in between.

import re

text = raw_input ("Input a binary sequence of five figures: \ n")

pattern = "(0. {3} 0) | (1. {3} 1)"

valid = False

#The input is checked for validity

if len (text) == 5:

valid = True

for i in text:

if i! = '0' and i! = '1':

valid = False

break

#If the input is valid it is checked if it is capicua

if valid:

x = re.search (pattern, text)

if (x! = None):

print ("Is capicua!")

else:

print ("It is not capicua!")

#If the input is not valid and an error message appears:

else:

print ("ERROR: text is not valid")

This code uses sets to analyze a sequence of three-digit numbers and sticks with those that are odd. Here the method is used in all() that, unlike find iter(), returns a vector with the substrings of the occurrences instead of the positions.

import re

text = "551 889 302 105 012 817 894 206"

pattern = "[0-9] {2} [13579]"

x = re.findall (pattern, text) #Returns a vector with the substrings of the occurrences

for i in x:

print (i)

What does the regular expression “[0-9] {2} [13579]” that I just used mean? We know that a number will be odd if its last digit is odd. So I'm looking for numbers whose first two digits are between 0 and 9 and whose last digit is odd.

In this other example, the set [^] is used to discard all numbers that contain the digit '1'. The "space" character is also discarded to separate each of the numbers:

import re

text = "551 889 302 105 012 817 894 206"

pattern = "[^ 1] {3}"

x = re.findall (pattern, text) # Returns a vector with the substrings of the occurrences

for i in x:

print (i)

Databases

A database is a file that is organized to store data. Most databases are organized like a dictionary in that they are mapped from keys to values. The biggest difference is that the database is on disk (or other permanent storage), so it persists after the program ends. Because a database is stored in permanent storage, it can store much more data than a dictionary, which is limited to the size of memory on the computer.

Like a dictionary, database software is designed to keep data entry and access very fast, even for large amounts of data. The database software maintains its performance by creating indexes as data is added to allow the computer to quickly jump to a particular entry.

Database Peculiarities

However, the types of data and the way they are stored can differ greatly depending on the context exactly, and that is why, over time, a number of different models have been developed to manage databases.

•

Hierarchical: The data that is organized in the form of an inverted tree uses a model where a parent node of information can have several children.

•

Network: An improvement of the hierarchical model that allows a child to have multiple parents.

•

ransactional: Whose sole purpose is the sending and receiving of data at high speeds. These bases are very rare.

•

Relational: This is the model used today to represent real problems and manage data dynamically. It's the one we're going to focus on, but there are others.

•

Documentaries: They allow us to save full text, and in general, to carry out more powerful searches. They serve to store large volumes of historical background information. Together with the relational ones, they are the most used in web development.

•

Object-oriented: This model is quite recent and typical of object-oriented computer models, where it is about storing complete objects in the database. It is possible that it will take on more importance in the future.

•

Deductives: They are databases that allow deductions. They are mainly based on rules and facts that are stored in the database, so they are somewhat complex.

Relational databases are widely used today because it is easy to represent and manage realworld problems. They are based on the idea of creating relationships between data sets, in which each relationship is also a table. Each table consists of records, made up of rows and columns, also known as tuples and fields. Obviously, within relational databases, there are many DBMS. Most are also compatible with Python. Some are paid, others free, some are simple, and others are very advanced. Let's do a review:

•

SQL Server: It is a relational model database management system developed by Microsoft and only available for Windows systems. It is proprietary and a direct competitor of Oracle, MySQL, and PostgreSQL.

•

Oracle: This database is a proprietary object-relational type database management system, developed by Oracle Corporation, considered one of the most complete systems. Its dominance in the enterprise server market was almost total until the appearance of the competition. It is multiplatform, and also the latest versions of Oracle have been certified to work under GNU / Linux.

•

MySQL: It is a relational database management system developed under dual GPL / Commercial license by Oracle Corporation and is considered the most popular open-source database in the world, and one of the most popular in general together with Oracle and Microsoft SQL Server, especially for web development environments.

•

PostgreSQL: It is a free object-oriented relational database management system. Like many other open-source projects, PostgreSQL development is not managed by one company or person but is led by a community of developers who work selflessly, altruistically, freely, or supported by commercial organizations.

•

SQLite: It is a relational database management system contained in a small library written in C. It is a public domain project, and unlike the other systems that use the client-server architecture, its engine is not an independent process, but rather it links with the program by becoming an integral part of it. However, do not be fooled, because although it seems like the simple solution, SQLite in its third version allows databases of up to 2 Terabytes in size and many other functionalities. In short, its configuration is very simple, so simple that it does not exist, so it will not cause problems, and it is the best solution for this course.

As you can see, we find many Relational DBMS. In Python, each of them have free modules and connector programs to communicate the databases and the programming language. Even though they are different systems, the query language does not vary much. Otherwise, it would be difficult to go from one system to another, and the DBMS could not compete with each other.

Apart from programming languages such as Python, focused on the creation of programs, DBMS implement their own syntax or language to make queries and modifications to their registers. The most used language in relational databases is SQL (Structured Query Language), and it is necessary to learn it if we want to use this type of database in our programs. Obviously, this language covers a lot, so in this unit, we will only see some basic queries to use in conjunction with SQLite in our Python scripts. While this chapter will focus on using Python to work with data in SQLite database files, many operations can be more conveniently performed using the software called Database Browser for SQLite, which is freely available at:

http://sqlitebrowser.org/

With the browser, you can easily create tables, insert data, edit data, or run simple SQL queries. In a sense, the database browser is similar to a text editor when working with text files. When you want to perform one or very few operations on a text file, you can open it in a text editor and make the changes you want. When you have many changes to make to, you will often write a simple Python program. You will find the same pattern when working with databases. You will do simple operations in the database manager, and more complex operations will be performed more conveniently in Python.

Creating a Database Table

When you first look at a database, it looks like a spreadsheet with multiple sheets. The main data structures in a database are tables, rows, and columns. In technical descriptions of relational databases, the concepts of the table, row, and column are more formally called relation, tuple, and attribute, respectively. We will use less formal terms in this chapter.

Databases require a more defined structure than Python lists or dictionaries. When we create a table in the database, we must tell the database in advance the names of each of the columns in the table and the type of data we plan to store in each of them. When the database software knows the type of data in each column, you can choose the most efficient way to store and search the data based on the type of data. You can see the various data types supported by SQLite at the following URL: http://www.sqlite.org/datatypes.html

Defining the structure of your data in advance may seem inconvenient at first, but the payoff is quick access to your data, even when the database contains large amounts of data. The code to create a database file and a table called Tracks with two columns in the database is the following:

import SQLite 3

con = sqlite3.connect ('music.sqlite')

cur = conn.cursor ()

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

cur.execute ('CREATE TABLE Tracks (title TEXT, plays INTEGER'))

conn.close ()

#Code: http://www.py4e.com/code3/db1.py

$ Or select Download from this trinket's left-hand menu

The operation connect makes a "connection" to the database stored in the filemusic.sqlite3 in the current directory. If the file does not exist, it will be created. The reason this is called a "connection" is that sometimes the database is stored on a "database server" separate from the server on which we run our application. In our simple examples, the database will just be a local file in the same directory as the Python code we are running. A cursor is like a filehandle that we can use to perform operations on the data stored in the database. Call to cursor() is conceptually very similar to calling open () when dealing with text files.

Once we have the cursor, we can start executing commands on the content of the database using the method execute(). The database commands are expressed in a special language that has been standardized across many database vendors to allow us to learn a single database language. The database language is called Structured Query Language or SQL.

http://en.wikipedia.org/wiki/SQL

In our example, we are running two SQL commands against our database. As a convention, we will display SQL keywords in uppercase, and the parts of the command that we are adding (such as table and column names) will be displayed in lowercase. The first SQL command drops the table Tracks from the database if it exists. This pattern is simply to allow us to run the same program to create the table Tracks over and over without causing an error. Note that the command DROP TABLE removes the table and all its contents from the database (that is, there is no "undo").

Cur.execute ('DROP TABLE IF EXISTS Tracks')

The second command creates a table called tracks with a column of text called title and an integer

cur.execute ('CREATE TABLE Tracks (title TEXT, plays INTEGER'))

Now that we have created a table called tracks, we can put some data in that table using SQL INSERT operation. Again, we start by making a connection to the database and getting the cursor. Then we can execute SQL commands using the cursor.

The SQL INSERT command indicates which table we are using and then defines a new row by listing the fields we want to include (title, plays) followed by the VALUES we want to place in the new row. We specify the values as question marks (??) to indicate that the actual values are passed as a tuple ('My Way' 15) as the second parameter to the call execute().

import sqlite3

conn = sqlite3.connect ('music.sqlite')

cur = conn.cursor ()

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

cur.execute ('CREATE TABLE Tracks (title TEXT, plays INTEGER)')

cur.execute ('INSERT INTO Tracks (title, plays) VALUES (?,?)',

('Thunderstruck', 20))

cur.execute ('INSERT INTO Tracks (title, plays) VALUES (?,?)',

('My Way', 15))

conn.commit ()

print ('Tracks:')

cur.execute ('SELECT title, plays FROM Tracks')

for row in cur:

print (row)

First, we insert two rows into our table and use commit() to force the data to be written to the database file.

Then we use the command SELECT to retrieve the rows we just inserted from the table. In command SELECT, we indicate which columns we would like to extract (title, we play), and we indicate from which table we want to retrieve the data. After executing the statement SELECT, the cursor is something we can loop through in an instruction for. For efficiency, the cursor does not read all the data from the database when we execute the statement SELECT. Instead, the data is read as we walk through the rows in the declaration for. The output of the program is as follows:

Tracks:

('Thunderstruck', 20)

('My Way', 15)

Our loop for finds two rows, and each row is a Python tuple with the first value as title and the second value as the number of plays.

At the end of the program, we run an SQL command to 'CLEAR' the rows we just created so that we can run the program over and over again. The command DELETE shows the use of a clause WHERE which allows us to express a selection criteria so that we can ask the database to apply the command only to the rows that match the criteria. In this example, the criteria now apply to all rows, so we empty the table so we can run the program repeatedly. After the DELETE, we also call commit() to force the data to be removed from the database.

SQL Basics

So far, we have been using the structured query language in our Python examples and have covered many of the basics of SQL commands. In this section, we discuss the SQL language in particular and provide an overview of SQL syntax. Since there are so many different database vendors, Structured Query Language (SQL) was standardized so that we could easily communicate with multi-vendor database systems. A relational database is made up of tables, rows, and columns. Columns generally have a type such as text, numeric, or date data. When we create a table, we indicate the names and types of the columns:

CREATE TABLE Tracks (title TEXT, plays INTEGER)

To insert a row in a table, we use the SQL commandINSERT:

INSERT INTO Tracks (title, plays) VALUES ('My Way', 15)

When using the declaration insert, specify the table name, then a list of the fields/columns you would like to set in the new row, and then the keyword VALUES and a list of corresponding values for each of the fields. The SQL command SELECT used to retrieve rows and columns from a database. The declaration SELECT allows you to specify which columns you want to retrieve, as well as a clause WHERE to select which rows you want to see. It also allows an optional clause order BY to control the sorting of the returned rows.

SELECT * FROM Tracks WHERE title = 'My Way'

Using * indicates that you want the database to return all columns for each row that matches the clause WHERE. Note that unlike Python, in an SQL clause WHERE, we use a single equals sign to indicate a test of equality instead of a double equals sign. Other logical operations allowed in a clause WHERE include <,>, <=,> =,! =, as well as AND / OR and parentheses to build your logical expressions. You can request that the returned rows be ordered by one of the fields as follows:

SELECT title, plays FROM Tracks ORDER BY title

To delete a row, you need a clause WHERE in an SQL statement DELETE. The clause WHERE determines which rows are to be removed:

DELETE FROM Tracks WHERE title = 'My Way'

It's possible UPDATE a column or columns within one or more rows in a table using SQL statement UPDATE as follows:

UPDATE Tracks SET plays = 16 WHERE title = 'My Way'

The declaration UPDATE specifies a table and then a list of fields and values to change after the keyword SET and then an optional clause WHERE to select the rows to update. Single instruction UPDATE will change all rows that match the clause WHERE. If no clause is specified WHERE, perform the UPDATE in all rows of the table. These four basic SQL commands (INSERT, SELECT, UPDATE, and DELETE) enable the four basic operations required to create and maintain data.

Error Handling in Python

In software development, different types of errors can occur. These could be syntax errors, logic errors, or runtime errors. Syntax errors are more likely to occur during the initial development phase and are the result of incorrect syntax. Syntax errors can easily be caught when compiling the program for execution. Logical errors, on the other hand, are the result of incorrect logic implementation. An example would be a program accessing an unordered list assuming it was ordered. Logical errors are the hardest to track down. Runtime errors are the most interesting errors that occur if we don't consider all possible cases. An example would be trying to access a non-existent file.

In this section, we will learn how to handle errors in Python and how to log errors for a better understanding of what happened within the application.

Syntax errors

Syntax errors, also known as misinterpretations, are perhaps the most common type of complaint you get when you're still learning Python:

while True print 'Hello world'

Traceback (most recent call last):

...

while True print 'Hello world'

^

SyntaxError: invalid syntax

The interpreter repeats the faulty line and displays a small 'arrow' pointing to the first place where the error was detected. This is caused by (or at least detected in) the symbol that precedes the arrow: in the example, the error is detected in the print statement since there is a missing colon (':') before it. The file name and line number are displayed, so you know where to look if the input is coming from a program.

Exceptions

Even if the statement or expression is syntactically correct, it can generate an error when you try to execute it. Errors caught during execution are called exceptions, and they are not unconditionally fatal: you will soon learn how to handle them in Python programs. Let's start with a simple program to add two numbers in Python. Our program takes two parameters as input and prints the sum. Here is a Python program for adding two numbers:

def addnumbers (a, b):

print a + b

addNumbers (5, 10)

When writing the above program, we didn't really consider the fact that something could go wrong. What if one of the parameters passed is not a number?

addNumbers ('', 10)

We have not handled that case; therefore, our program will break with the following error message:

Traceback (most recent call last):

File "addNumber.py", line 4, in <module>

addNumbers ('', 10)

File "addNumber.py", line 2, in addNumbers

print a + b

TypeError: cannot concatenate 'str' and 'int' objects

We can handle the above question by checking if the parameters passed are integers. But that does not solve the problem. What if the code breaks for some other reason and causes the program to crash? Working with a program that breaks when encountering an error is not a good sight. Even if an unknown error has occurred, the code must be robust enough to handle the break gracefully and let the user know that something is wrong.

In Python, we use the declarations tryYexcept to handle exceptions. When code breaks, an exception is thrown without crashing the program. We are going to modify the program that adds numbers to include the declarations tryYexcept.

def addNumbers (a, b):

try:

return a + b

except exception as e:

return 'Error occurred:' + str (e)

print addNumbers ('', 10)

Python would process all the code inside the statements try and except. When it encounters an error, control is passed to the block except, skipping the code in the middle. As seen in the above code, we have moved our code within a statement try and except. You try to run the program, and it should throw an error message instead of the program crashing. Also, the reason for the exception is returned as an exception message. The above method handles unexpected exceptions. Let's take a look at how to handle an expected exception. It assumes that we are trying to read a file with our Python program, but the file does not exist. In this case, we will handle the exception and let the user know that the file does not exist when it occurs. Take a look at the file reading code:

try:

try:

with open ('fname') as f:

content = f.readlines ()

except IOError as e:

print str (e)

except exception as e:

print str (e)

In the above code, we have handled the file reading inside an exception handler IOError. If the code breaks due to the unavailability of the file name, the error would be handled within the controller IO Error. Similar to the exception IO Error, there are many more standard exceptions like Arithmetic, Overflow Error, and Import Error, to name a few.

We can handle multiple exceptions at once by putting together the standard exceptions as shown:

try:

with open ('fname') as f:

content = f.readlines ()

printb

except (IOError, NameError) as e:

print str (e)

The above code would show the exceptions IOError and NameError when the program runs.

Suppose we are using certain resources in our Python program. During the execution of the program, an error was encountered, and it was only half executed. In this case, the resource will be kept unnecessarily. We can clean up such resources using the clause finally. Take a look at the following code:

try:

filePointer = open ('fname', 'r')

try:

content = filePointer.readline ()

finally:

filePointer.close ()

except IOError as e:

print str (e)

If, during the execution of the above code, an exception occurs while reading the file, the file Pointer would be closed on the block finally.

Records

When something goes wrong within an application, it is easier to debug if we know the source of the error. When an exception occurs, we can record the information necessary to locate the problem. Python provides a simple and powerful registry library. Let's take a look at how to use registers in Python.

import logging

# initialize the log settings

logging.basicConfig (filename = 'app.log', level = logging.INFO)

try:

logging.info ('Trying to open the file')

filePointer = open ('appFile', 'r')

try:

logging.info ('Trying to read the file content')

content = filePointer.readline ()

finally:

filePointer.close ()

except IOError as e:

logging.error ('Error occurred' + str (e))

As seen in the above code, we first have to import the Python log library and then initialize the logger with the log file name and log level. There are five log levels: DEBUG, INFO, WARNING, ERROR, and CRITICAL. Here we have to set the log level to INFO; therefore, INFO and the previous logs will be logged.

In the above code, we had a program file, so it was easier to figure out where the error had occurred. But what do we do when it comes to multiple program files? In such a case, getting the error stack helps in finding the source of the error. The exception stack trace may have been logged as shown:

import logging

# initialize the log settings

logging.basicConfig (filename = 'app.log', level = logging.INFO)

try:

filePointer = open ('appFile', 'r')

try:

content = filePointer.readline ()

finally:

filePointer.close ()

except IOError as e:

logging.exception (str (e))

If you try to run the above program when an exception occurs, the following error is logged in the log file:

ERROR: root: [Errno 2] No such file or directory: 'appFile'

Traceback (most recent call last):

File "readFile.py", line 7, in <module>

filePointer = open ('appFile', 'r')

IOError: [Errno 2] No such file or directory: 'appFile'

Python Web Development

Contributions of Python to Web Development

Python is a programming language that can also be used to create personal and business web pages. Knowing how to program websites and applications is synonymous with success and a job gap. The future is in the network, and professionals capable of placing companies in this new medium of commerce are needed. It is because of the above that many programmers have chosen to specialize in this category.

Python webs are chosen every day by high-level companies, a sign of the quality and good usability offered by webs created with this code. Thus, programming in Python is one of the skills most sought after by the headhunters of companies such as Netflix, Spotify, and Pixar. Choosing Python web ensures you are not pigeonholed into a single type of web development. It is an open source whose creation possibilities are endless, as well as its direct applications. With a good study on Python, you will learn to make websites from scratch with all its functionalities, from ecommerce to a platform with products on consumer demand like Netflix.

Python code has numerous advantages at the time of sitting down to create webs. We detail some of them below:

•

It is an open-source language, which means that it is free software. You can use it for free at all times.

•

It is multiplatform, valid for all types of systems and devices.

•

It is understandable to all programmers. The way of writing Python code is neat and clean, so anyone will know how to understand and work on your created structure.

•

It has a flexible style. With Python web, you can create a multitude of elements, from lists to more complex functions.

•

It has a healthy programming style. Python web is designed to work according to specific rules so that everyone follows the same guidelines.

Web Frameworks for Python

A web framework is a set of components that help you develop websites easier and faster. When you build a website, you always need a set of similar components: a way to handle user authentication (register, login, logout), an administration panel for your website, forms, a way to upload files, etc. Luckily for us, other developers realized long ago that they always faced the same problems when building websites, so they came together and built frameworks (such as Django) with out-of-the-box components. The frameworks serve so that we do not have to reinvent the wheel each time and that we can move faster when building a new site.

To understand what frameworks are really for, we need to look at how servers work. The first thing is that the server needs to know that you want a web page to serve you. Imagine a mailbox (port) in which someone is constantly looking for incoming letters (requests). This is what a web server does. The web server reads the letter and sends a response to the web page. But to send something, we have to have some content. And frameworks help us create that content. When a request arrives at a web server, it is passed to the framework, which tries to find out what is actually requested. Take a website address first and try to figure out what to do with it. This part is done by the URL resolver of our framework (note that a website address is called URL - Uniform Resource Locator, so the name URL resolver makes sense). This one isn't very smart - it takes a list of patterns and tries to match the URL. The framework checks the patterns from top to bottom, and if something matches, it passes the request to the associated function (which is called view). Imagine a postman carrying a letter. He walks down the street and checks each house number with the one on the letter. If it matches, he leaves the letter there.

All the cool things are done in the view function: we can look at a database to find some information. Maybe the user asked to change something in the data, like a letter saying, "Please change my job description." The view can check if you have permission to do so, update your job description, and return a message: "Done!" The view then generates a response, and Django can send it to the user's browser. This description is a bit simplistic, but at the moment, you don't need to know all the technical details. Just having a general idea is more than enough.

There are quite a few Python web frameworks out there, but here are some of the best:

•

Django: Django is a high-level web framework that enables rapid development of safe and maintainable websites. Developed by seasoned programmers, Django takes care of much of the complications of web development, so you can focus on writing your application without reinventing the wheel. It's free and open-source, has a thriving and active community, great documentation, and many free and paid support options.

•

Grok: Grok, defined by its authors, is a framework for web applications made for Python developers. It is aimed at beginners and experts. Grok is intended for agile development. This framework comes from the well-known Zope, a complete dean in the world of application servers in web environments, of which the Zope Toolkit is used, a set of objectoriented libraries specially oriented to the reuse of components in web environments.

•

Webpy: This is the software written by Aaron Swartz for creating dynamic websites with Python. It was officially posted while I was working on reddit.com (which was later rewritten using other tools). “Simple as powerful”, “It is the anti-framework framework. web.py doesn't get in your way"; some of the characteristics and opinions for which it is made known on the official website webpy.org. It is in the public domain, so it can be applied for the development of any type of project.

•

Turbogears: TurboGears is a Python web application framework that consists of various WSGI components such as WebOb, SQLAlchemy, Genshi, and Repoze. TurboGears is designed around the model-view-controller (MVC) architecture, very similar to Struts or Ruby on Rails, designed to make rapid web application development in Python easier and easier to maintain. Since version 2.3, the framework has also provided a "minimal mode" that allows it to act as a microframe for use in environments where the full stack is not required or desired.

Using Django

We will focus on introducing ourselves to web development in Python in the Django framework because this helps you write software that is:

•

Full: Django follows the "Batteries Included" philosophy and provides almost everything developers would like it to have "out of the box". All you need is part of a single "product," everything works perfectly, follows consistent design principles, and has a wide and updated documentation.

•

Versatile: Django can be (and has been) used to build almost any type of website - from content management systems and wikis to social media and news sites. It can work with

any framework on the client-side, and it can return content in almost any format (including HTML, RSS feeds, JSON, XML, etc.). The site you are currently reading is based on Django! While it offers options for almost any functionality you want (different database engines, template engines, etc.), it can be extended to use other components if necessary.

•

Insurance: Django helps developers avoid several common security mistakes by providing a framework that is designed to "do the right thing" to protect the website automatically. For example, Django provides a secure way to manage user accounts and passwords, thus avoiding common mistakes such as placing session information in cookies where it is vulnerable (instead, cookies only contain a key and the data is stored in the database data) or passwords are stored directly in a password hash. Django allows protection against some vulnerabilities by default, including SQL injection, cross-site scripting, cross-site request spoofing, and clickjacking.

•

Scalable: Django uses a component based on the architecture "shared-nothing” (Each part of the architecture is independent of the others, and therefore can be replaced or changed if necessary). Taking into account a clear separation between the different parts means that you can scale to increase traffic by adding hardware at any level: cache servers, database servers, or application servers. Some of the busiest sites have scaled Django to meet their demands (for example, Instagram and Disqus, to name just two).

•

Maintainable: Django code is written using design principles and patterns to encourage the creation of maintainable and reusable code. It uses the "Don't Repeat Yourself" (DRY) principle so there is no unnecessary duplication, reducing the amount of code. Django also encourages grouping related functionality into reusable "applications" and, at a lower level, groups related code into modules (following the pattern model View Controller (MVC)) .

•

Portable: Django is written in Python, which runs on many platforms. This means you are not tied to any particular platform and can run your applications on Linux, Windows, and Mac OS X distributions. Additionally, Django is supported by many web-hosting providers, and they often provide specific infrastructure and documentation for hosting Django sites.

Django Origins

Django was initially developed between 2003 and 2005 by a team that was responsible for creating and maintaining newspaper websites. After creating several sites, the team began to consider and reuse many common design codes and patterns. This common code became a generic web framework, which was open source, known as the "Django" project in July 2005.

Django continues to grow and improve from its first milestone, the release of version (1.0) in 2008, to the recent release of version 1.11 (2017). Each release has added new functionality and bug fixes, ranging from support for new database types, template engines, caching to the addition of generic functions, and display classes (which reduce the amount of code developers have to write).

Django is now a thriving collaborative open source project, with thousands of users and contributors. While it still has some features that reflect its origin, Django has evolved into a versatile framework that is capable of developing any type of website.

Django Possibilities

The preceding sections show the main features that in almost all web applications: URL mapping, views, models, and templates. Just a few other things that Django provides, including:

•

Forms: HTML forms are used to collect user data for processing on the server. Django simplifies the creation, validation, and processing of forms.

•

User authentication and permissions: Django includes a robust authentication and permission system that has been built with security in mind.

•

Search: Dynamic content creation is much more computationally intensive (and slow) than a static content service. Django provides flexible caching so that you can store all or part of a rendered page so that it is not re-rendered only when necessary.

•

Administration site: The Django admin site is included by default when you create an app using the basic skeleton. This makes it trivially easy to provide an administration page for administrators to create, edit, and view any of their site's data models.

•

Data serialization: Django makes it easy to serialize and serve your data as XML or JSON. This can be useful when creating a web service (a website that only serves data to be consumed by other applications or sites and does not display anything on its own) or when creating a website where the client-side code handles all the rendering of the data.

Virtual Environment

Django makes it easy to set up your computer so you can start developing web applications. This section explains what you get out of the development environment and provides an overview of some of your startup and configuration options. It explains the recommended method of installing the Django development environment on Mac OS X and Windows and how you can test it.

The development environment is an installation of Django on your local computer that you can use to develop and test Django apps before deploying them to the production environment. The main tools that Django provides are a set of Python scripts for creating and working with Django projects, along with a simple development web server that you can use to test locally (i.e., on your computer, not on a server. external web) Django web applications with your computer's web browser.

When you install Python3, you get a single global environment that is shared with all Python3 code, while you can install the packages you like in your environment. You can only install one particular version of each package at a time. If you install Django in the default / global environment, you will only be able to target a single version of Django on the computer. This can be a problem if you want to create new sites using the latest version of Django but keep websites that depend on older versions. Experienced Python / Django developers run Python applications within separate Python virtual environments. This enables multiple different Django environments on the same computer. The same Django development team recommends that you use virtual Python environments!

The libraries that we will use to create our virtual environments are in virtualenvwrapper (Mac OS X) and virtualenvwrapper-win (Windows), which in turn use the tool virtualenv. The toolswrapper creates a consistent interface for managing interfaces on all platforms.

Mac OS X

Install virtualenvwrapper (virtualenvi ncluded in the package) using pip3 shown in the following.

Sudo pip3 install virtualenvwrapper

Then add the following lines to the end of the start file of your shell. The startup file is called differently .bash_profile and it's hidden in your home directory.

export WORKON_HOME = $ HOME / .virtualenvs

export VIRTUALENVWRAPPER_PYTHON = / usr / bin / python3

export PROJECT_HOME = $ HOME / Devel

source /usr/local/bin/virtualenvwrapper.sh

Then reload the startup file by making the following call in the terminal:

source ~ / .bash_profile

At this point, you should see a handful of scripts starting to run. You should now be able to create a new virtual environment with the command mkvirtualenv.

Windows

Installing virtualenvwrapper-win is even simpler than starting virtualenvwrapper because you don't need to configure where the tool stores the environment information (there is a default value). All you need to do is run the following command in the online command console:

pip3 install virtualenvwrapper-win

And then you can create a new virtual environment with mkvirtualenv

Taking Advantage of Virtual Environments

Once you have installed virtualenvwrapper or virtualenvwrapper-win, working with virtual environments is similar on all platforms. Now you can create a new virtual environment with the command mkvirtualenv. As this command is executed, you will see that the environment starts up (what you will see is slightly platform-specific). When the command is completed, the new virtual environment will be active - you can check it because the beginning of the prompt will be the name of the environment in parentheses (as shown below).

$ mkvirtualenv my_django_environment

Running virtualenv with interpreter / usr / bin / python3

...

virtualenvwrapper.user_scripts creating

/home/ubuntu/.virtualenvs/t_env7/bin/get_env_details

(my_django_environment) ubuntu @ ubuntu : ~ $

Once you are inside the virtual environment, you can install Django and start development. There are just a few other useful commands you should know about (there are more in the tool's documentation, but these are the ones you will use regularly:

•

deactivate - Exit the current Python virtual environment

•

workon- List the virtual environments available

•

workon name_of_environment- Activate the specified Python virtual environment

•

rmvirtualenv name_of_environment- Delete the specified environment.

Django Installation

Once you have created the virtual environment and made the callworkonto get into it, you can use pip3 to install Django.

pip3 install Django

You can check that Django is installed by running the following command (this checks that Python can find the Django module):

# Mac OS X

python3 -m Django --version

1.11.7

# Windows

py -3 -m Django --version

1.11.7

The above test works, but it's not very fun. A more interesting check is to create a project skeleton and see if it works. To do this, navigate in your command console/terminal to where you want to store your Django applications. Create a folder for your site verification and navigate to it.

mkdir django_test

cd django_test

You can then create a new site skeleton called "mytestsite" using the tool Django-admin as it's shown in the following. After creating the site, you can navigate to the folder where you will find the main script for project management, called manage.py.

Django-admin startproject mytestsite

cd mytestsite

We can start the development web server from this folder using manage.py and the command runserver, as shown.

$ python3 manage.py runserver

Performing system checks ...

System check identified no issues (0 silenced).

You have 13 unapplied migration (s). Your project may not work properly until you apply the migrations for app (s): admin, auth, contenttypes, sessions.

Run 'python manage.py migrate' to apply them.

September 19, 2016 - 23:31:14

Django version 1.10.1, using settings 'mysite.settings'

Starting development server at http://127.0.0.1:8000/

Quit the server with CONTROL-C.

Once you have the server running, you can view the site by navigating to the following URL in your local web browser: http://127.0.0.1:8000/.

Website Project: Blog

We will build a blog system today to learn the basics. First, we will create a Django project.

cd ~ / Documents / Projects

Django-admin.py startproject FirstBlog

cd FirstBlog

ls

What do these files do?

•

_init_.py tells Python that this folder is a Python package. We learned about this in the third lesson; it allows Python to import all the scripts in the folder as modules.

•

manage.py is not really part of your website; it is a utility script that you run from the command line. It contains an array of functions to manage your site.

•

settings.py contains your website settings. Django doesn't use XML files for configuration; everything is Python. This file is simply a number of variables that define your site settings.

•

URLs.py is the file that assigns the URLs to the pages. For example, you could map yourwebsite.com/about to an "About Us" page.

Applications

However, none of these files create a functional website. For that, we need applications. Applications are where the code that makes the website work is written, but before we take a look at them, we need to get a little understanding of Django's design principles.

First, Django is an MVC framework, which stands for Model View Controller. Django refers to itself as an MTV framework, which stands for Model Template View. It is a slightly different approach than MVC, but fundamentally, they are quite similar. MVC is an architectural pattern that provides a method to structure your projects. Separates the code that is used to process data from the code that manages the user interface.

Second, Django subscribes to the DRY, or Don't Repeat Yourself philosophy, which means you should never write code that performs a certain task more than once. For example, on our Blog, if we wrote a function that picked a random article from the archive and implemented this function on multiple pages, we would not re-code it every time it was needed. We code it once and then use it on every page.

So how does this relate to apps? Well, the applications allow you to write your website in a DRY style. Each project, like the one we have here, can contain multiple applications. Rather, each application can be part of multiple projects. Using the example from before, this means that if we created another site in the future that also needed a random page function, we wouldn't have to rewrite it. We could just import the application from this project. Because of this, it is important that each application has a different purpose. If you write all the functionality of your site inside one app, and then you need to use part of it again later, you have to import it all. If you were creating an e-commerce website, for example, you wouldn't want to import all the blog features. However, if you create an app for the shuffle function and an app for the blog publishing system, you can choose the bits you need.

This also means that within site, the code is well organized. If you want to modify a feature, you don't have to search a massive archive; instead, you can navigate to the corresponding app and change it without worrying about interfering with anything else.

python

mangage.py startapp blog cd blog

ls

Again, we have a file _init_.py to convert it into a package and three other files: models, tests, and views. We don't need to worry about testing for now, but the other two are important. Models and Views are the parts M and V by MVC.

When you want to access that data, go through these models by calling the method on them, rather than running raw queries. This is very useful because Django can use multiple database programs. We are going to use MySQL today because it is the most powerful, and it is what most hosts offer. However, if we need to switch to a different database in the future, all the code will still be valid! In other languages, if you wanted to switch to SQLite or something similar, you would need to rewrite the code that accesses your database. In the views file, we write the code that generates the web pages. This ties all the other parts together. When typing a URL, it is sent through the scripturls that we saw before the script of views, which then obtains relevant data from the models, processes it, and passes it to a template, which is finally served as the page the user sees. We'll take a look at those templates shortly. They are the easiest part, mainly HTML.

For a blog, we will need a table of posts, with various fields for the title, body text, author, time of writing, etc. An actual blog demo.

from Django.db import models

class posts (models.Model):

author = models.CharField (max_length = 30)

title = models.CharField (max_length = 100)

bodytext = models.TextField ()

timestamp = models.DateTimeField ()

MySQL

These models are only a description. We need to make a real database of them. First, however, we need MySQL to run on our system. On a real webserver, this wouldn't be a problem as they usually have it pre-installed. Fortunately, with a package manager, it is easy to install. First, you need to install Homebrew and Easy installation.

brew install MySQL

easy_install MySQL-python

mysqld_safe --skip-grant-tables #let anyone have full permissions

mysql -u root

UPDATE mysql.user SET Password = PASSWORD ('nettuts') WHERE User = 'root';

#give the user 'root' a password

FLUSH PRIVILEGES;

MySQL -u root -p #log in with our password 'nettuts'

CREATE DATABASE firstblog;

quit

python2.6 manage.py runserver

When you reboot, MySQL won't run, so whenever you need to do this in the future, run MySQL to start the server. You can then run python2.6 manage.py runserver in a new tab to start the development server.

This command will not run the server yet. It will just return an error. That's because we have to adjust our settings. Let's take a look at settings.py.

You must first change the database configuration. These start in line twelve.

DATABASES = {

'default': {

'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.

'NAME': 'firstblog', # Or path to database file if using sqlite3.

'USER': 'root', # Not used with sqlite3.

'PASSWORD': 'nettuts', # Not used with sqlite3.

'HOST': '', # Set to empty string for localhost. Not used with sqlite3.

'PORT': '', # Set to empty string for default. Not used with sqlite3.

}

}

If you try to run the server again, it should work, provided you have installed MySQL correctly. If you visit 127.0.01: 8000In your web browser, you should see the default Django page. Now let's turn our Django site into a blog. First, we need to use our Models to create tables in the database by running the following command:

python2.6 manage.py syncdb

Every time you change your models, you must run this command to update the database. Note that this cannot alter existing fields; you can only add new ones. So if you want to remove fields, you will have to do it manually with something like PhpMyAdmin. Since this is our first time running the command, Django will configure all the built-in default tables for things like the admin system. Just write "yes" and then fill in your details. Now let's configure the file urls.py. Write the line:

URL (r '^ $', 'FirstBlog.blog.views.home', name = 'home').

Now, we create the views file to respond to these requests.

from django.shortcuts import render_to_response

from Blog.models import posts

def home (request):

return render_to_response ('index.html')

Templates

This index.html file doesn't exist yet, so let's do it. Create a folder called templates in your application Blog and save a file calledindex.html, which can simply contain "Hello World" for now. Next, we need to edit the config file, so Django knows where this template is located.

Line 105 is where the section for declaring template folders begins; so adjust it like this:

TEMPLATE_DIRS = (

"blog / templates",

# Put strings here, like "/ home / html / django_templates" or "C: / www / django / templates".

# Always use forward slashes, even on Windows.

# Don't forget to use absolute paths, not relative paths.

)

If you run the server again and refresh the page in your browser, you should see a "Hello world" message. Now we can start designing our blog. We will add some boilerplate HTML for the home page.

<! DOCTYPE html>

<html lang = "en">

<head>

<meta charset = "utf-8" />

<link rel = "stylesheet" href = "css / style.css">

<link href = "images / favicon.ico" rel = "shortcut icon">

<title> First Blog </title>

</head>

<body>

<div class = "container">

<h1> First Blog </h1>

<h2> Title </h2>

<h3> Posted on date by author </h3>

<p> Body Text </p>

</div>

</body>

</html>

If you save and refresh the page, you should see that the page has been updated with this new content. The next step is to add dynamic content from the database. To achieve this, Django has a template language that allows you to insert variables with braces. Change the middle section of your page to look like this:

<div class = "container">

<h1> First Blog </h1>

<h2> {{title}} </h2>

<h3> Posted on {{date}} by {{author}} </h3>

<p> {{body}} </p>

</div>

We can then pass values to these variable placeholders from the file views.py, creating a dictionary of values.

from django.shortcuts import render_to_response

from Blog.models import posts

def home (request):

content = {

'title': 'My First Post',

'author': 'Giles',

'date': '18th September 2011',

'body': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam cursus tempus dui, ut vulputate nisl eleifend eget. Aenean just felis, dapibus quis vulputate at, porta et pain. Praesent enim libero, malesuada nec vestibulum vitae, fermentum nec ligula. Etiam eget convallis turpis. Donec non sem fair. ',

}

return render_to_response ('index.html', content)

Save and update, and you should see that you are now transferring content to a template from your views file. The last step is to get data from our database and pass it in instead. Fortunately, we can do all of this without SQL queries, using Django's models. We need to add our application of Blog to our project First Blog changing other settings. Go to INSTALLED_APPS on line 112 and add to the list the 'FirstBlog.blog', to then change views.py for you to add data from the database.

from django.shortcuts import render_to_response

from Blog.models import posts

def home (request):

entries = posts.objects.all () [: 10]

return render_to_response ('index.html', {'posts': entries})

Then update the template to access this information.

<div class = "container">

<h1> First Blog </h1>

<hr />

{% for post in posts%}

<div class = "post">

<h2> {{post.title}} </h2>

<h3> Posted on {{post.timestamp}} by {{post.author}} </h3>

<p> {{post.bodytext}} </p>

</div>

<hr />

{% endfor%}

</div>

Here, we can access all the data in our table in the file views.py, then select only the first ten entries. We pass this data to the template, we go through the inputs, and display the data with the HTML of our site. This will not work yet, because there is nothing in the database. Stop the server and run:

python2.6 manage.py syncdb

This will add the new table for our posts to the database. Then open a new tab and type:

MySQL -u root –p

Type your password, press Enter, and run:

INSERT INTO blog_posts (author, title, bodytext) values ('Bob', 'Hello World', 'Lorem Ipsum');

Go back to the previous tab and run the server again. Refresh the page, and you should see a blog post with the fictional content you just added. If you run the MySQL command a few more times, you should see more posts appear on the page when you refresh.

Django Administration System

The last thing we need to do with this is to check out the Django admin system. This is a powerful feature in Django that allows you to manage your site without writing any more code, just like you would if you were building a site from scratch. To enable it, we need to change some settings. First, uncomment lines 4, 5, 13, and 16 in urls.py, so you can access the administration page.

Then go to section INSTALLED_APPS from settings.py and delete the comment

'django.contrib.admin' and 'django.contrib.admindocs', To allow the administrator to control his table of publications, create a new file calledadmin.py in the folder of Blog and add the following lines:

from Django.contrib import admin

from Blog.models import posts

admin.site.register (posts)

Run python2.6 manage.py syncdb again to add the tables for the admin section and restart the server. If you visit 127.0.0.1:8000/admin now in your browser, you should see a login page.

Use the details you chose earlier when you ran the command syncdbto login. You should see a section called Blog, with a caption for the table of publications. You can use this to create, edit, and delete blog posts with a simple interface. That's all you have to do. You just created a fully functional yet simple blog. To finish this lesson, we are going to see how to install Django on a web server.

Installation on a Web Server

Most web servers run scripts in various languages using CGI. Django can run on FastCGI and also theoretically CGI, but this is not officially supported and would be too slow for a real production website. You will need to check if they are installed. They are usually found under a heading, such as "CGI and scripting language support."

If you have VPS hosting or are lucky enough to have a dedicated server, your life is so much easier. These usually come with Python pre-installed, and from there, you just need to follow the same steps we went through to get a local copy of Django running. If you don't have Python, you can install it with a package manager. Your system can even come with Django.

ssh root@example.com

wget http://www.djangoproject.com/download/1.3.1/tarball/

tar xzvf Django-1.3.1.tar.gz

cd Django-1.3.1

python setup.py install

Once you have Django installed on your server, upload the site you just created using any file transfer client. You can put the files anywhere, but keep them out of the folderpublic, or anyone will be able to view the source code of your site. I use /home for all my projects.

Next, create a MySQL database called 'firstblog' on your server and run syncdb again. You will need to re-create your account for the admin control panel, but this is a one-time thing. If you try to run this, you may get an error, and that's because the settings for the server are different from your local computer. You may need to change the database password withinsettings.py, but depending on your server configuration, you may encounter other problems as well. Google is your friend!

To run the server this time, the command is slightly different. You must specify an IP address and a port so that you can access the site over the Internet.

python manage.py runserver 0.0.0.0:8000

If you visit your site in a web browser, on port 8000, you should see your site!

Final Words

In the Computer Industry, a phenomenon known as free software has been gaining influence. This is a movement that proclaims access to the source code of a program, which admits to being free of use, execution, distribution, and modification. In other words, the new software created under this concept could be used for any purpose, run in any environment, be distributed at the user's own discretion, and be modified if necessary. Programming languages are the basic tool for building programs, as are the machete and hoe for a peasant, the pick and shovel for a builder. Python has been gaining followers in communities such as free, scientific, and educational software due to its simplicity and ability to focus on current problems.

Although this book is not intended for professional programmers, programming at a professional level can be rewarding work, both financially and personally. Creating useful, elegant, and smart programs for others to use is a very creative activity. Your computer or Personal Digital Assistant usually contains many different programs belonging to different groups of programmers, each of them competing for your attention and interest. They all do their best to adapt to your needs and provide you with a satisfying user experience. Sometimes when you choose a certain software, its programmers are directly rewarded for your choice.

Likewise, writing programs is a creative and rewarding activity. You can write programs for many reasons, ranging from being active in solving a complex data analysis problem to doing it for the fun of it by helping others solve a puzzle. This book assumes that everyone needs to know how to program and that once you learn to program, you will find out what you want to do with those newly acquired skills. Python is a language that everyone should know. It is straightforward and clear, and the simple syntax, the dynamic typing, the memory manager, the large number of libraries available, and the power of the language, among others, make developing an application in Python easy, fast, and, what is more important, fun.

Python's syntax is so simple and close to natural language that Python programs look like pseudocode. For this reason, it is also one of the best languages to start programming. Python is, however, not suitable for low-level programming or performance-critical applications. Some success stories in the use of Python are Google, Yahoo, NASA, Light & Magic Industries, and all Linux distributions, in which Python represents an increasing percentage of the available programs. Always learning a new programming language has new challenges from learning about the philosophy of the language and even its own lexicons, which make the use and expression of its programs with this new language characteristic. But this requires practice and time to become fluent in speaking and writing Python programs. For now, in this book, we learned:

•

What is a programming language, and what its fundamentals are.

•

The fundamentals of programming with the Python language.

•

Working with data types: how to make collections, lists, input and output, and use of variables.

•

What classes are and everything that Object-Oriented Programming covers (inheritance and polymorphism).

•

The management of files and databases (SQLite).

•

The graphical interface for developing visual programs.

•

How to document your code and make it an official document.

•

How to develop a web page.

There are many useful reports in which we can see that Python is becoming one of the programming languages with the highest growth rate. Python is, statistically, one of the programming languages that has grown the most in recent years. More and more people are interested in learning to program with Python. In fact, there are those who consider it the programming language of the future. A situation that leads to a great demand for specialized professionals. However, this is just one of the benefits of becoming a Python programmer. Becoming a Python programmer is not only limited to getting more job opportunities but believe us, you are going to have them. It is also about working and specializing in an exciting programming language that you will like more the more you learn about it. Whether you are new to programming or are already a veteran looking for new challenges, Python is for you.

Programming is considered by many a form of art, and like all art, it needs a language that allows you to express ideas in the way you want. Python is the canvas that allows you to reflect, in a simple and elegant way, ideas in an algorithmic way. Its applications, both in the teaching and scientific communities, will allow it to increase its popularity and adoption internationally. Hopefully, this information, especially to the community of geeks around the world, where there are many people, computer scientists or not, interested in taking their first steps in the world of programming in a free software environment, since Python constitutes, without a doubt, one of the best variants.

The learning has not ended here. Indeed, it has only just begun. This book is a tool with every intention of taking you by the hand on your journey as a programmer from day zero. We hope to be a clear, solid, and lasting base of knowledge that will be kept in your collection whenever it is necessary in any challenge encountered in the world of programming. Remember that you can always consult this information again and that a large community of people with the same interests as you is waiting to meet you to help you learn and collaborate.

RASPBERRY PI

Learn Fundamentals and Unlock Powerful Hacks of Using Raspberry Pi

Introduction

The Raspberry Pi is a low-cost, credit card-sized device that uses a regular keyboard and mouse and attaches to a computer monitor or TV. It is a lightweight, capable computer that allows individuals of all ages to explore programming and learn how to program in languages such as Scratch and Python. From surfing the internet and watching high-definition video, to making spreadsheets, word-processing, and playing sports, it can do everything you 'd expect a desktop computer to do.

In addition, the Raspberry Pi has the potential to connect with the outside world and has been used in a broad variety of interactive developer ventures, including music machines and parent detectors to weather stations and infra-red cameras tweeting birdhouses. We want to see children all over the world use the Raspberry Pi to learn to program and understand how computers work.

Raspberry Pi is the name of a collection of single-board computers created by the UK charity Raspberry Pi Foundation, which aims to educate kids in computer science and make it easier for them to access computer education.

The Raspberry Pi was introduced in 2012, and several versions and variants have since been released. The original Pi had a single-core 700MHz CPU and just 256 MB RAM, and a quad-core 1.4GHz CPU with 1 GB RAM is available for the new edition. For Raspberry Pi, the main price point has always been $35 and all models have been $35 or less, including the Pi Zero, which is just $5.

In order to learn programming skills, create hardware projects, do home automation and even use them in industrial applications, people all over the world use Raspberry Pi.

The Raspberry Pi is a very inexpensive machine running Linux, but it also provides a set of GPIO (input / output general purpose) pins that allow you to manipulate physical computing electronic components and explore the Internet of Things (IoT).

What would you do with a Raspberry Pi?

To learn to code, some people buy a Raspberry Pi, and people who are already able to code use the Pi to learn to code electronics for physical projects. Instead of using a proprietary closed system, the Raspberry Pi will open up opportunities for you to build your own home automation projects, which is common with people in the open source community because it puts you in charge.

The best Raspberry Pi and Raspberry Pi Zero projects to try

We recommend buying a Raspberry Pi and letting imagination run wild for those wanting to learn more about computers, software creation and creating tiny machines.

Given what you can do with it, it's a fairly well-priced product. It can help teach coding or be a base for more complex programming. As such, several individuals have used the device to create a range of machines and functions, from school kids to fully-fledged developers.

By 2015, more than five million machines had been sold, according to the Raspberry Pi foundation, making it one of the best-selling British computers. In schools where kids, or older students, can learn computer skills, it is extremely common.

Unfortunately, it's also a pretty nifty little package for hackers, partly due to its size, portability and strength. But really, it only goes to show how good it is. It's a path into robotics, software creation and a whole range of technological skills for the more morally sound consumers, which would otherwise cost thousands of pounds in tuition fees.

If you are looking for inspiration to start your own Raspberry Pi project, then you have come to the right spot. To give you some ideas, we have gathered some of the best use cases around.

Build a portable security box

The Pi's portability and affordability has made it a common instrument for red-teamers, penetration testers and other security personnel (people paying to hack into safety systems). It's perfect for sneakily integrating with target networks because it has a built-in Ethernet port, minimal power requirements, and the ability to run any Linux program.

Kali, a Linux distribution that is explicitly designed for hacking activities, is the program of choice for security operators trying to use Pi in this way. For the Raspberry Pi, there's a purpose-built version of Kali, and installing it is pretty easy.

Not only can you use it in your security operations once you have Kali enabled, you can also use it as a safe space to play around with new tools without causing harm to your primary computer. However, as always, you should only be hacking targets that have given you express authorization.

Host a Raspberry Pi platform for Wordpress

To familiarize yourself with the Raspberry Pi, hosting your own website is a great project. You can learn how to work with MySQL, PHP, and Apache applications, as well as the practicalities of operating with Linux, by running a Wordpress server.

Not just that, but you'll also have a functioning Wordpress website at the end of it, which you can use to host your own content! If you want it to be a proper website, you will need to register a domain name, but it's a great place to view stuff such as CVs, artistic portfolios or something as basic as a personal blog.

Install Windows 10 in full on Raspberry Pi 3

For installing Microsoft's operating system on Raspberry Pi 3 Model B or B+ boards, you can use the Windows on ARM (WoA) installer, available on GitHub. Previously, on Raspberry Pi computers, only stripped-down Windows IoT Core operating systems were available, but this new bundle provides complete Windows 10 OS functionality.

Accessible on GitHub, the installer is optimized for ease of use and convenience, requiring bundled binaries and the WoA core kit.

Run IoT Core for Windows 10 on Raspberry Pi

Would you like to run the Windows 10 Internet of Things version on your Raspberry Pi? With Windows 10 IoT Core, the microcomputer will run a stripped back version of the operating system.

While running the full version of the operating system on the Raspberry Pi Model B+ would be fantastic, with only 1 GB of RAM and a 1.4 GHz ARM-based processor, it doesn't have the processing power.

Enter Windows 10 IoT Core, a basic version of the Microsoft OS designed to run on less powerful platforms. It's a lightweight IoT app that enables a single UWP app to be run at a time. If you want to commercialize your creations and little equipment is required, you don't need a license.

First of all, you'll need a Raspberry Pi 3 and a spare microSD card, plus a separate microSD card reader on your Windows device. Visual Studio, text editor, SDKs, add-ons, and certificates are also required. This may seem like a lot, but you're not going to have to spend too much money to start running Windows 10 IoT Core.

Next, you'll need to set up the Raspberry Pi memory card that you're using. With the Latest Out of Box Program (NOOBS) installer, you can make this simpler. Build a bootable card using Microsoft's IoT Dashboard software from a Windows PC or laptop.

You can now use the Broadcom Raspberry Pi 2 & 3 and OS build options (Windows 10 IoT Core) to set up the computer, then enter a password, pick a Wi-Fi network, and install the OS on the Raspberry Pi-compatible memory card.

Install this into your Raspberry Pi and then you're ready to boot the new version of Windows IoT Core on your computer.

Set up Raspberry Pi as a server for VPN

A VPN enables you to disguise your online identity so that when you search the internet, download content, or engage in conversations, your actions can not be monitored. VPNs can also be used on standard machines, and when using a micro-computer such as Raspberry Pi, the procedure is quite the same. There are plenty of Raspberry Pi VPN programs available, including Express VPN, HideMy Butt, IPVanish, and SaferVPN.

But what brings this to the next stage is using your Raspberry Pi as a VPN server to create a personal VPN hotspot to prevent any website used on your network from transmitting information about your identity. Link it to your router by downloading a client on the Raspberry Pi, and your identity will be scrambled until it reaches the external network.

To set up your Raspberry Pi as a VPN server, install Raspbian to access the command line first, and then you can install a VPN client using the PiVPN script to secure your communications. As your VPN client, we suggest using OpenVPN, although it can also be used with lots of others.

PART I:

THE BOARD

Chapter One

The Raspberry Pi

The Raspberry Pi Components

The Raspberry Pi is a series of small single-board computers developed by the Raspberry Pi Foundation in the United Kingdom to promote fundamental computer science teaching in schools and developing countries. The original model became much more popular than expected, selling for uses such as robotics outside its target market. Peripherals (such as keyboards and mice) and cases are not included here. However, in several official and unofficial bundles, several accessories are packed.

Two arms comprise the company behind the Raspberry Pi. The first two versions were produced by the Raspberry Pi Foundation. The Foundation founded Raspberry Pi Trading after the launch of the Pi Model B. Eben Upton was the CEO at the time. The third model, the B+, was further developed by the Foundation. Raspberry Pi Trading is responsible for technology growth, while the Foundation is an educational charity in schools and developing countries that supports the teaching of basic computer science.

What's fresh about the Raspberry Pi 4?

Support for dual display (4 K): You can now attach two displays to this desktop computer with this feature, and that feature is also available in 4K.

Better performance: A new, revamped processor and RAM comes with the new Raspberry Pi 4, which guarantees you a new desktop experience.

Fast networking: Gigabit Ethernet, along with on-board wireless networking and Bluetooth, comes with the Pi 4.

RAM: The Raspberry Pi 4 comes in 3 RAM-based variants: 1 GB, 2 GB, and 4 GB.

USB 3: The latest Raspberry Pi 4 has improved USB capabilities. You can find two USB 3 ports along with two USB 2 ports, which can transfer data up to ten times faster.

Technical criteria

• Broadcom BCM2711, 64-bit SoC @ 1.5GHz Quad-core Cortex-A72 (ARM v8)

• 1 GB, 2 GB or 4 GB LPDDR4-2400 SDRAM (model dependent)

• 2.4 GHz and 5.0 GHz

• Normal 40 pin GPIO header Raspberry Pi (fully backward compatible with previous boards)

• 2 ports for micro-HDMI (up to 4kp60 supported)

• MIPI DSI 2-lane display port

• MIPI CSI 2-lane camera port

• Stereo audio and composite video connector 4-pole

• H.265 (Decode 4kp60), H264 (Decode 1080p60, Encode 1080p30)

• Graphics from OpenGL ES 3.0

• Micro-SD card slot for operating system loading and data storage

• 5V DC via USB-C connector (minimum 3A *)

• 5V DC via header GPIO (minimum 3A *)

• Power over Ethernet (PoE) enabled (separate PoE HAT required)

• Operating temperature: ambient temperature of 0 to 50 degrees C

* If downstream USB peripherals consume less than 500mA in total, a good quality 2.5A power supply can be used.

Configuring the Raspberry Pi 4

What you're going to need

A power supply: Included in the device is a USB Type-C port. With at least 3.0 A of electricity, you need a power supply.

Micro-SD card: You will need this to store your files and the Raspbian OS. The minimum storage requirement is 8 GB. Several sellers have micro-SD cards with the Raspbian OS pre-installed, so you're ready to go.

Keyboard and Mouse: You need a USB keyboard and a USB mouse to use the Raspberry Pi 4. Both are mandatory for the first installation. You can also use the Bluetooth keyboard and mouse after setting it up.

TV / Computer screen: You need a TV or computer screen and a cable to connect the Raspberry and the monitor to display the content within the computer. Pi 4 can use it if your display has speakers mounted inside it. A micro-HDMI port is the port needed here. You will need their respective micro-HDMI converters if you have a particular cable, such as regular HDMI, DVI, and VGA cables. If your monitor supports VGA, for instance, then use a VGA-to-micro-HDMI adapter with it. You will be able to use your VGA cable this way.

Before setting up the Raspberry Pi 4, these are the basic specifications needed. Add-ons including a protective shell, headphones / speakers, and Ethernet cable can also be added.

Configuring the SD card

You should do it yourself if your SD card does not have the Raspbian operating system. Using a laptop with an SD card slot mounted is everything you need to do. Many of the newest laptops have this feature.

The best way is by using NOOBS to install the Raspbian operating system.

Why pick a Raspberry Pi?

Virtually anything can be a Raspberry Pi. What can it be for you?

That's the beauty of it: there's a Raspberry Pi project that is great for you, whether you're a complete novice or a die-hard tech-savvy DIYer. A media center software like Kodi or Plex can be put on your smartphone with a few easy clicks and a microSD card. The Raspberry Pi can be an arcade with only a little more know-how. Get very intense, and link to smart devices, home monitoring equipment, LED strips, and more with the Raspberry Pi. It's truly up to you!

Link to the Pi 4 Raspberry

Install in the mini system all the necessary components. To ensure that the components are safe, the set-up must be performed in a specific order.

First, insert the micro-SD card into the underside of the Raspberry Pi 4 slot. Take your mouse cable's USB port and attach it to the Raspberry Pi 4 USB port. Connect the keyboard in the same way. Make sure that your screen is plugged into a socket and switched ON. Use a micro-HDMI cable to connect the TV / computer monitor to your laptop, or an adapter if necessary. Insert a female micro-HDMI component into the Raspberry Pi port called HDMI0. Attach an Ethernet cable connected to a WiFi router or a broadband network to connect Raspberry Pi 4 to the Internet via Ethernet. If your screen has speakers embedded in it, the Raspberry Pi will use it. You can use external audio devices such as headphones and speakers by connecting them through a headphone jack if you do not want to use those speakers or there are no speakers on your monitor.

Booting the Raspberry Pi 4

This machine does not have a power button, so it boots up as soon as you plug in the power supply and turn it on.

You will see the red LED light in the unit glowing. This is a sign that power is linked to Raspberry. You will soon be seeing raspberries on the left of your screen as it boots up.

The Raspbian desktop will appear after a couple of seconds.

Finishing the configuration

You will see the Welcome to Raspberry Pi pop-up when you launch your Raspberry Pi 4 for the first time. This will lead you into the initial configuration.

To start the setup, click 'Next,' then set the country, language, and time zone. Once again, press 'Next.' Insert a new password. Connect to a WiFi network by choosing its name and entering a password. Allow the wizard to search for and install updates. This can take a little while. To complete the setup, press Done or Restart.

The Apps

I hope you've grasped the setup of the Raspberry Pi 4 by now. Now let us take a look at some of this device's cool uses.

1. Motion Camera Stop

You know everyone's in love with stop motion. A Raspberry Pi 4 and a dedicated camera module will be needed to build your digital stop motion camera.

The creation process of a camera is time-consuming. You'll need a Python, a tripod camera, and a well-lit area. It will need time and practice for satisfactory performance.

To mount a button, you will need a breadboard (unless you already have an appropriate plunger button that can be attached to the GPIO of the Raspberry Pi), and a Python script to snap each file.

2. Server on the Internet

Yeah, your Raspberry Pi 4 can now be configured to host a website. It can also host your blog.

There are two ways for this to be done. Install both Apache and its related libraries. Or create a full LAMP stack, alongside Apache, with PHP and MySQL. It is recommended to set up an FTP.

You can add the HTML files to the \www\ directory once these steps are completed, and your web server is ready. Or a particular website like WordPress can be installed.

3. Monitoring platform for networks

Do you want the devices on your network to be monitored? Are you thinking about connectivity shortages?

The best approach for you, then, is to develop a tool for network monitoring. On the internet, there are many instruments available. One of the best software is the Nagios tool, which is simple to install and run. You can easily monitor the uptime and display the visualization of the connected devices with the Nagios tool. Simply flash your disk image onto the SD card mounted on your Raspberry Pi 4 to use it.

4. Live YouTube video streaming

Live streaming on YouTube is another way to take advantage of a Raspberry Pi 4.

A compatible USB camera is required for live streaming.

Get ready with your YouTube channel built with the libav-tools kit. There is a comprehensive tutorial available on the Raspberry Pi 4 for streaming a video live on YouTube. You can visit it for specific directions.

5. Learn how to code

One of its main motivations was to teach kids to code when this device was initiated in 2012. It is not just youngsters, however, who can learn to code. The in-built coding tools available on the Raspberry Pi 4 can also be used by adults and seniors.

In Raspbian, there are many pieces of software available which provide fundamental programming skills. The most important, however, is Scratch.

Scratch is a block-based programming tool designed to accommodate all levels, which avoids the complexities of code line input. You simply drag the commands into place, instead. In the code view, you can see the impact of your commands and export the code as a program to be run.

Scratch is sufficiently easy to control the lights mounted in the GPIO of the Pi and sufficiently complex to program basic games.

The Raspberry Pi system looks like a motherboard, exposed to the installed chips and ports (something you would expect to see if you opened your computer and looked at its internal boards), but it has all the components you need to connect and start computing input, output, and storage devices.

The different components on the Raspberry Pi board:

ARM CPU / GPU — This is a SoC (Broadcom BCM2835 System on a Chip) consisting of a central processing unit (CPU) for ARM and a graphics processing unit (GPU) for Videocore 4. All computations that make a machine work (taking input, doing calculations, and generating output) are done by the CPU and the GPU handles the output of graphics.

• GPIO — These are general-purpose input / output link points that allow the opportunity for real hardware hobbyists to tinker.

• RCA — An RCA jack enables analog TVs and other similar output devices to be paired.

• Audio output — For connecting audio output devices such as headphones or speakers, this is a regular 3.55-millimetre jack. There's no audio going in.

• LEDs — Light-emitting diodes for all the light requirements of your indicator.

• USB — This is a standard peripheral computer communication port of all types (including your mouse and keyboard). Model A has one, and there are two for Model B. If it has its own USB port, you can use a USB hub to extend the number of ports or plug your mouse into your keyboard.

• HDMI — This connector allows you to use an HDMI cable to link up a high definition television or other compatible unit.

• Power — This is a 5v Micro USB power supply connector that can be attached to your compatible power supply.

• SD Cardslot — This is a full-sized slot for your SD card. You need an SD card with an operating system (OS) to boot the device. They are available from the manufacturers for purchase, but if you have a Linux machine and the wherewithal, you can also download an OS and save it to the card yourself.

• Ethernet — This adapter allows access to the wired network and is available on Model B only.

Many of the missing features, such as WiFi and audio, can be added as required by using the USB port(s) or a USB hub.

The computer itself and its operating systems

The Raspberry Pi measures approximately 3.4 inches by 2.1 inches (8.6 centimeters by 5.3 centimeters), but for such a tiny unit, it's very strong. The ready availability of cheap and compact processors for mobile devices, which need to cram a reasonable amount of processing and multimedia capacity into a small shell with the ability to remain relatively cool and not suck power too quickly, made this possible.

For this purpose, the foundation selected a chip with an ARM architecture (a processor architecture widely used for cell phones and similar devices). The chip has a RAM of 256 MB, runs at 700 MHz and includes a GPU that is 1080p capable. Although there are other ARM chips available, in part because of Eben Upton's relationship with the business (he works for them), the group preferred a Broadcom chip. The ability of Broadcom to offer a bulk rate for small orders enables the foundation to get a much better price on this chip than on the processor of any comparable competitor.

The unit comes without peripherals or internal storage space, like many of the earliest home computers, and the user will have to connect peripherals for input, output, and storage. You'll need at least an output TV or display, an input keyboard (and probably a mouse), an SD card to hold the OS and store data, a power supply, and any necessary cables. For extra storage, you can connect an external hard drive, but it will also require an SD card, as the OS will boot from SD by default.

The device's compatible operating systems are all Linux distributions. For its low memory overhead, Linux was chosen at least partially, making it possible to run a fully functioning OS on such a simple computer that is devoid of permanent storage built-in. As a CS learning tool, Linux is also usually free and has great potential, because its releases come with some already installed programming languages.

As developers hop on the bandwagon to provide material, the open-source nature of Linux will help in the proliferation of applications. The Raspberry Pi Foundation’s original goal was to build both the system and the learning curriculum around it, but the organization chose to scale its scope down, focus on developing the machine and let software be developed by an enthusiastic and willing open-source programming community.

The programmability and simplicity of the Raspberry Pi make it similar to the computers of yesteryear that spawned so many programmers and machine hobbyists. But this system can be used for Web browsing, unlike these computers. The Internet makes it easier to find things to do with the computer than back in the day. On the Raspberry Pi web, there is an online user forum, and tutorials and other materials are easily accessible. Of course, to enable network connectivity, you will need either a Model B Ethernet Connector or an external WiFi system connected via USB.

Distributions of Linux for Raspberry Pi

With the Debian Squeeze, Arch Linux ARM and Fedora 14 Remix distributions, the Linux OSs available for the Raspberry Pi are continuously developing. But the four versions of Linux available for download from the Raspberry Pi site as of August 2012 are:

• Raspbian Wheezy — Debian Wheezy is an unofficial port. This is the preferred operating system for Linux beginners. It has a graphical GUI for the LXDE GUI, a Web browsing Midori browser, various programming tools, and source code examples.

• Debian Wheezy soft-float — Almost similar to Raspbian Wheezy, this version uses a binary interface (ABI) soft-float application rather than Raspbian hard-float, slowing performance, but enabling compatibility with some specialty software that does not operate with hard-float ABI.

• Arch Linux ARM — This OS has the most user access, but because of the lack of a GUI, it is not quite Linux novice-friendly.

• QtonPi — This is a software development kit (SDK) embedded Linux framework specifically designed to build applications through QT 5, a rapid development environment for embedded devices, mobile apps, and other applications.

Why choose the Raspberry Pi and not anything else?

The Raspberry Pi has a few competitors, but the foundation encourages individuals to clone the concept, so competitor might not be the right word. BeagleBoard and PandaBoard (which are both the companies' names and their key devices) are included. They are also non-profit organizations, but with aims somewhat different from the Raspberry Pi Foundation. BeagleBoard targets adult hardware tinkerers, and PandaBoard aims to provide a moderately priced mobile software-programming platform.

Like Raspberry Pi, ARM processors are both exposed boards and capable of HD video. But there are more connectors and link headers (board bits that can be used by soldering additional hardware) on BeagleBoards and PandaBoards than on the Raspberry Pi, and both devices are bigger. The following are not comprehensive part lists, but here are some characteristics that vary from Pi:

BeagleBoard and BeagleBoard-xMBoard-

• Texas Instruments Cortex A8-based processor, running on the BeagleBoard from 600 MHz to 720 MHz (depending on version) and 1 GHz on the xM.

• 128 MB RAM on the original BeagleBoard, but on the newer boards, 256 MB and 512 MB RAM, respectively.

• Connector DVI-D display

• S-video adapter

• Audio (not all audio out) in and out

• One BeagleBoard USB port and four xMM USB ports are included.

• Power from USB and DC

• No RCA or HDMI connector

• ES PandaBoard & PandaBoard

• Dual-core ARM Cortex A9 MPCore processor, also manufactured by Texas Instruments, on the PandaBoard at 1GHz and on the ESS at 1.2 GHz

• 1 GB of RAM

• Connector DVI-D display

• Header for LCD expansion

• One on-the-go USB port and two regular USB connections

• Connectivity with WiFi and Bluetooth

• Power from USB and DC

• No RCA connector

The Raspberry Pi has two advantages over the others for their intended educational purposes. Second, it was conceived to be a full machine that functions. Insert an OS-containing SD card, attach the power and peripherals, and it's ready to go. For initial setup, BeagleBoards and PandaBoards need to connect to a host device, and while they have similar processing capabilities, they need a little more know-how to get them fully operating.

Secondly, the other appliances are a lot more costly than the Raspberry Pi. In April 2012, the two main BeagleBoard models were $125 to $149, and $174 to $182 for the two PandaBoard models. These prices are a far cry from the Raspberry Pi 's $25 and $35 base prices. That's not to suggest the other gadgets aren't for you. Review the specifications and decide which computer fits your requirements best. The Raspberry Pi seems best placed to get computing power to the masses, given its functionality and price.

Hardware aside, for those wishing to learn programming on current computers, software-based educational tools are available.

OLPC, Sweets from Cotton, and Arduino

Some other computers, including OLPC laptops, the Cotton Candy stick machine and Arduino boards, merit mention here. One Laptop Per Child (OLPC) is a charitable organization that seeks to provide children in developing nations with complete, durable, WiFi-enabled laptops. Running at 1 GHz, the XO-1.5 model has 1 GB of RAM and 4-32 GB of internal flash memory. It runs a specially designed Linux distribution, much like the Raspberry Pi.

The Cotton Candy is a thumb-drive-sized gadget that can transform a monitor into your TV, like the Pi. It has a 1.2 GHz ARM Cortex-A9 processor, a high-def GPU ARM Mali-400MP, 1 GB of RAM, a slot for SD cards, WiFi, an HDMI port, and USB connectors. It runs Linux and virtualization clients for Android or Ubuntu for other OSs. It is intended for accessing Web or media content rather than programming education, unlike the Pi.

Arduino boards are microcontroller boards with smaller quantities of memory and speed built in. They can be used to construct simple computers with components such as motors or blinking lights to operate physical devices, and can be used in combination with computers such as the Pi. Will anybody want to create a robot?

What are the Raspberry Pi 3's specs?

• Chipset: Broadcom BCM28377

• Chipset:

• 1.2 GHz quad-core 64-bit ARM cortex A533

• Ethernet: 10/100 (100Mbps max throughput)

• USB: Four USB 2.0 with data transfer of 480Mbps

• Storage: MicroSD card or storage attached via USB

• Wireless: 802.11n Wireless LAN (150Mbps peak transmission / receive throughput), Bluetooth 4.11n

• Graphics: 400MHz multimedia from VideoCore IV

• Memory: 1 GB SDRAM LPDDR2-900

• Expandability: 40 input-output pins for general purposes

• Complete HDMI port

• Audio: 3.5 mm audio output jack and composite video jack combined

• Interface with a Camera (CSI)

• Interface view (DSI)

How can I use my Raspberry Pi 3 to get the most?

It's good advice to get a case to protect the Pi from harm, particularly if you're going to bring the Pi elsewhere. You may also invest in a high-speed micro SD card, as illustrated below, if efficiency is important to you.

Although the Pi can run a number of different operating systems, the official Raspbian operating system is a good option if you're after reliability and performance, having been tuned to get the most out of the Pi, bundling a fast web browser and a decent range of office and programming applications.

You can also go to the terminal and type 'sudo raspi-config' if you have not installed the Raspbian OS using the Noobs installer and are running out of space, and then select the option 'Expand root partition to fill the SD card' to ensure that you are using all available space on the card.

Chapter Two

Getting Started with The Raspberry Pi

Pi Drawbacks

Whether you want to learn the Raspberry Pi 's capabilities or are a seasoned veteran, here are some projects that you might want to consider pitting your wits against.

1. Building a basic buggy robot

A perfect introduction project to the Raspberry Pi world is this buggy robot. This project will help any amateur Pi user learn how to create a small robot with simple python commands that can be managed.

You will learn:

•How to set up an engine controller board with two engines

•How motors can be managed using Python

•How to make a chassis for a robot

You will need:

• Raspberry Pi 3

• Board of motor controllers

• 2 x 3V-6V DC engines

• 2 wheels

• Batteries and battery holders

• Ball caster

• Leads from the cable or jumper

• A USB pack of batteries

• Equipment for simple electronics

2. See like a bat

For anyone who loves bats and Raspberry Pi, here's yet another fun project. In this project, you will learn how to construct a wearable echolocation device to help you "see like a bat."

You will learn:

• How to create a potential divider

• How to set up an ultrasonic distance sensor

• How to calculate the range of ultrasonic pulses

• How to power a small motor using Pulse Width Modulation (PWM)

• Why functions can be used to overcome abstract mathematical problems

You will need:

• Raspberry Pi 3

• Ultrasonic sensor of distance

• Vibration engine

• 1 1.2k (or other-see worksheet) resistor

• 1 Resistor of 2.2k (or other-see worksheet)

• 1 x Breadboard Solderless

• 6 x Leads male-to-female jumper

• 2 x Leads from male-to-male jumper

• 6 x jumper for female-to-female leads

3. Create a smart mirror

You will get the opportunity to create your very own smart mirror in this project. When done, applications and details related to items such as the weather, local news, or anything you like can be shown in your new mirror.

The project is also modular and can be moved around or hung on a wall with ease.

You will need:

• 1 x Pi 3 Raspberry

• 1 x Low-profile monitor (or old display)

• 12 ft-1x2 12 ft-1x3 1 x Glue Wood

• 1 x HDMI cable with low profile

• 1 x 18-24" "See-Through Acrylic Mirror, 1 mm

4. Creating an automatic gardener

Why not get a Raspberry Pi to garden for you if you’re fed up with tending to your indoor plants with your precious time? You will get to do just that in this project.

On completion, this project will teach you how to water and light your plants by creating a portable automated Raspberry Pi-powered gardener. You'll never have to remember watering your domestic plants again.

You will need:

• Raspberry Pi Zero around 1

• Peristaltic 12v pump 1

• White Silicone Tubing, 1/8-inch ID, 3/16-inch OD

• 5v Grow Light to 1

• IRLB8721PBF MOSFET N-Channel · 2

• Jumper wires (generic)

• M4 Bolts + Nuts x 4

• M3 Bolts + Nuts > 2

• M2.5 Bolts + Nuts > 2

• Electrical Tape Number 1

• 12v Power Supply ~ 1

5. Create a quadcopter for the Raspberry Pi

You may want to consider this if you are familiar with creating Raspberry Pi projects. You can create your very own quadcopter drone here, which is powered by your very own Raspberry Pi software.

To build the drone assembly, you'll need a few more parts than other projects we've mentioned, apart from a Raspberry Pi 3, Navio Kit, and simple electronics equipment. For more info, check out the full guide.

6. Create your own mobile phone

For more sophisticated Raspberry Pi DIYers, this initiative will undoubtedly test your skills to the max. This project will show you how to make a Pi-Phone, your very own mobile phone.

This project's developer managed to scavenge and piece parts together to assemble it for as little as $160.

You will need:

• Model B of Raspberry Pi

• PiTFT 320-240 touchscreen

• Battery of 2500mAh LiPo

• GSM / GPRS SIM900 module

• 3.3V to 5V 1A DC-DC boost converter

• Cables, sockets, switches, etc.

7. Using a Raspberry 4 to make a pocket laptop

Last, but by no means least, is this beautiful, but complicated, Raspberry Pi project. Here, using cardboard and Raspberry Pi 4, you can make a mini-pocket laptop.

It's a little more hands-on than other projects on the list, but your expertise will surely be brought to the next level.

This configuration uses a 4 GB Raspberry Pi 4, a Bluetooth keyboard, a Power PCB, and a 7-inch monitor. Naturally, you may change the template to suit your own preferences and budget.

Raspberry Pi Benefits

The Raspberry Pi has made its way into the computing hobby market, but it is still very capable for other business and personal uses. For a compact and lightweight server, an incredibly low power draw, small form factor, no noise, solid state storage, and other characteristics make it an appealing solution.

I have been playing with a Raspberry Pi (revision B) running various GNU / Linux distributions recently. I wanted to take it for a spin and see what I could throw at it, because the Pi is essentially a mini-computer. I was pleasantly surprised. In reality, it's been so good that I decided to try setting it up with different services as a mini server. In doing so, I have come up with a list of benefits that I believe are very persuasive.

1. Power consumption. The Pi draws about five to seven watts of energy. This is around one tenth of what could be found in a similar full-size box. Since servers operate night and day on an ongoing basis, the electrical savings can really add up. I have estimated that the simple Pi package (Pi board, case, and power supply) would pay for itself if it is left to run 24/7/365, with around one year's worth of electricity savings. I ended up with a very cheap and high quality CanaKit Basic Kit (ASIN # B00DG9D6IK).

2. No moving parts . The Pi uses an SD card for storage that is fast and has no moving parts. There are no supporters or other things to think about as well. Compared to lower level cards, a Class 10 SD card is typically the highest performing, but this will primarily only impact boot time where there is the most I / O. There is a compatibility chart for SD cards here, the results can differ, but overall, Transcend cards have a good value. I have had very good luck.

3. Small form factor. You can hold the Pi (with a case) in your hand. It is unlikely for a similar full-size box. This implies that the Pi can also be incorporated into devices.

4. No noise at all. the Pi is absolutely quiet.

5. Status lights. On the Pi's motherboard, there are multiple status lights. You can see NIC operation, disk I / O, power status, etc., with a simple event.

6. Expansion capabilities. Several devices are available for the Pi, all at very affordable prices. From an I / O board (GPIO) to a camera, everything. There are two USB ports in the Pi, but more devices can be added by hooking up a powered USB hub.

7. Built-in graphics capable of HDMI. The display port on the Pi is HDMI and can accommodate resolutions up to 1920, which is useful for, for example, turning the Pi into a video player box. For backwards compatibility, there are several converters that can convert to VGA. It is possible to find a list of HDMI to VGA converters here. I ended up using the VGA (ASIN # B0088K7QUQ) Sanoxy HDMI cable that has so far performed well.

8. Affordable. The Pi (revision B) provides the best specs for the price, at least I've noticed, compared to other similar alternatives. It is one of the few devices which offers 512 MB of RAM in its class. Since it first arrived, the Pi has come down in price, and is ultimately affordable as a hobby, business use, or whatever necessity there is.

9. Massive support for the community. The Pi has phenomenal community support. Help can be obtained very easily for hardware and/or GNU / Linux software that, depending on the GNU / Linux distribution used, runs primarily on Pi in user forums. It is possible to find a good list of distributions here.

10. Overclocking functionality. If there are performance issues with the program used, the Pi may be overclocked, but this is at the cost of the user doing so.

11. Multiple uses. The storage on an SD card makes it easy to switch between other SD cards running other GNU / Linux distributions to adjust the Pi features quickly and easily. If you want to set up the Pi to test it as a server, then try something else later, just swap the SD card and you're done. A backup of the SD card can be generated using the 'dd' command on a GNU / Linux machine and restored later if needed.

With all the good stuff about the Pi, there are a few minor disadvantages:

1. ARM architecture. While ARM is a highly efficient and low-powered architecture, it is not x86 and therefore it is not possible for any binaries compiled to run on x86 to run on Pi. The good news is that for the ARM architecture, complete GNU / Linux distributions have been compiled and new ones are emerging all the time. There are very few applications where x86 is completely necessary. Wine, which runs Windows programs, is the only one that I have found so far to be a concern. Wine, unfortunately, doesn't work on the Pi.

2. Non-upgradable RAM. The main Pi components are soldered to the motherboard, including 512 MB of RAM. However, this is not a concern, as GNU / Linux can easily run on it. I've found that when operating a small server, the Pi uses around 100 MB of RAM (without X11 running).

The Pi software

The Pi runs GNU / Linux and similar operating systems. Windows running is not such a success story; there are so many technical issues with running Windows on the Pi, so Windows was considered impractical.

The Raspberry Pi is a single credit card-sized computer board that can be used for several computer tasks, such as sports, word processing, spreadsheets, and even HD video playback. It was established in the UK by the Raspberry Pi Foundation. Since 2012, it has been prepared for public consumption with the idea of giving students and children a low-cost educational microcomputer. The Raspberry Pi board design’s main aim is to promote learning, experimentation, and innovation for students at the school level. The compact and low cost of the raspberry pi board. The maximum number of Raspberry Pi computers in cell phones is used. The growth of mobile computing technology in its 2nd century is very high, a significant segment of which is powered by the mobile industries. ARM technology is used by 98% of all cell phones.

Raspberry Pi Tech

The Raspberry Pi is available in two versions, model A and model B. The primary distinction between model A and model B is the USB port. The Model A board `uses less power and an Ethernet port is not included. The Model B board, however, contains an Ethernet port developed in China. In 2014, the foundation of the Raspberry Pi board released the computer module, which packs a model B Raspberry Pi board into a module for use as part of embedded systems, to promote its use. The Raspberry Pi comes with a range of open source technologies, i.e. communication and multimedia web technologies.

Specifications of the Raspberry Pi Hardware

A program memory (RAM), processor and graphics chip, CPU, GPU, Ethernet port, GPIO pins, Xbee socket, UART, and power source connector are included in the Raspberry Pi board. And separate interfaces for other devices that are external. It also requires mass storage, so we use an SD flash memory card for that. Similarly, the Raspberry Pi board can boot from this SD card like a PC boots from its hard disk.

SD cards containing Linux OS, US keyboard, display, power supply, and video cable are mainly important hardware specifications of the Raspberry Pi board. USB mouse, powered USB hub, case, internet link, and Model A or B are optional hardware specifications: a USB WiFi adaptor is used and LAN cable is used for internet connection to Model B.

About memory

Aboard's Raspberry Pi model is equipped with 256 MB of SDRAM and 51 MB is designed for model B. Compared to other PCs, Raspberry Pi is a small size PC. Gigabytes of standard PC RAM memory is available. But the RAM memory is more than 256 MB or 512MBB usable in the Raspberry Pi board.

CPU (Central Unit of Processing)

The Central Processing Unit is the brain of the Raspberry Pi Board and is responsible for carrying out logical and mathematical operations of the computer 's instructions. The Raspberry Pi uses the ARM11 processor series, which has entered the Samsung Galaxy phone ranks.

GPU (Unit for Graphics Processing)

The GPU in the Raspberry Pi board is a specialized chip designed to speed up the image calculations process. This board is designed to support Open GLL with a Broadcom video core IV.

Port of Ethernet

The Raspberry Pi Ethernet port is the primary gateway for communicating with additional computers. The Raspberry Pi Ethernet port is used to plug your home router to access the internet.

Pins from GPIO

In the Raspberry Pi, the general purpose input & output pins are used to communicate with the other electronic boards. These pins can accept input & output commands based on Raspberry Pi programming. The Raspberry Pi offers GPIO digital pins. These pins are used to connect other electronic components. For instance, to transfer digital data, you can link it to the temperature sensor.

XBee Socket

The XBee socket is used for wireless networking purposes on the Raspberry Pi board.

Connector to Power Source

A small switch is a power source cable that is positioned on the side of the shield. Enabling an external power source is the main purpose of the power source connector.

UART

A serial input & output port is a Universal Asynchronous Receiver/ Transmitter. This can be used in the form of text to transfer serial data and is helpful for converting the debugging code.

Displays

The Raspberry Pi board's link options are two styles, HDMI and Composite. Several LCD and HD TV monitors can be paired with an HDMI male cable and a low-cost adaptor. HDMI versions 1.3 and 1.4 are supported, and a cable version of 1.4 is suggested. The Raspberry Pi audio and video O / Ps are supported by HMDI but do not support HDMI I / p. Older TVs can be linked using composite video. Audio is accessible from the 3.5 mm jack socket when using a composite video link and can be sent to your television. You need a cable which adjusts from 3.5 mm to double RCA connectors to send audio to your TV.

Raspberry Pi Board Model A

A Broadcom (BCM2835) SOC (system on chip) board is the Raspberry Pi board. It is available fitted with an ARM1176JZF-S core CPU, 256 MB SDRAM and 700 MHz. Raspberry Pi USB 2.0 ports only use external options for data access. The micro USB adapter draws its power from the board, with a minimum range of 2 (500 MA) watts. The advanced graphics chip is designed to accelerate the process of image calculations. This is designed with the Broadcom video core IV cable, which is helpful if you want your Raspberry Pi to run a game and video.

Raspberry PI Model A Features

The Raspberry Pi features of model A primarily include:

• 256 MB of memory SDRAM

• Single USB 2.0 connector

• Coprocessor for Dual Core Video Core IV Multimedia

• Composite RCA (PAL and NTSC) Video Out (HDMI) (rev 1.3 & 1.4)

• Jack 3.5 MM, HDMI, Audio Out

• SD, MMC, SDIO Card slot on the storage board

• Operating System for Linux

• Total HD Broadcom BCM2835 SoC Multimedia Processor

• Scale 8.6cm*5.4cm*1.5 cm

Raspberry Pi Model B Board

A Broadcom BCM2835 SOC (system on chip board) is the Raspberry Pi. A 700 MHz, 512 MB SDRAM and ARM1176JZF-S core CPU are included. Only external data access options are used for the USB 2.0 port of the Raspberry Pi Boars. The Ethernet in the Raspberry Pi in model B is the primary gateway for interconnecting with other devices and the internet. This draws its power, with a minimum range of 2.5 watts (500 MA), from a micro USB adapter. The advanced chip for graphics is designed to accelerate the manipulation of image calculations. This is designed with the Broadcom video core IV cable, which is helpful if you want your Raspberry Pi to run a game and video.

Set up & launch your Raspberry Pi

With an SD card, the Raspberry Pi board comes packed. This slot allows us to insert an SD card and our computers can use it. The SD card is a key Raspberry Pi board storage unit like a personal computer's hard disk. The bootable Linux operating system you are intending to use is loaded into the card. Raspberry Pi supports operating systems for Linux, Qtonpi, ARM, and Mac. One Iso can be selected; you will need to write it to an SD card using the program Disk Manager. Other storage mechanisms, such as an external USB hard disk or a USB drive, may also be used. There are several brands of SD cards that are available in various sizes on the market. The Raspberry Pi supports a maximum SD card of 64 GB.

You're going to need to connect a monitor, keyboard, mouse like a PC before you start your raspberry pi. It supports three different O / Ps, such as HDMI video, composite video, and DSI video, where some special hardware is required for the DSI video. It can be sold with or without an SD card when you purchase a Raspberry Pi board. It is a very important raspberry pi board specification. Since it retains the operating system, records and services. If the SD card didn't come with your raspberry pi, then the minimum size you could get is 4 GB.

The benefits of the Raspberry Pi are that it is small in size and operates to manage web traffic like a regular machine on a low cost server.

Applications of Raspberry Pi

In many applications such as video streamers, arcade machines, tablet computers, home automation, car computer, internet radio, robot power, cosmic computers, meteorite hunting, coffee, Raspberry Pi boards are used.

Motor Speed Control depending on Raspberry Pi

The main goal of this project is to use the Raspberry Pi to regulate the speed of a DC motor.

Hardware and software Requirements

DC Engine, Raspberry Pi model, TV or PC display, IC Engine Driver, LED, Resistors, Capacitors, Diode, Transformer, Voltage Regulator and PHP program / cable pi.

Motor Speed Control Block Diagram Based on Raspberry Pi

To monitor the DC motor velocity, this project uses a Raspberry Pi board. A DC motor's speed is directly proportional to the voltage applied across its terminals. When the voltage varies across the motor terminal, the speed varies accordingly as well. To run the engine at different speeds by pressing the key, a keyboard must be linked to the Raspberry Pi board.

The PWM (pulse width modulation) is activated at the output according to the software, and it can be programmed using PHP / wiring pi. The average current and voltage change according to the service cycle, so the DC motor speed will also change. For receiving PWM signals and sending the desired O / P to the DC engine, a motor driver IC is connected to the board.

Using Raspberry Pi, Auto Intensity monitoring of streetlights

The main objective of this project is to use Raspberry Pi to monitor the automatic strength of streetlights.

Requirements for Hardware and Applications:

The transformer, the diodes, the capacitors, the resistors, the LEDs, the Raspberry Pi frame, the TV or PC display, the White LEDs, the MOSFET, the Crystal, the PHP or the Wiring Pi software.

This project uses many LEDs as streetlights that use less electricity. When compared to the HID lamps, the lifespan of the LEDs is also greater. To regulate the intensity, a Raspberry Pi is used by generating pulse width modulation signals that drive a MOSFET to turn the LEDs to achieve the desired operation.

The intensity of LEDs gradually varies from evening to the next day, particularly during peak hours, with maximum light intensity and then slowly decreasing the intensity of the decreasing lights. In the Raspberry Pi software, MOSFET switching by pulse width modulation technique is implemented to provide variable voltage across the LEDs

List of projects focused on the Raspberry Pi

• Raspberry Pi programmable sequential switching

• Solar Street Light-Based Raspberry Pi

• Synced and Christmas Lights Music

• Raspberry Pi Wearable Powered Device

• Raspberry Pi home automation

• Tablet touch screen

• Industrial automation focused on Raspberry Pi using Zigbee communication

• Enclosure with Lego Raspberry Pi

• Raspberry Pi as a transmitter for FM

• Robot Arm Control Autonomous Based on Raspberry Pi with Bluetooth Control

• Console Retro Gaming

Nostalgia for technology is true, and this latest (or old) trend has been at the forefront of retro gaming consoles. When they were first rereleased, the classic Nintendo systems sold out. SEGA and Atari both capitalized on the craze and issued their own. One can simulate over 40 retro gaming systems, over 30,000 games, customize your game lists, and play with up to 5 players with a Raspberry Pi. You can build your own arcade full of your favorite games from the past, using Recalbox or RetroPie.

In order to create a cluster (known as a "bramble"), some individuals also combine several Raspberry Pi. It is possible to use the Raspberry Pi 3 cluster as an efficient computing system. The largest bramble ever built was a GCHQ-built 96 Raspberry Pi computer.

How the Mini PC Craze was brought on by Raspberry Pi

One of the key reasons for its success is the small, compact size and low cost of a Raspberry Pi. This takes me to another compact and strong piece of technology that all of us should consider adding mini PCs to our lives.

The Raspberry Pi's rise in popularity helped customers see the many advantages of a portable machine. In the mini PC craze, the concept of a powerful, compact, and well-priced machine helped bring in. A mini PC in a miniature compact case is a desktop computer. This takes up considerably less space than a typical CPU desktop tower. There are various mini Windows and Linux PCs, and either a Ready-to-Go setup or a version of Barebones can be selected. A Barebones package contains a shell, motherboard, and processor, meaning a hard drive, operating system, and RAM must be added. All you need to get started includes a Ready-to-Go pack.

The benefits of a mini PC are its size, usability (easy to change components and easy to switch from one screen to another), cost (you can find one for about $300), and low energy consumption (you can find one for about $300).

The go-to set-up for a portable computer has been laptops and tablets, but there is so much that these machines can do. As a mix of both a laptop and a desktop, you can create a mini PC. One can have the comfort of a laptop, but a desktop's capacity and upgrade capabilities.

For work and business use, home entertainment purposes, gaming, video conferencing, and media creation, many individuals use mini-PCs. Incorporating the best of all worlds provides mini PCs with several benefits.

Chapter Three

Linux System Administration

An Overview

Linux is an open-source Unix culture, including the Linux Kernel-based operating systems. On September 17, 1991, it was initially published by Linus Torvalds. It is a free and open-source operating system, and under the GNU General Public License, the source code can be updated and distributed to anyone commercially or non-commercially.

Linux was originally designed for personal computers and was eventually used on other computers, such as servers, mainframe computers, supercomputers, etc. Linux is also used today in embedded systems such as routers, controls for automation, TVs, digital video recorders, video game consoles, smartwatches, etc. Linux’s greatest success is the Android operating system; it is based on the Linux kernel that runs on smartphones and tablets. Linux has the highest user base of all general-purpose operating systems because of Android. Generally, Linux is bundled inside a Linux distribution.

Distribution on Linux

The Linux distribution is an operating system consisting of a series of Linux kernel-based applications, or you might assume that the distribution includes the Linux kernel and supports libraries and software. And by installing one of the Linux distributions, you can get a Linux-based operating system and these distributions are available for various types of devices, such as embedded devices, personal computers, etc. There are around 600+ Linux distributions available, and some of the common distributions for Linux are:

• MX Linux

• Manjaro

• Mint Linux

• Elementary

• Ubuntu

• Debian

• Solus

• Fedora

• OpenSuse

• Deepin

Linux architecture

The following components belong to the Linux architecture:

1. Kernel: Kernel is the foundation of the operating system that is based on Linux. To provide each process with its virtual resources, it virtualizes the computer's common hardware resources. This makes it look as if the method is the only process operating on the computer. It is also the duty of the kernel to avoid and manage conflicts between various processes. The different kernel forms are:

• O Monolithic Kernel

• O Kernel hybrids

• O Kernels of Exo

• Micro kernels of O

2. Device Library: Particular types of functions that are used to enforce operating system features.

3. Shell: This is a kernel interface that hides from users the ambiguity of the kernel’s functions. It takes user commands and executes the functions of the kernel.

4. Hardware Layer: This layer consists of all RAM / HDD / CPU peripheral modules, etc.

5. System Utility: This provides the user with the features of an operating system.

Linux Advantages

Linux’s biggest benefit is that it is an operating system that is open source. This ensures that the source code is freely accessible to anyone and you can contribute, change and distribute the code to anyone without permission. Other advantages include:

• Linux is better than any other operating system in terms of stability. This does not mean that Linux is 100% stable, but it is less vulnerable than any other operating system, since it has some malware. So, anti-virus software is not needed.

• Linux software updates are quick and regular.

• There are various Linux distributions available to use according to your needs or your taste.

• Linux is freely accessible on the internet to use.

• It has tremendous community support.

• It offers great stability. It seldom slows down or freezes and, after a short time, there is no need to reboot it.

• It protects the user's privacy.

• The Linux system's performance is much better than that of other operating systems. This allows a large number of individuals to function at the same time and it manages them effectively.

•  Network-friendly it is.

• Linux's versatility is strong. There is no need to install a full Linux suite; only the necessary components need be installed.

• A large range of file formats are compatible with Linux.

• Installation from the web is simple and convenient. It can also be mounted on any hardware, including your old operating device.

• Even if it has limited hard disk space, it performs all the tasks properly.

Linux drawbacks

• It is not particularly user-friendly. So, for beginners, it can be frustrating.

• Compared to Windows, it has limited peripheral hardware drivers.

Linux Basics

Basic Linux Commands:

You need to open the command line first before we move on to the list of commands. Check out this CLI tutorial if you are still uncertain about the command-line interface. Although the steps can vary depending on the distribution that you're using, the command line can typically be found in the Utilities section.

Here is a list of the Linux basic commands:

1. Command pwd

To find out the direction of the current working directory (folder) you are in, use the pwd command. The command returns an utter (full) path, which is essentially a path that starts with a forward slash (/) for all the directories. /home / username is an instance of the absolute path.

2. Command to cd

Use the cd command to move through the Linux files and folders. Depending on the actual working directory you're in, it includes either the full path or the name of the directory.

Let's presume you're in the /home / username / Documents directory and you want to go to the Documents subdirectory Images. Simply type the following command in order to do so: cd Images.

Another case is if, for example, you’re in the /home / username / Movies directory and you want to move to a completely new directory. In this case, you must type cd, followed by the absolute path of the directory: cd /home / username / Movies.

To help you navigate easily, there are several shortcuts:

• cd . (with two dots) for one directory to step up

• CD to go directly to the home folder

• cd- to switch to your previous directory (with a hyphen)

Linux's shell is case sensitive, on a side note. You must type the directory name exactly as it is.

3. Control ls Command ls

For displaying a directory’s contents, the ls command is used. By default, the contents of your current working directory will be shown with this instruction. Type ls, and then the directory route, if you want to see the content of other directories. To access the content of documents, for example, enter ls /home / username / Documents.

With the ls command, there are variations you can use:

• ls -R can list all sub-directory files as well as all sub-directory files.

• ls -a reveals concealed directories

• ls -al lists files and directories containing detailed data such as permissions, size, owner, etc.

4. Cat order, cat command,

One of Linux's most commonly used commands is cat (short for concatenate). It is used in the standard output (sdout) to list the contents of a file. In order to run this command, type cat, followed by the name and extension of the file. For example: cat file.txt.

Here are other ways for the cat command to be used:

• A new file is generated by cat > filename

• cat filename1 filename2 > filename3 joins and stores the output of two files (1 and 2) in a new file (3)

• cat filename tr a-z A-Z > output.txt to convert a file to upper- or lower-case use.

5. The cp order command

Copy files from the current directory to a separate directory using the cp command. For example, the cp scenery.jpg /home / username / Pictures command generates a copy of scenery.jpg in the Pictures directory (from your current directory).

6. MV command

The mv command's primary use is to transfer files, although it can be used to rename files as well. In mv, the arguments are identical to the command cp. You need to type mv, a name for the file, and a directory for the destination. MV file.txt /home / username / Documents, for example.

The Linux command to rename files is: mv oldname.ext newname.ext newname.ext.

7. The MKDIR command

Use the mkdir command to create a new directory, and if you type mkdir Music, a directory called Music will be created.

There are additional mkdir commands also:

• Use this Linux simple command, mkdir Music / Newfile, to create a new directory within another directory.

• To create a directory between two existing directories, use the p (parents) option. For example, mkdir -p Music/2020/Newfile creates a new file called '2020.'

8. Order to rmdir

Use the rmdir command if you need to delete a directory. However, rmdir only allows empty folders to be removed.

9. The rm order command

To delete directories and the contents inside them, the rm command is used. Using rm -r if you only want to uninstall the directory as an alternative to rmdir.

Note: With this order, be very cautious and double-check which directory you are in. This will erase it all, and there is no undoing.

10. Touch Order Command

The touch command allows you to use the Linux command line to build a new, blank file. For example, to build an HTML file entitled Web under the Documents directory, enter touch /home / username / Documents / Web.html.

11. Locate command

You can use this command, much like the search command in Windows, to find a file. What's more, it will make it case-insensitive by using the -i argument along with this button, so you can scan for a file even if you don't know its exact name.

Use an asterisk (*) to scan for a file that includes two or more words. For instance, the locate -i school*note command will search for any file containing the words "school" and "note" in upper or lower case.

12. Find Command

Similar to the locate order, scan for files and directories by using find as well. The difference is, to locate files in a given directory, you use the find command.

For example, the find /home/ -name notes.txt command will search the home directory and its subdirectories for a file called notes.txt.

By using the discovery, other variants are:

• To search files using the current directory, locate. -name notes.txt

• / -style d -name notes to check for directories to use.

13. The Grep command

Grep is another simple Linux command that is unquestionably helpful for daily use. It helps you to browse through all the text in a specific file. For example, Grep blue notepad.txt looks for the word blue in the notepad file. There will be completely displayed lines containing the searched term.

14. Command sudo

This instruction, short for SuperUser Do, allows you to perform tasks that require administrative or root privileges. Using this command for everyday use, however, is not recommended because if you did anything wrong, it would be easy for an error to occur.

15. The df order command

Using df to get a report of the disk space consumption of the device, shown in percentages and KBs. Type df -m if you want to see the report in megabytes.

16. Du command

The du (Disk Usage) command is the answer if you want to check how much space a file or a directory takes. However, instead of the normal size format, the disk use overview will include disk block numbers. Add the -h argument to the command line if you want to see it in bytes, kilobytes, and megabytes.

17. Head command

To access the first lines of any text file, the header command is used. It shows the first ten lines by default, but you can change this number to your taste. Type head -n 5 filename.ext, for example, if you just want to view the first five lines.

18. Tail command

This one has a feature similar to the head command, except the tail command would view the last ten lines of a text file instead of displaying the first lines. Tail -n filename.ext, for example.

19.Diff command

The diff order, short for difference, compares the contents of two files line-by-line. It will output the lines that do not fit after evaluating the files. Programmers also use this order instead of rewriting the entire source code when they need to make program alterations.

Diff file1.ext file2.ext is the simplest form of this command.

20. The tar order command

The tar command is a popular Linux file format that is identical to the zip format, with compression being optional, and is the most used command to archive several files into a tarball.

With a long list of functions, such as adding new files to an existing archive, listing the content of an archive, removing content from an archive, and many more, this command is very complex.

Introducing Raspbian

Raspbian is a free Debian-based operating system designed for the Raspberry Pi hardware. The collection of basic programs and utilities which make your Raspberry Pi run is an operating system. Raspbian, however, offers more than just a pure OS: it comes with more than 35,000 packages of pre-compiled software packed nicely for quick installation on your Raspberry Pi.

In June 2012, the initial construction of more than 35,000 Raspbian packages designed for the best results on the Raspberry Pi was completed. Raspbian, however, is still being actively developed with a focus on enhancing the reliability and performance of as many Debian packages as possible.

Note: Raspbian is not affiliated with the Base of Raspberry Pi. A small, dedicated team of developers who are fans of the Raspberry Pi hardware, the Raspberry Pi Foundation 's educational objectives and, of course, the Debian Project, developed Raspbian.

Use external computers for storage

A device that holds all the addressable data storage that is not within the main storage or memory of a computer is an external storage device, is often referred to as auxiliary storage and secondary storage. Removable or non-removable, temporary or permanent, and available over a wired or wireless network may be an external storage unit.

External storage allows users to store data independently at a comparatively low cost from the main or primary storage and memory of a device. It increases storage space without having to open up a device.

External storage is mostly used to store information that programs running on a desktop, laptop, server, or mobile device, such as an Android or iOS smartphone or tablet, have less regular access to.

An external storage device for PCs mostly consists of stationary or portable hard drives (HDDs) or solid-state drives (SSDs) connected to or wirelessly through a USB or FireWire link.

An external storage device can serve as primary storage linked to servers via Ethernet or Fibre Channel switches for businesses, or as secondary storage for backup and archiving purposes. External storage provides block-based, file-based or object storage HDD, all-flash and hybrid storage arrays, or a combination of these three protocols known as unified storage. Examples of external storage are storage area networks (SANs) for block-level storage and network-attached storage (NAS) systems for file-based storage.

The transport of data between on-site and off-site computer systems is another common case for an external storage unit.

When transferring vast volumes of data to the cloud, providers will also use external storage devices in a practice known as cloud seeding. Since it can take hours or days to transfer tens of terabytes of data over a network, clients put their data on an external storage device and send the device to their preferred provider for copying locally. Only modified data will travel through the network to the cloud for backup, archiving or disaster recovery (DR) purposes after the initial seeding.

New User Account Formation

You were given the opportunity to build one or more user accounts using the Setup Agent when you first started using your Red Hat Enterprise Linux framework after installation. You can now do so if you have not built at least one account (not including the root account). For everyday activities, you can avoid working in the root account.

There are two ways to build new and/or additional user accounts: from a shell prompt or using the graphical User Manager program.

To use the User Manager to graphically build a user account:

1. Pick Applications = > Device Settings = > Users & Groups from the panel (the main menu on the panel). By typing redhat-config-users at the shell prompt, you can also start the User Manager.

2. If you are not signed in as a root, your root password will be prompted.

3. The window should be visible. Click User Connect.

Software Install and Uninstall

Users are accounts that can be used in a system to login. Each consumer is recognized by the system through a unique identification number or UID. All device user information is stored in the /etc / passwd file. Users' hashed passwords are stored in the /etc / shadow format.

On the basis of the degree of access, users can be divided into two categories:

1. Superuser / root / administrator: All the files on the server can be accessed.

2. Standard users: Access limited.

When a new user is created, the system takes the following actions by default:

• Assigns the user a UID.

• Establishes the /home/ home directory.

• Sets the user's default shell as /bin / sh.

• Build a private community of users named after the username itself.

• Contents of /etc / skel are copied to the current user's home directory.

• .bashrc, .bash profile, and .bash logout are copied to the new user's home directory. These files contain the user's session environment variables.

Definition of /etc / passwd File Contents

Any user can read this file, but only root as a read and write permission for it. This file is composed of the following colon-separated device user information:

1. Field Username

2. Field of Password

• In this sector, a 'x' indicates that the encrypted password is stored in the file /etc/shadow.

3. Amount of User ID (UID)

4. Community ID number of the user (GID)

5. Fields of additional details, such as the full user or comment name (GECOS)

6. Absolute direction of the home directory of users

7. The user's login shell

Pi Safe Shutdown

Pulling your Raspberry Pi’s power will lead to picture corruption and other problems that can damage your Pi! We will build a small push button in this article that will act as an option for 'Safe-Shutdown'. Using the GPIO pins and some jumper wires, we will link it to our Raspberry Pi, and with a few lines of code, we will have our own power switch!

Next, we're going to look at how to wire a button to the Pi GPIO connector in a easy way. Then we are going to write a python script that will securely shut down the Pi. Setting up the Pi so that the button will work all the time will be the final step. Let's get rolling!

You will need:

• Raspberry Pi B+ (Any Pi will work, just make sure the GPIO pins are checked)

• Tactile switches

• Jumper Wire Packs for Female / Male Extensions

• Solderless Boards of Bread

The Circuit

We're going to wire the button to GPIO Pin 26 (yellow wire) and ground (green wire) to do this. This configuration is called an Active Low button, which means that it will have no voltage or low logic when the button is pressed. On its GPIO pins, the Pi has pull-up resistors, so active low wiring means we do not need to install an external resistor.

With the wiring here, make sure you are extremely careful, as shortening the wrong pins together will destroy your Pi. This is why I've got a Pi-shaped coaster now.

The three external libraries we will use:

The gpiozero library button module offers quick access to the programming of the GPIO on the Pi. It is the library of time, so we can wait in human time.

The OS library gives us the power to shut down the Pi (you can also run any terminal commands using this library!).

We first build an object with a button that enables us to interact with the button. In our case, we'll give this feature the GPIO number input that we connected the button to 26. This feature assumes active low buttons by nature, so we do not need to alter anything else.

We want this software to run all the time, so that it will still work when we click the button after a week-long retro gaming session. To do this, we build a true loop that will run indefinitely.

Inside the loop, if statements first detect a button (we have two), then activate the code to wait for a second, then check to see if the button is still holding down.

The last line tells the loop to wait a second until the button is tested again, so we're not in a hurry, so we can wait for the buttons. Make sure that you include this wait without python running this script as quickly as possible and putting an unwanted load on the CPU.

Chapter Four

Setting Up the Troubleshooting

From experience, each model of the Raspberry PI (and operating system) has its own peculiar problems and corrections, so I will presume that you are using a Raspberry Pi 3 and running the latest version of the Raspbian stretch OS to keep things reasonably normal for this chapter.

All set? Let's dive inside!

1. Issues with Boot

This may be attributed to quite a variety of variables. The Red LED (power LED) is usually indicated by "ON" while the green (activity LED) is either "OFF" or permanently "on."

The Solution:

Computer operation is reflected by the green light on the Raspberry Pi, so when it is blinking at intervals, it indicates the Pi is running. Therefore, the first place you can search whether it's off or not flickering is where the Pi's program is housed: the slot for the SD card. Ensure the proper insertion of the SD card. If things don't improve, search the SD card to make sure the OS has flashed correctly and the files on it aren't corrupted.

I typically just format the SD card in situations like this, and flash it with the OS again. Upload it into a PC and copy it out before formatting if you have data that you would like to retain on the SD card.

2. NOOBS OS Stuck on the splash show

This is one of the key reasons why I am not a huge fan of the NOOBS app for Raspberry Pi. The Raspberry Pi's boot operation gets stuck on the splash screen when this error occurs.

The Solution:

This can be solved by formatting the SD card and ensuring that it is copied to the right Noob files. Try another SD card or the same SD card on a different Raspberry Pi if this doesn't work. If the problem persists, installing Raspbian stretch or some other distro might save you more time.

3. Could not access the Pi over SSH

This is more of a safety feature, rather than a mistake, built into the Raspberry Pi stretch OS. For a Raspberry Pi running a new install of the Raspbian stretch, contact over SSH is disabled.

The Solution:

Under the Raspberry Pi settings, you need to enable SSH communication with the PI connected to the monitor, go to preferences, and then select Raspberry Pi settings.

Select the radio button named Activated in front of SSH when the configuration window opens.

If you're running a Pi in headless mode, you'll need to delete the SD card, insert it into your PC, then build an empty file called SSH, copy it to your SD card, and then insert the SD card back into your Raspberry Pi. You should be able to access your PI via SSH now.

4. The board departs intermittently.

This includes the rebooting of the Raspberry Pi itself at random intervals and often the power LED is off while the board is on.

The Solution:

This is basically a problem of control. For example, the Raspberry Pi 3 needs a 5V, 2.5A power supply to work properly, so anything short of that is likely to affect its efficiency. While I worked on the PI with 5V 1.5A, output depends on the task that the Pi is set to perform. Essentially, check to make sure you give the Pi enough juice to remain awesome when this happens.

5. USB Not Working

This error describes situations where USB devices attached to the Raspberry Pi are either not recognized or not functioning properly by the Pi, as the tag implies.

The Solution:

There could be a bunch of stuff wrong here:

1. The Raspberry Pi cannot get enough power and the USB system is therefore unable to power it. Ensure that your Pi is powered properly.

2. The USB interface may be defective. To make sure it works right, test it with your PC or some other device.

3. Before turning it on, attach your computer to the Pi. Although this probably shouldn't be a problem, the Pi will need to do some initialization for USB devices such as your keyboard and mouse, particularly if you are connecting it to the Pi for the first time. Weird solution, but occasionally works.

4. There are occasions when the system connects very well to your Pi, but for the specific activity you are trying to use it for, it is simply not usable. To confirm if this is the case, execute the order from the terminal;

LSUSB-T-t

This should send you a list of your pi-connected USB devices.

5. Issues with drivers. Ensure that the USB interface is compatible with the operating system running on the Raspberry Pi based on Linux. Here, Elinux.org has several USB devices that are Raspberry Pi compatible. The list is well ordered, and it should help you decide whether your computer is compatible.

6. Update the Pi. Before starting any new project on the Raspberry Pi, it is necessary to run an update or upgrade. The justification for this is to guarantee that you have compatible and new apps running on your Pi. At times, this may be an explanation for hardware not responding as it should to specific commands.

7. Keyboard Show Character Errors. When the key shown on the screen varies from the key pressed on the keyboard, the # key in particular. This error happens most of the time due to the default UK keyboard configuration of the NOOBS and Raspbian applications.

The Solution:

You'll have to change the setup to that of your own keyboard or language to correct this. This can be accomplished by going to the configuration menu of the Raspberry pi, selecting the keyboard setup menu under the Internationalization menu, and scrolling down to pick the keyboard layout that suits your keyboard's country of origin / language.

Go to Preferences and choose the mouse and keyboard settings if you are operating with a display.

Select a keyboard layout and then select your keyboard layout from the new window.

6. Not working with HDMI-based monitor, Raspberry Pi

So you could link via ssh to your Pi, but you can't seem to get it to function with an HDMI display? There are two things you can do:

• Do an inspection of your HDMI cable

• Attach the display to the Pi and, before powering up your Raspberry Pi, select the correct mode (HDMI or VGA) on the monitor. Ensure your screen is switched on before powering the Pi.

7. Raspberry Pi Non-working camera

Most people expect the Raspberry Pi camera to function right out of the box, and I have had to suggest this easy solution so much that it probably deserves a spot on this list.

It must be allowed on the Pi to be able to use the Pi camera. However, this should be accomplished after updating and upgrading the Pi.

To do this, start by running the commands to update and upgrade:

Apt-get Sudo update

Sudo apt-get Update Upgrade

Pursued by:

Sudo raspi-config settings

This will open the configuration window for the Raspberry Pi shown below. Scroll down, pick your camera, and then choose Allow. Go to Preferences and choose Raspberry Pi Configuration if you are operating with a monitor. Check the Activated Radio Button in front of the camera when the configuration window opens. Reboot the Pi with it done. You should be able to receive your feeds and images now. If you are still unable to access the camera, try a different connector strip and camera.

Read more on how to use the Raspberry Pi Pi Camera and the Raspberry Pi USB Camera.

8. Blank or Black Capture with Raspberry Pi Camera

This describes a situation where a photo will appear to have been taken by the Raspberry Pi but the image appears blacked out.

The Solution:

As described above, due to the software update, several errors on the Raspberry Pi will be due and this error is not different. The first fix you can attempt is to download and upgrade your Raspberry Pi to get the new updates and improvements. After updating to effect improvements, reboot.

9. Ethernet Off on WiFi

For example, Wi-Fi access is disabled when an Ethernet cable is linked to the Raspberry Pi. This was presumably introduced to disable routing between the Wi-Fi and the Ethernet port as a security feature for Pi. A config file called ifplugd, which must be disabled if you want to use Wi-Fi and Ethernet at the same time, handles this operation.

To do this, run:

Sudo Update-Disable RC Networking

Or

Sudo apt-get purge, ifplugdd-get purge

You should be able to use both network options at the same time now, but do not overlook the security vulnerability this might make, as the Pi would behave like a router in this mode.

10. Hangs the Pi Attempting to Change Password

This applies to a situation where the Pi is either hanging or rejected (i.e. new password not registered) by an attempt to alter the password of the Raspberry Pi.

The Solution:

This is one of the indications suggesting that the Raspberry Pi may not get enough juice from the attached power supply or that the power supply performance fluctuates much. It's as easy to fix this as switching the power supply to your Raspberry Pi or plugging it to another port on your PC.

This is obviously not an exhaustive list of mistakes that one could find when working with the Raspberry Pi. This might give you a head start on the shared unique mistake and even related mistakes. Check our Raspberry Pi Projects section to get started using Raspberry Pi with cool applications.

Have you faced a mistake that has taken days to resolve? Feel free to share them via the comment section.

Chapter Five

Configuring The Network

This book will demonstrate how to easily configure a static IP address for the Raspberry Pi Ethernet port. This makes it far easier to remotely log into it because you will already know what your Pi's IP address is. For PC / Windows users, or anyone not familiar with Linux, these are really simple instructions.

The new PIXEL edition of Raspian has been revised (3/3/2017) by this Instructable. The configuration of the network has been changed to use the dhcpcd.config vs interfaces file.

Hardware:

• Pi Raspberry

• Switch network

• Cables from Ethernet

• Optional: Wireless USB dongle for Wi-Pi WiFi

Step 1: Check the existing network configuration. Click settings for Pi Network. From the prompt or LXTerminal: instruction, form the 'ifconfig' command. The current network settings will be shown with this instruction.

Step 2: Existing Network Configuration Backup. If you are new to Linux, it is a good idea to back up the dhcpdc.conf file:

/etc / dhcpcd.conf sudo cp /etc / dhcdcp.backup

This will allow you to roll back any modifications you make.

Step 3: Change Network Configuration

Modify Settings for Network

You must edit the dhcpcd.conf file to set up a static IP address in order to edit the network settings. You may use the following command to load the file into the file update editor:

Nano /etc / dhcpcd.conf sudo

To set an Ethernet port (eth0) to a static IP address, place these lines at the top of the file:

The eth0 interface

Static IP address=10.11.44.124/244=10.11.44.124/244

10.11.44.14.14 static routers= static routers

Static server domain name=172.16.33.855

Set the address (IP address) to the IP address that you want the Raspberry Pi to carry. Configure the value of the router to the gateway address. If available, set your name servers to domain name servers. Use ctrl x once the file has been changed to save and exit.

Step 4: Launch the Raspberry Pi again. Restart the Raspberry Pi. Once you have modified the dhcpcd file, you must restart the Raspberry Pi to make the changes successful.

Step 5: Verify the Configuration of the New Network. Perform a Network Configuration Test. Use the "ping" command to check that the Raspberry Pi is on the network and that the network is still talking to another device.

If you find it difficult to ping other machines on the network, try the following:

1. Confirm that the Raspberry Pi and the network switch are securely linked to the Ethernet cable.

2. Confirm the correctness of the IP address, mask, and gateway.

3. If a Windows machine is pinged, often the security setting prevents a ping request from responding.

Networking (Wired)

You must spend less time on social media if you want to write code, and spend more time breaking things or leaving your comfort zone. Here’s a quick shopping list to get connected to your laptop with your Raspberry Pi:

• Two 1 foot Ethernet link cables. (These are called "repair cables." If one splits, always buy them in pairs.)

• A Crossover Converter. (In this shot, I don't know why it is red. The one I got was black. You will find it in that color, I 'm sure.)

• USB / Ethernet Realtek adapter. (CableMatters sells this, but it appears in ipconfig as "Realtek USB GbE Family Controller." Plus, if you need to plug in your cursor, there are several additional USB ports.)

Since Medium has difficulty embedding images into lists, after this numbered list, I'll need to post my screenshots.

1. Using a straight Ethernet Cable, link your Raspberry Pi using the PC Ethernet Port. It ought to be fairly obvious. Connect the USB-Ethernet Adapter to the Crossover Adapter, then connect the adapter's Ethernet port to the one on the Pi. To make sure things are related, make sure you hear the "click".

2. Open Settings for Windows. Click the Windows menu as we're using Windows 10, and then pick the Settings gear icon.

3. Open Sharing Center and Network. To get there, click on "Network & Internet" in Settings. You can see the "Ethernet" tab on the left side if you have your Ethernet plugged in. Click on it. There should be a section on the right side called "Connected Settings" with a link that says "Network and Sharing Hub." Click it.

4. Modify the settings for sharing Wi-Fi. Wait, why am I playing with the Wi-Fi settings? (Seriously.) I don't want to touch it, I might break it! That's what I do, but, contrary to what it sounds, for Internet Link Sharing (ICS) to work, you need to change your Wi-Fi sharing settings. I ran into all kinds of things online where people were moaning about how their Ethernet settings had changed, but nothing happened. This is because our Wi-Fi sharing settings need to be modified so that it shares its Internet connection with Ethernet. As terrifying as that sounds, that's how it is done. Click the blue text on the "Network and Sharing Hub" where you see the Connections field for "Wi-Fi". (It may have an attachment to what network you are linked to.) This should open the "Wi-Fi Status" window.

5. Wi-Fi Properties Available. Click the 'Properties' button in the 'Wi-Fi Status' window. This should open the window for "Wi-Fi Assets."

6. Modify the settings for the ICS. (Note: Just to reiterate what I said in step 4, if you did something mentioned in that step to your Ethernet settings, undo it.) Against common wisdom, we're going to have to click on a few items that should be even more frightening. Click the "Sharing" tab in the "Wi-Fi Properties" window. Check the box for "Allow other network users to connect via the Internet link of this device." Pick the Ethernet link from the drop-down menu underneath it. You can call your Ethernet link something else, as is the case where mine is called "Ethernet 2." Alternatively, check the "Allow other network users to monitor or disable a shared Internet link" box. To close the 'Wi-Fi Assets' window, press 'OK.' Click "Close" in the "Wi-Fi Status" window.

7. Check your link properties on Ethernet. In the "Network and Sharing Center" window, select "Ethernet" as the value this time is on the Connections field. (Again, it could be called something else, but it should be below the "Wi-Fi" connections we messed with earlier.) This should open a window called "Ethernet Status" or something similar. Click the button for Properties. “Ethernet Properties" (or anything similar) should open this up.

8. Test your Settings for IPv4. With this move, Cisco geeks might feel comfortable knowing what it does. Find "Internet Protocol Version 4 (TCP / IPv4)" in the "Ethernet Resources" window in the "This link uses the following things" section. If not, you will need to restart your machine to activate it. Make sure it is tested. Double-click on it or pick it and click the "Properties" button to open the "Internet Protocol Version 4 (TCP / IPv4) Properties" window. (I hope you don't need to do that.) If we had not done either of the previous measures, the radio button "Automatically get an IP address" would have been tested, as would the option "Automatically get a DNS server address”. Nevertheless, we now see that "Use the following IP address" is selected, and all the "IP address", "Subnet Mask", and "Normal Gateway" fields are allowed, while "Get automatic DNS server address" is disabled in the DNS settings, and "Use the following DNS server addresses" is selected. The field "IP Address" should contain 192.168.137.1 and the field "Subnet Mask" should contain 255.255.255.0.0. The “default portal" ought to be blank. Meanwhile, unless you want to change this to 1.1.1.1 (Cloudflare's public DNS server) and 8.8.8.8 (Google's public DNS server), DNS address fields will remain null. We can click 'OK' in the 'Ethernet Properties' window and then click “Close” in the “Ethernet Status” window. Alternatively, we could open the Command Prompt (cmd) and type ipconfig / all to check the details. We can also ping our link through ping 192.168.137.1 or ping the Pi via its hostname, such as ping raspberrypi.local, assuming raspberrypi is the hostname of your Pi (found using sudo hostname).

9. Into your Pi with SSH. This is usually achieved using PuTTY. I'm a fan of using Chocolatey to install software that is open source on Windows, though. Install Chocolatey, and then use Chocolatey in Powershell to install Putty. I was actually hoping to write about how to use SSH later this week in a post. I'll post a connection to that later when that's done. You should be able to SSH into your Pi (ssh pi@raspberry.local), then do stuff like ping google (ping google.com). It's more complex than that, but this is something I want to tie up.

Wireless Networking

For setting up wireless connections with the Raspberry Pi Desktop on Raspberry Pi OS, a GUI is given. You can set up wireless networks from the command line if you do not use the Raspberry Pi Desktop.

Wireless connections can be made at the right-hand end of the menu bar via the network icon. If you use a Pi with built-in wireless networking, or if a wireless dongle is plugged in, a list of available wireless networks will be shown by left-clicking this icon, as shown below. The message 'No APs detected-scanning ...' will be shown if no networks are found. Keep the menu open, wait a few seconds, and your network should be found.

Note that wireless networking is disabled on the Pi 3B+, which follows the 5 G protocol for regulatory purposes, before the country code has been set. Open the Raspberry Pi Configuration program from the Preferences menu to set the country code, pick Localization, and then set the necessary code.

Wi-Fi2

The right-hand icons indicate whether a network is secure and provide an indication of its signal power. Please click the network to which you want to connect. A dialog box prompts you to enter the network key if it is secure:

Please enter a key and click OK, then wait a few seconds. To indicate that a connection is being made, the network icon will flash momentarily. The icon will stop blinking when it is ready and display the strength of the signal.

Chapter Six

Tool for Raspberry Pi Configuration

When it comes to having access to the configuration tool, these few steps are straightforward and the most important part of this tutorial:

1. There is an icon in the menu bar for either SSH on the Raspberry Pi or accessing the terminal from inside the Raspbian desktop.

2. Type the command that follows:

Raspi-config sudo

You will now have access to the Raspi Config tool, so let's go through each item's functionality now.

User Account Update

It is very easy to find out about the Raspberry Pi default login through a Google search. You will probably only guess the username and password, so if you don't want anyone to access your Pi, it's necessary to change the password.

Use this method to change the password for the user pi, and I highly recommend that you do so. Raspberry is the default pi user password, so it's pretty easy to guess. Using this app, you can not alter any other user's passwords.

Options for the Network

This menu includes options relevant to the Raspberry Pi's network capabilities.

Hostname: This option allows the network name of the Raspberry Pi to be set. It’s convenient if you have several Raspberry Pis and want to make a distinction between them.

Wi-Fi: You can use this method to set the Wifi SSID and passphrase. If you have found setting up WiFi manually a little frustrating from the command line, this option is super handy.

Names of the network interface: This option enables predictable network interface names to be allowed or disabled. By default, this option is off and should be turned on only if you need it. In our WiFi guide, there is more information about this alternative.

Options for Booting

In the Raspi configuration tool, the third item specifies how your Pi will boot. The option is to boot the Pi, which is not suitable for most users, into the desktop. (Command line defaults to Raspbian lite)

Desktop / CLI: This choice enables you to choose whether to boot the Raspberry Pi or the command line on your desktop.

Wait for a network connection at boot: If you want your Pi to wait for a network connection at boot, turn on this function.

Splash Screen: Choose whether to view a graphical splash screen or to boot text by default. If you're searching for mistakes, text can be helpful, or you can link to the error log.

Choices for Internationalisation

If you need to change the settings of your Raspberry Pi keyboard layout, such as your locale, time zone or update.

Change Locale: For example, en au. UTF8 UTF8 or en gb. UTF-8 UTF-8 will change your locale here.

Change Time zone: If you wish to set a Raspberry Pi time zone, use this option. This will allow you to update the time zone and set it so that it is the right time for your place. To change your time zone correctly, simply follow the prompts.

Change Keyboard Layout: It can take a while for this one to load all the available keyboard layouts. You can pick the correct keyboard layout once it's loaded. Bear in mind that the UK keyboard is a different style from the US layout.

WiFi Country Change: You can update this, so it's the same as the country in which you actually live. Most nations have numerous legal networks that you can use for WiFi.

Options for Interfacing

This choice allows the number of interface functions available on the Raspberry Pi to be disabled or enabled differently.

Enable Camera

If you want to use the Raspberry Pi camera module, you will need to activate it. Go in and pick the option to trigger it.

If you're planning on following my Raspberry Pi Time-Lapse tutorial, you'll need the camera module activated.

SSH

This choice allows SSH access to your PI to be disabled or activated. Enabling this would allow you to access your Pi from a remote location, so it is best to keep it disabled if you don't intend on ever using SSH.

If you intend to use the Raspberry Pi on a public network, make sure that you have changed the pi user’s password so that it is not raspberry .

VNC

Later versions of Raspbian have VNC preinstalled, so if you want to use RealVNC to connect to the Raspberry Pi, make sure that you switch it on.

SPI

It allows you to disable or activate the kernel module SPI (Serial Peripheral Interface) required by PiFace. This allows a four-wire serial connection to be connected, so you have sensors, memory, and peripherals.

The I2C

Allows the I2C kernel module to be disabled or enabled, so that I2C devices can be attached.

Serial Sequence

You can disable or allow shell and kernel messages from the serial link with this option.

1-The Cable

If you plan on using something like the DS18B20 temperature sensor or other devices that make use of the 1-wire protocol, switch on the 1-wire interface.

GPIO Remote

This choice allows you to control the GPIO pins remotely and should only be turned on if you know that it needs to be switched on.

Overclocking

To get more strength out of it, you can overclock your Raspberry Pi. The default settings for the Raspberry Pi overclock are set to off, and the CPU sits at 700 MHz. You can, however, overclock it up to 1000 MHz by using this gadget. Depending on the Raspberry Pi version you have, these values can differ.

You should also remember that overclocking will cause greater instability and shorten your Pi 's lifespan as well. Later models of the Raspberry Pi, such as the Raspberry Pi 3, also have it disabled.

Advanced Options Section

The last batch of options in the Raspi-Config tool are advanced options, and these are a little more active. If you do more beyond the fundamentals of the Pi, you probably don't need to change these.

Expand Filesystem to expand

Chapter Seven

Advanced Raspberry Pi Configuration

When you install Raspbian, the 'RasPi Config' tool is the first thing you'll see. It allows the device to be configured, which would otherwise be trickier in the Linux world.

Why does the tool 'RasPi Config' come first?

Tasks such as setting the date and time or regional settings for your keyboard are frequently performed without dialogs in a command-line interface, no extra support for a demanding novice.

For the Pi and Raspbian itself, there are several other details, such as: the ability to easily activate over-scan for your TV; change the memory split to the computer / graphics card or even overclock your device to make it a little faster; allow remote SSH access to the system; among other things, avoid booting the system into the desktop environment.

Mastering the tool for configuration

1. Open the tool with raspi-config

Double-click your desktop's LXTerminal icon. This will open the prompt command, where you can run the configuration tool. You will need to execute an order to do this:

Raspi-config sudo

You can not necessarily see it being typed when asked for your password. If you have entered a password and pressed Enter to submit it, you will be shown the configuration page.

2. Expand the framework for root files

By default, the Raspbian root file system will be 2 GB, so that as many different SD cards as possible can match the image provided for it.

The 'expand roots' option would allow the operating system to use all available space if your card is larger. Upon using this option, the command will immediately be executed. It can take some time to run. To see the modifications, reboot your machine.

3. Configure the location

Locale is the language and regional settings used by your Pi, but this normally has little influence on what you see. It is also responsible for any default currency settings, etc., so if incorrect at a later time, it may be irritating. You will be taken over by a wizard after selecting the option. Until building more, use the arrow keys to check the constructed locale. You will be taken to the tzdata screen by the time zone where you can change it.

4. Overclock your Pi

You can adjust your Pi's clock velocity and voltage to many different presets. It can cause instability to set the clock speed and voltage at higher rates than the specification, so do it in small increments and ensure good airflow around your Pi.

Run this wizard again if you see any apparent instability and set the clock speed back down to something slightly lower—repeat until your device is fully stable. After making this adjustment, it is also recommended to reboot your system. Keep the Shift key to disable overclocking temporarily.

5. Modify the split memory

Changing the Pi 's memory split enables you to assign a greater amount of memory to either the device or the graphics processor. It must have either 16/32/64/128/256 as the value you give it.

Suggested Recommendations:

• 32 MB GPU memory where video and 3D rendering are not needed for simple distro use.

• 64 MB GPU memory that includes video playback or has 3D effects available for desktop use.

• 128 MB GPU memory for graphical applications and games that play 3D rendered games or do comprehensive multimedia.

6. Modify boot actions

The Raspbian distro will boot into a command line interface by default, where you must first log in as 'pi'. You must give the machine a command to let it know that that's what you want to do if you want to run a window manager.

This is not suitable for a lot of people, because command lines scare them. There's an option to start the window manager automatically on boot, because of this. To allow this behaviour by default, set this choice to 'Yes'. Obviously, this can be reversed at any time to return to a text-based login where you have to manually start:

Startxx

7. Update raspi-config

From time to time, the raspi-config tool receives updates. Generally speaking, this is either to add more functionality or patch minor bugs. Until you start adjusting some device settings, it's not a bad idea to run the updater while using the tool. Although it is much more likely that it will be modified to look better or do more stuff, it is not unlikely that there may be miscellaneous bug fixes hidden inside that might cause you to worry otherwise.

Note, though, you'll need an active internet connection while you're trying to update your copy of the raspi-config tool. Often, always try to make sure that the new update is available to you.

PART II:

BUILDING A MEDIA CENTRE OR PRODUCTIVITY MACHINE

Chapter Eight

The Pi: A Home Theatre Pc

We love Raspberry Pi because of how it helps a new generation of kids learn to code, how it has contributed to an influx of new manufacturers of all ages, and how easy it is to turn any TV into a smart TV.

Though we still have a few Raspberry Pi computers at hand to make robots and cooking devices, or just to code a Scratch game, a TV is always powered by at least one in the building. It's time to totally update our media centre to become a 4K-playing powerhouse with the arrival of the super-powered Raspberry Pi 4.

Get the relevant hardware

Only Raspberry Pi 4 can perform at 4K, so when deciding which Raspberry Pi to select, it is important to note this.

Since it was published in 2012, Raspberry Pi has been a great option for home media centers because it is affordable and backed by an active community. Now that 4K content is quickly becoming the latest digital media standard, the demand for 4K streaming supporting devices is increasing, and luckily, Raspberry Pi 4 can handle this easily! Three Raspberry Pi 4 models are available, distinguished by the amount of RAM they have: 1 GB, 2 GB, or 4 GB. So, which should go for? Both versions performed just fine in our tests, so go for the one you can afford.

Cases with Raspberry Pi

Pi 4 Flirc Raspberry case

The Flirc case for Raspberry Pi 4 is a fantastic option and looks great as part of any home media entertainment system, made of aluminum and intended to be its own heatsink. In every house entertainment device, this will look at home.

Raspberry Pi 4 official case (in black and grey)

The official Raspberry Pi 4 case, particularly the black and grey version, is always a good choice as it blends well into any home entertainment setup. You can also hack the case to hold a tiny fan for extra cooling if you're feeling adventurous.

Raspberry Pi 4 Aluminium Heatsink Case

This is a giant heatsink, another case made of aluminum, which helps keep your Raspberry Pi 4 cool while in use. It has a choice of three colors: black, gold, and gunmetal grey, so if you want something a little different, it's a great option.

Raspberry Pi add-ons optional

External Maxtor 2 TB USB 3.0 HDD

4K content can be very large and, if you have a large set, your storage will run out quickly. It would be extremely convenient to have an external hard drive linked directly to your Raspberry Pi using the faster USB 3.0 link to prevent any streaming lag.

The SHIM Raspberry Pi Fan

The added power of Raspberry Pi 4 means things can get very hot, particularly when 4 K media files are decoded, so getting a fan can really help keep things cool. Due to its size and noise (no excessive humming here), Pimoroni 's Fan SHIM is perfect. A Python script is open, but with the power supplied by Raspberry Pi's GPIO pins, it also "only works."

HAT Raspberry Pi TV

To allow the DVR feature in Kodi to watch live TV, you can add a Raspberry Pi TV HAT to your 4K media center if you feel adventurous. For the best reception, you may want to attach your principal aerial. This will give your 4K media centre a great finishing touch.

Rii i8 + Wireless Mini Keyboard

If your TV does not support HDMI-CEC, which allows you to monitor Kodi by using your TV remote, then this nifty wireless keyboard is extremely helpful. Plug in your Raspberry Pi with the USB dongle, switch on the keyboard, and that is it. You've got to navigate with a mini keyboard and mouse now.

Chapter Nine

The Pi as A Productivity Machine

The Raspberry Pi’s versatility as a low-power, general-purpose desktop computer makes it a good choice. While it can never produce the same output level as a typical desktop or laptop, its low cost and environmentally friendly power usage helps to compensate for any issues with slower performance.

The Raspbian operating system includes the popular Libre Office productivity suite as a standard, available from the Raspberry Pi website. This equals all the resources that you would expect to find in a commercial product such as Microsoft Office: word processor, spreadsheet, database, presentation tool, and even diagram or mathematical formula development applications. Alternatively, via the web browser, you will use much of the same cloud-based applications as you can use on any other device.

The Pi can be used as a day-to-day computer for office and school work, using any of the methods mentioned in this chapter, locally installed applications or cloud-based services, while not damaging its usability as a forum for programming and experimentation.

A tip

It is a smart idea to use more of the memory for general-purpose use and less for the graphics processor if you intend to use the Pi as a pure productivity computer. Refer to Chapter 6, 'The Raspberry Pi Configuration Tool,' to find out how to modify this division.

A broad range of options are now provided by cloud computing services, from the basics of storage, networking, and processing capacity to natural language processing and artificial intelligence and traditional office applications. The cloud can now provide almost any service that doesn't need you to be physically close to the computer hardware you are using.

Cloud-Based Applications Use

What are some cloud computing examples?

A large range of services are underpinned by cloud computing. This includes customer services such as Gmail or the cloud backup of images on your mobile, but also services that allow large corporations to host all their data and operate all their cloud apps. To run its video streaming service and its other business systems, Netflix depends on cloud storage resources, as well as a variety of other organizations.

For many applications, cloud computing is becoming the default option: software vendors are gradually selling their apps over the internet as services rather than standalone products as they attempt to move to a subscription model. Cloud computing, however, has a possible drawback, in that it may also add additional costs and new risks for businesses using it.

Why is it called computing in the cloud?

A fundamental idea behind cloud computing is that the position of the service is completely irrelevant to the customer and many of the specifics, such as the hardware or operating system on which it runs. With this in mind, the metaphor of the cloud was taken from the old schematics of the telecommunications network, in which the public telephone network (and later the internet) was often depicted as a cloud to suggest that it didn't matter — it was just a cloud of stuff. This, of course, is an over-simplification; the position of their facilities and data remains a key problem for many consumers.

What is the history of computing on the cloud?

Since the early 2000s, cloud computing as a word has been around, but the idea of computing-as-a-service has been around for much, much longer—as far back as the 1960s, when computer offices would enable businesses to rent time on a mainframe instead of purchasing one themselves.

These 'time-sharing' services were largely overtaken by the advent of the PC, which made it much more accessible to own a computer, and then in turn by the rise of corporate data centers where massive quantities of data can be processed by businesses.

But again and again, in the application service providers, utility computing, and grid computing of the late 1990s and early 2000s, the idea of renting access to computing power has resurfaced. Cloud computing preceded this, which really took hold with the advent of applications such as Amazon Web Services as a service and hyperscale cloud computing providers.

How critical is the cloud?

According to research from IDC, building the infrastructure to sustain cloud computing now accounts for more than a third of all IT spending worldwide. Meanwhile, as computing workloads continue to migrate to the cloud, spending on conventional, in-house IT continues to slide, whether that be public cloud services provided by providers or private clouds created by companies themselves.

PART III:

PROGRAMMING THE PI

Chapter Ten

An Introduction to Scratch

Scratch is based on a graphical user interface that makes it unnecessary for complex language syntax or general code-typing. The ability to help provide beginners with their first programming experience is first and foremost. This is why providing a range of functions still takes precedence over the factor of simple usability. However, despite these limitations, as the following list indicates, Scratch has some of the essential properties of conventional programming paradigms. There are:

Visual: All Scratch elements are represented, for example, by an understandable graphical representation of program commands via image blocks. In addition, they can be inserted and placed together conveniently via drag-and - drop.

Object-orientated: There are neither classes nor an inheritance scheme for Scratch programming. However, Scratch shows characteristics of the object-oriented programming concept with elements such as data encapsulation (controlled access to data through specified interfaces) or polymorphism (objects may assume different data types).

Imperative: The imperative programming paradigm is accompanied by some of the scripts that are made available to you to program from Scratch. Instruction sequences, therefore, determine in which series what acts are to be performed.

Event-oriented : As soon as the event specified in its header block occurs, any script that you use in a Scratch project begins. The loading of a project can also be postponed until the occurrence of a particular event by using a "Wait Until" block.

Parallelism-supporting: From the beginning, Scratch advocates the distribution of computer programs into individual sub-components that separate the concept of parallel programming.

There are the following characteristics concealed behind other available menu items:

Develop: The core component of the Scratch web project is the graphical development environment that you launch via the "Development" tab. You program all of your Scratch applications directly into the browser with the help of this web editor.

Explore: In this folder, you can call up other users' projects. You can not only replay but also display all of the Scratch programming by doing so. In a "Studio", designs of a similar nature merge.

Ideas: The 'Ideas' section gives you access to numerous tutorials and guides that help you create your own projects, particularly when it comes to brainstorming. A redirect link for downloading the Scratch software (Windows 10, macOS, ChromeOS, Android) can also be found here, enabling you to program without needing an active Internet connection.

About Scratch: If you click on the 'About Scratch' menu item, you will be led to the general Scratch project details tab. You can find links to help information materials for parents and teachers, as well as tips and a FAQ section, among other items.

Understanding the Scratch Editor: Scratch coding functions like this

Scratch’s development environment is reminiscent of a building block for the homepage, which is not so surprising given the block-nature of the script available. You can also add costumes and sounds to a project in addition to these scripts, which make up most of the functional components, which you can then manage or execute via script. The range of scripts can be expanded by clicking on "Add Extension" with, for example, a pencil, video recording code or a text-to - speech feature.

Tip

Scratch gives you a range of costumes, sounds, and scripts that you can instantly implement into your projects. Alternatively, if the required element is not included in the available content, you can also import or record your own images or sounds. Your own scripts can be produced as well.

Costumes: Bring figures and objects to life

A game, video or animation, or maybe even a basic comic, whatever you would like to program from Scratch: figures and other items are the central building blocks for your plot. You can pick and incorporate any number of graphics into your project under the 'Costumes' tab. Choose from the image options available, draw objects by hand, or import graphics stored locally. If your computer has a camera, you also have the option of taking a picture.

Scratch: Menu for Costume Collection

Later, objects or figures in various poses give you the option of creating sequences of motion.

You can then customize it if you have chosen a costume. To do this, select the desired object (where you can delete it at any time by clicking the Recycle Bin icon) in the left-hand menu and use the available editor tools to change colors, delete unique information with an eraser, add text or warp the object. It is also possible to transform the graphic to a raster or vector graphic. You can name the costume in the 'Costume' sector, which the respective scripts later need as reference values.

Scratch: Editor for costumes

We have changed the appearance of the figure in this example Scratch tutorial through its fill color.

Notice the "Choose a Background" button on the lower right edge of the display. With this choice, you decide the background picture of your project. Scratch ha their own selection of stock images, or you can import your own images, or even paint your own background.

Scratch-Tutorial: Background picture figure

You can shift or change the context in Scratch coding using scripts, just as with objects and figures.

Sounds and songs in the background

The right soundtrack is just as important as objects and figures for many artistic ventures. You introduce and control all sounds through the menu of the same name while programming with Scratch. On the one side, as with the graphic elements, you have a variety of pre-created Scratch sounds available to you for this purpose, which you can access through "Choose Sound." On the other hand, there is an opportunity to import or record sounds, provided you have a microphone attached.

Menu to record sounds using Scratch

As soon as you press the record button, the recording of a new Scratch sound begins.

In the left-side menu, inserted sounds can be picked by clicking on the corresponding thumbnail and then modified in different ways. You may, for example, cut out selected sequences, change the volume, or increase or decrease the play speed, among other things. Since sounds are inserted through scripts into the Scratch project, each sound often needs a unique name that you can assign in the "Sound" area.

Scratch-Tutorial: Window to edit a sample sound

Pick these by keeping the left mouse button from the desired starting point and dragging the selection screen to the desired endpoint if you want to take out sequences or just edit selected pieces.

Scripts: the nature of coding with Scratch

It is important to practice handling the Scratch scripts in order to program with Scratch successfully. The actual code behind these scripts is created automatically, regardless of whether it's an event, method, operator or a variable, as soon as you drag the available blocks into your project. You should concentrate on integrating individual values and the respective graphic and sound components into the respective scripts.

There are precise explanations for all pre-created scripts that illustrate their roles. If you want your project to implement a script, simply drag the respective block into the middle editor window, as the script building models are referred to in Scratch. The values or options to be identified can be displayed directly on the block and can be typed or selected directly there as well. If such a new script applies directly to an already incorporated script, simply append the corresponding block as you would if a puzzle were being placed together.

Practice Scratch: Display options and incorporate scripts

You can revisit the latest version of your Scratch project at any time in the preview window and playback implemented sequences for testing purposes.

Note

The complexity of Scratch learning lies not in having to internalize syntactic rules or a recording format, but rather in knowing the separate scripts’ roles to execute them optimally and merge them.

Programming with Scratch: an example of a simple project

Since the most important components of this programming framework were introduced in the previous section of this Scratch tutorial, Scratch's possibilities should finally be illustrated using a particular example.

In the first step, by moving the mouse over the backdrop icon at the lower edge of the screen and clicking on "Choose Backdrop," we are looking for a backdrop for our project. We have selected the theme "Blue Sky," which we support without any changes:

"Blue Sky" Backdrop of Scratch

We chose the "Blue Sky" Scratch backdrop for our example,

Next, in the project example, we insert a figure. Instead of the "Costume" tab, the "Backdrops" tab can be displayed. Click on the "Choose Figure" button on the bottom right. There are numerous figures with multiple costumes in the Scratch selection with which motion sequences can later be simulated. For example, the "Cat" figure is available in the "cat a" and "cat b" versions, which are played back consecutively, creating the impression that the cat is walking

Note

Custom versions of a figure make it simpler to program from Scratch for a motion sequence.

Scratch tutorial: figure of the "Cat"

You bring them to life with Scratch programming by separate figure costumes or poses.

We want to get to the main point in the last stage of this short example, which is programming from Scratch and making the figure controllable. To insert the following scripts from left to right, for instance, as long as you hold down the "Arrow to the right" key:

Events: If you click the [ ] key

Control: keep on [ ] seconds

Look: turn over to the next costume

Motion: moving one move at a time

Assign the desired key with the event script, in the case of our "Arrow to the right" scratch tutorial. Confirm the buffer between the costume changes via the corresponding "control" script. If you insert the "0.2" value, 0.2 seconds will pass before the figure changes its appearance, which might seem more normal to the motion series. The "look" script ensures that the arrow keys are switched between "cat a" and "cat b" as long as you keep them. The figures often step to the right when the costume is moved using the fourth script from the "Motion" segment. The standard 10 measures have been determined by us.

Software Scratch: description of scripts in a project example

For the purposes of this example, the values used in this Scratch tutorial are selected; smaller or faster costume changes are just as likely as small or larger steps for the figure.

Tip

The outcome of this coding example can be checked directly through the project page of Scratch.

Publish your own project for Scratch coding

You can publish your programming projects at any time on the Scratch platform as soon as you have become a Scratcher and have created your own user account. Click on the 'Publish' button in the upper menu bar to do this.

You can now modify the project title, formulate guidelines, and add feedback or acknowledgments in the launch window. If you shift the slider to the left next to "Commenting on," you also shut down your project's comment feature.

Introductions and establishment (15 minutes)

• Introduce facilitators

• Ensure that each student has access to a computer

• Login o: csv

• Login or password: visitor2

Easy Commands Introduction (15 minutes)

1. Launch Scratch (Start-> All Programs or from the main start menu will also be right there)

2. Note that Scratch is split into multiple parts.

3. On the right is the first one of interest and is called the "level" This is the field in which in our programs we will transfer the "actors."

4. A list of all the existing actors in our programs is below. Note that actors are called "sprites" in our programs and we only have one actor at the moment.

5. For one of the actors, there is a "script" / knowledge area in the centre. This field of knowledge is empty. We will work more on this later,

6. There is a list of commands on the left side that we can send our actor to

7. Explore the blue commands currently in the command list, to begin with. What are they doing?

8. Discuss coordinates, direction, turn degrees, etc. as necessary

9. Note that it is possible to adjust something in the white circle.

Introduction to a Command Sequence (15 minutes)

1. Often there are many acts in a row that we want to do. For instance, we might want to move 30 steps forward and then turn 45 degrees.

2. Drag the necessary blocks to the "scripts" region in the centre, and then double-click to run the entire series.

3. What's happening?

4. Build a series so a square is drawn by your sprite.

5. To actually check what you drew, use the pen.

Introduction (15 minutes) of Iteration

1. Note that you have a certain repetition when you draw a square. A square consists of four sides. You go forward some distance on either side, and then turn 90 degrees.

2. We can use the notion of iteration instead of repeating our code blocks four times.

3. Drag the repeat block out and set the value of it to 4.

4. Put inside of it a move / turn sequence.

5. Click on the block and see what happens (remember that if you want the sprite to draw a trail, you have the pen down)

Chapter Eleven

An Introduction to Python

What is Python? Python is a popular programming language. It was created by Guido van Rossum in 1991. It is used for:

• Web (server-side) growth

• App production

• Mathematics

• Scripting methods

What is Python capable of doing?

• Python can be used to build web applications on a server.

• Python can be used alongside apps to build workflows.

• Python can connect to systems in databases. It can read and edit files as well.

• Python can handle big data and perform complex mathematics.

• Python can be used for rapid prototyping, or for production-ready software creation.

And why Python?

• Python works with Windows, Mac, Linux, Raspberry Pi, etc.

• Python has a plain syntax equivalent to the language of English.

• Python has a syntax that enables developers to write fewer lines of programs than any other programming languages.

• Python runs on an interpreter system, meaning that as soon as it is written, code can be executed. It ensures that prototyping can be very rapid.

• Python can be handled in a procedural way, an object-oriented way or a functional way.

Great to know

The most recent big release of Python is Python 3, which we are going to use in this tutorial. Python 2, however, is still very popular, despite not being updated with anything other than security updates.

Python will be written as a text editor in this tutorial. In an integrated development environment, such as Thonny, Pycharm, Netbeans, or Eclipse, it is possible to write Python, which is particularly useful when handling larger Python file collections.

Python Syntax Compared to other programming languages

Python was developed to be understandable and has some similarities to the mathematically inspired English language. As compared to other programming languages that often use semicolons or parentheses, Python uses new lines to complete a command.

Using whitespace, Python relies on indentation to describe scope, such as the scope of loops, functions, and classes. For this reason, other programming languages also use curly-brackets.

Features of Python programming language

1. Readable: Python is a very readable language.

2. Simple to learn: Python is easy to learn because it is an intuitive and high-level programming language, which means that the language is easy to understand and thus easy to learn.

3. Cross-platform: Python is open and can be run on different operating systems, such as Mac, Windows, Linux, Unix, etc. This makes it a language that is cross-platform and portable.

4. Open Source: Python is a programming language for open source software.

5. Wide standard library: Python comes with a large standard library that has some useful codes and functions that we can use in Python when writing code.

6. Easy: Installing and using Python is free. This means that it can be downloaded free of charge and included in your application. See: The Python License for Open Source. Python is an example of Free / Libre Open Source Software (FLOSS), which means that you can freely share versions, read and change the source code of this software.

7. Supports the handling of exceptions: What is an exception? An exception is an occurrence that during an exception to the schedule that can interrupt the usual program flow. Python facilitates the handling of exceptions, which ensures that we can write less error-prone code and can evaluate different situations that can later trigger an exception.

8. Advanced Features: Supports generators and understanding of lists.

9. Automatic memory management: Python supports automatic memory management, sothe memory is automatically cleared and issued. You don't have to think about cleaning the memory.

With Python, what can you do?

You may be wondering what all Python applications are. There are so many Python applications, and here are some of them:

1. Web development is based on Python for Web structures such as Django and Flask. They help you write server-side code to handle the database, write programming logic for the backend, map urls, etc.

2. Machine learning: There are many applications for machine learning written in Python. Machine learning is a way to write logic so that a machine can learn on its own and solve a specific problem. Product recommendations on websites such as Amazon, Flipkart, eBay, etc., for example, are a machine learning algorithm that recognizes the interest of users. Another instance of machine learning is facial recognition and voice recognition on your computer.

3. Data Analysis: Python can also be used to create data analysis and data visualization in the form of charts.

4. Scripting: Scripting writes small programs to automate basic tasks such as sending emails with automatic response, etc. It is also possible to write such types of applications in the Python programming language.

5. Game Development: You can create games using Python.

6. Embedded applications can be built in Python.

7. Desktop applications: You can use libraries such as TKinter or QT to build desktop applications in Python.

You'll need the Psycopg2 Python package to connect to your database from a Python script. You can install it with pip.

Psycopg2 Install sudo pip3

Open your Python editor now and write some code to connect to your database:

Psycopg2 import

Psycopg2.connect('dbname = test) 'conn =

Oh, cur = conn.cursor)

Cur.execute('select * from individuals')

The outcome = cur.fetchall)

For success results:

PRINT(Outcome)

Run this code to see the query 's output. Notice that you'll need to include more credentials in the connection string if you're connecting remotely, such as adding a host IP, username, and database password:

Conn = psycopg2.connect('host=192.168.86.31 user = pii(host=192.168.86.31)

Dbname = test)) 'password = raspberry

To look up this question specifically, you could even construct a function:

Def get-all-people):: (def def

Query ="

CHOOSE

*

FROM

Individuals

"'""

(query) cur.execute(query)

Cur.fetchall)) ((returns,

And one which includes a search:

Def get-people-by-business(company):

Query ="

CHOOSE

*

FROM

Individuals

Where the Business = Percent s

"'""

Values = (firm,)

Cur.execute(values, query)

Cur.fetchall)) ((returns,

Or even a function used to add records:

Def add person(name, company): def add person:

Query ="

INSERT INTO,

Individuals

VALUES – VALUES

(percent s, percent s) (percent s)

"'""

Values = (name, business)

Cur.execute(values, query)

Chapter Twelve

Minecraft Pi Edition

You can find Minecraft Pi in the Games section by installing Raspbian on your Raspberry Pi. Minecraft Pi is a bare-bones version of the popular survival game that aims to teach different programming languages to users.

It's fun, of course, but it's not the Minecraft game that we have come to know and love. A community of users have found out how to install the full version of Minecraft on your Raspberry Pi 2 or 3, as with all things Raspberry Pi.

There's a lot of editing and tinkering with files and terminal commands, as with all things Raspberry Pi. Just make sure you take your time, read every move, and you should be okay.

Bear in mind

There's some stuff you should know before you dive in:

You will need to understand the log-in details for your Mojang account, along with your Minecraft username. You will need a paid license for Minecraft, naturally. You can buy one from Minecraft.net

Minecraft 1.8.9 is unique to the guide. However, the newest edition, officially 1.9.4 (more on this below), can be run with a quick tweak. Running Minecraft is not going to be the smoothest experience on a $35 machine, but it is certainly playable.

Project an hour to spend getting all up and running. The method is straightforward, often requiring you to copy several terminal commands from your browser and paste them into the command line. Press Enter on the keyboard after you paste each command in, and your Pi takes care of the rest.

Tips for keeping the process as fluid as possible

Here are some tips to make the process go as fast as possible:

• Phase 1 does not extend to users of Raspberry Pi 3. You can't overclock the Pi 3 at present. Moreover, the Pi 3 is actually quicker out of the box than the Pi 2 's suggested overclocking pace.

• Use the arrow keys on your keyboard after entering the Phase 4 command to highlight Advanced Options and press Enter. Next, highlight the GL Options, and choose Allow.

• In Step 7 of the guide that says to click "edit profile," you actually need to click Profile Editor, and then double-click the first (and only) listing. Under Version Selection, next to Use Version, press a drop-down and pick a build number. Bear in mind, the default of the guide is 1.8.9. Use that version right now, and then, once all works, we can change it.

• Step 10 tells you, without further guidance, to edit the file "run.sh". To do this, open your Pi directory's Minecraft folder and right-click the run.sh file, then select Text Editor.

You have two distinct choices for launching Minecraft. The guide tells you to use "./run.sh" to start Minecraft in the Terminal. While that works, you will need to enter "cd Minecraft" in the Terminal window before entering the button. Another option is to open the Minecraft folder, double-click the file run.sh, and then select "Run."

Run the most recent edition

All right, so you can start tinkering with the installation once you get it up and running. You'll need to relaunch the Minecraft.jar file in order to jump to the new version of Minecraft.

1. Enter: cd Minecraft in the terminal window

2. First, please enter: java -jar Minecraft.jar Minecraft.jar

3. Click the Profile Editor button and update the version to 1.9.4 (or whatever the most recent version is).

4. Save the update and click on the Play button, forcing the new version of Minecraft to download.

5. Open the Minecraft folder next.

6. If you make a mistake, take two seconds and make a copy of the run.sh file in order to remove any headaches. Rename the lines from "runcopy.sh." to something else.

7. Open the run.sh file with a copy securely tucked away by right-clicking on it and selecting the Text Editor.

8. On your keyboard, press Ctrl-F, and in the text field, enter 1.8.9. Two — and only two — instances should be found. Replace each of them with the current version of Minecraft (the version number you selected in phase 3 should be the same).

9. Save the file, and then restart the Raspberry Pi.

10. Launch Minecraft as you would usually like and enjoy it.

PART IV:

HARDWARE HACKING

Chapter Thirteen

Learning to Hack Hardware

As is with the word hacker, the "hacker ethic" has morphed over time. Hacking was initially motivated by a thirst to learn how things work and was carried out on networks that the hackers were entitled to access. Mix a touch of chaos with the values of hacking and you end up with hackers who enjoy ideas and exploration of personal property rights.

Mass media have concentrated on this notion and do not understand that much of today's hacking is by people who believe in property rights and use their hacking skills to protect others who are unable to defend themselves.

Clifford Stoll meets a new machine administrator who adheres to the anarchistic interpretation of the hacker ethic in the non-fiction novel "The Cuckoo's Egg". During his experiences chronicled in the novel, Clifford experienced a shift in his thinking and knew the ideology of the systems administrator was incorrect but could not express it.

Land ownership is a pillar of civilization and is created using a fabric of confidence. This confidence is an unspoken understanding in many cases and the trust is codified in statute in others. More often than not, the trust is not enforced until after the event.

The dashed white line on the highway reminds the drivers of that confidence, but at 80 miles per hour, it does not keep another driver from turning his left hand in front of me. Similarly, I 'm sure that when I get a drink from the vending machine, it won't kill me. If it does, after the litigation, my family will be wealthy, but I will still be dead.

In any case, if we cannot trust each other, then the fabric of trust unravels and individuals stop constructing the very structures we want to explore. You can't have your cake and you can't eat it, either.

As hackers, we have an option that we can pursue without regard to property rights and break the fabric of trust or restore and improve the fabric of trust and property rights.

Great responsibility requires great strength:

• A power source that provides the voltage of the source we measured earlier (Vs = 5v).

• A resistor limiting current (R1 = x).

A diode that causes the forward voltage voltage to fall (LED1 = 2.0v for orange).

• A land link.

What we want to do is restrict the amount of current that flows through the circuit (I). Approximately 5mA (1/4th the maximum LED rating) should be ideal. Know the rule of Ohm? Huh? V = IR? We can use R = V / I to calculate the necessary resistance because we have a known voltage and amperage. For voltage, after the fall caused by the diode, we need the voltage, so our equation will look something like R=(Vs-Vf)/I where:

• Vs = voltage supply (5v)

• Vf = LED forward voltage (2v)

• I = current needed (0.005A)

• R = resistance required (x)

Plugging all of that in, we get the following: (5v-2v)/0.005A=600

However, at the precise value we like and might need to round up or down, we will not always find a resistor. I rounded down to the nearest value I had on-hand because I wanted to round in the direction of more sun, 510.

The rainbow LED results in the following application of the same process: (5v-3.2v)/0.005A=360

I rounded down again for more amperage and more luminosity and went with 220.

Executing the change

We can really dig in and start changing stuff now that we know what needs to be replaced and what to replace it with.

We need 6 components to be removed: the 3 LEDs and the 3 resistors (R9-R11). Using a soldering iron and a pair of needle-nose pliers, they can be removed reasonably quickly. These are steps I prefer to follow:

• Apply lead solder to the target modules’ pins. Doing so will clean the joint and the melting temperature will usually decrease.

• Grip the pliers with a goal part.

• Melt one of the target part’s joints with the soldering iron.

• Bend the part gently away from the joint when applying heat to the joint. This can allow a small bit of the component’s pin in the heated joint to pull out.

•  On the other pad, repeat, going in the opposite direction.

• Continue back and forth to force out the part.

• Optionally, to remove excess solder, use a desoldering pump or wick.

We will insert our new ones once the old components have been removed. I tend to work in a sort of "batch" phase with through-hole components:

• Insert a section, being aware of the polarity criteria.

• Bend the component’s leads at a 45-ish degree angle so that the component without solder remains in place. Note: In the future, this will make desoldering this part more difficult.

• Repeat for all components or sizable community.

• Flip the board over and weld each part into place.

• Trim part excess leads.

• Remember to reference the polarity we recorded at the beginning when adding the LEDs. It is possible to put the LED in backwards—even if it is backwards, it won’t light up.

A Short Soldering Guide

The great thing about soldering is that you don't need a lot to get started. For most of your welding projects, we will outline the basic equipment and supplies you will need below.

Welding Iron

To melt solder around electrical links, a soldering iron is a hand tool that plugs into a regular 120v AC outlet and heats up. This is one of the most important soldering instruments used, and it may come in a few variants, such as the shape of a pen or pistol. It's recommended that you use the pen style soldering iron in the 15W to 30W range for beginners. The majority of soldering irons have interchangeable tips that can be used for various applications of soldering. When using any form of soldering iron, be very careful because it can heat up to 896′ F, which is extremely hot.

In short, soldering is a common and fairly easy way for different kinds of materials and components to be affixed or bonded to each other. Using a small amount of metal alloy, known as solder, and a heated handheld tool called a soldering iron, the procedure is carried out. You'll usually use the hot metal tip of the iron when you solder things together to melt a small amount of solder alloy around and between the components or surfaces being connected.

The resulting soldered bond or joint, once cooled and hardened, will be permanent. It will provide a safe connection between discrete parts, electrically conductive (for circuitry), and watertight (for plumbing applications). It is worth noting, however, that hardened solders can typically be remelted and removed reasonably easily by reapplying adequate heat. This also makes it possible to separate or rework parts that have previously been welded together as required. This approach is known as desoldering, which we will return to.

We will include a brief overview of appropriate soldering techniques for a few different situations and part types in this beginners' guide, while offering helpful tips on how to safely and reliably use soldering iron and other main tools. We will also address the types of items, kits and soldering iron accessories could better fit various occupations, addressing some simple FAQs regarding the use and maintenance of general equipment.

How to Properly Solder

As for all DIY operations involving potentially dangerous instruments or environments, safety awareness in planning for soldering work should always be a top priority. As ever, before beginning the work, this involves ensuring that you have the correct PPE equipment in place. It also means ensuring that the entire environment is as well prepared and practically free from unnecessary risks as possible.

In addition, before you perform any work, it is important to know the core fundamentals of how to solder safely. There are different aspects to safe soldering for beginners that you need to be aware of in order to solder properly while posing a minimal risk to yourself, your instruments, and your environment.

The soldering iron edge, which needs to get extremely hot in order to perform its primary purpose, is the most obvious threat. Also, simple models that plug directly into a wall socket and provide no manual temperature control (typically a soldering station feature that enables iron performance to be fine-tuned) will normally very quickly heat up to about 400 degrees Celsius. This is easily hot enough when treated improperly to cause serious burns.

A variety of reassuring built-in safety features can be offered by more advanced models and varied add-on accessories. Models purchased as part of a comprehensive soldering iron kit can, however, hold plenty of potential if used carelessly to cause serious and permanent injury.

There are also other possible hazards to watch out for when soldering, in addition to the intense heat involved. In particular, due to air pockets or impurities, it is important to be aware that solder material itself can occasionally 'spit' when overheated. This implies, especially for beginners, that protective eyewear is a must.

In addition, most solder pastes and compounds contain hazardous elements such as lead and rosin-when handling soldering tools and materials, it is always sensible to wear gloves, and before starting a job, to ensure adequate ventilation of your workspace is possible.

Protection Checklist for Soldering

Prior to Soldering:

• Read carefully all product directions and safety recommendations and make sure you are aware of the common risks.

• Carefully read the solder ingredient lists and documentation. Check directly with suppliers or distributors if the label contains inadequate details about possible toxicity.

• Make sure the work area is safe, clean, stable and free from ignition sources.

• Check that you are operating in a well-ventilated environment with sufficient fume extraction available.

• Wear protective glasses at all times and use heatproof gloves to treat materials.

• Check that you have the correct product form for the job at hand— soldering irons are available in various sizes and wattages, mostly intended for particular types of applications.

• Do not use any soldering iron or other electrical device that shows noticeable damage to the body of the instrument, wiring or socket.

• Always know where the nearest fire extinguisher and escape paths are

During Welding:

• Never try to solder live / powered circuits, terminals, ties or parts

• Keep soldering iron cleaning accessories near at hand, such as wire pads and damp solder sponges, to ensure that the tip of the iron is kept as free as possible from material build-up during use.

• Never contact anything but the insulated handle (sometimes referred to as the 'wand') with the soldering iron.

• Use tweezers and/or gloves to hold surfaces and parts that are (or have been) welded recently.

• Be careful of possible molten alloy spitting and wear safety glasses at all times while melting solder.

• When not in use, always return the iron to its cradle or stand—never directly lay it on a work surface, table, or bench.

• If you inadvertently grab a cable, check that the stand is properly weighted or sturdy enough not to easily collapse-if this happens, don't try to catch the iron mid-fall.

• If you experience a burn, keep it immediately under cold running water for a minimum of 10-15 minutes until the required first aid measures are followed.

• If you need to leave it unattended at any point, always turn the soldering iron or station off at the plug socket.

Chapter Fourteen

The Gpio Port

The row of GPIO (general-purpose input / output) pins along the top edge of the board is a powerful function of the Raspberry Pi. A 40-pin GPIO header (unpopulated on Pi Zero and Pi Zero W) is found on all existing Raspberry Pi boards. A shorter 26-pin header was composed of boards prior to the Pi 1 Model B+ (2014).

Pins from GPIO

Any of the GPIO pins may be marked as an input or output pin (in software) and used for a wide variety of purposes.

Layout of GPIO

Note: GPIO pins are not numbered in numerical order; GPIO pins 0 and 1 are present on the panel (physical pins 27 and 28), but are for advanced use only.

The voltages

On the frame, two 5V pins and two 3V3 pins are present, as well as many unconfigurable ground pins (0V). Both general purpose 3V3 pins are the remaining pins, meaning outputs are set to 3V3 and inputs are 3V3-tolerant.

Outputs

It is possible to set a GPIO pin designated as an output pin to high (3V3) or low (0V).

Inputs

It is possible to read a GPIO pin designated as an input pin as high (3V3) or low (0V). With the use of internal pull-up or pull-down resistors, this is facilitated. The GPIO2 and GPIO3 pins have fixed pull-up resistors, but this can be set up in software for other pins.

MORE

The GPIO pins can be used with several alternative functions as well as simple input and output devices, some of which are available on all pins, others on particular pins:

• PWM (modulation of pulse-width)

• Open PWM applications on all pins

• PWM hardware for GPIO12, GPIO13, GPIO18, GPIO1919, GPIO19

• SPI SPI

• MISO (GPIO9); SCLK (GPIO11); CE0 (GPIO8), CE1 (GPIO7); SPI0: MOSI (GPIO10)

• MISO (GPIO19); SCLK (GPIO21); CE0 (GPIO18); CE1 (GPIO17); CE2 (GPIO16); SPI1: MOSI (GPIO20);

• The I2C

• Data: (GPIO2); (GPIO3) clock

• EEPROM Data: (GPIO0); Clock EEPROM (GPIO1)

• Serial Sequence

• TX (GPIO14); GPIO15 (RX)

• Pinout for GPIO

It's important to be mindful of which pin is which. Some people (like the RasPiO Portsplus PCB, or the Raspberry Leaf printable) use pin labels.

On the Raspberry Pi, a helpful reference can be accessed by opening the terminal window and running the pinout command. The GPIO Zero Python library, which is installed by default on the desktop image of the Raspberry Pi OS, but not on Raspberry Pi OS Lite, provides this method.

Chapter Fifteen

The Raspberry Pi (Camera Module)

To take advantage of the MMAL API running over OpenMAX, all the applications are powered from the command line and written. The MMAL API offers a framework that is simpler to use than that provided by OpenMAX. Note that MMAL is an API unique to Broadcom that is used only on VideoCore 4 systems.

Up to four OpenMAX (MMAL) components are used in the applications: camera, preview, encoder, and null sink. Both applications use the component of the camera; raspistill uses the cImage Encode’s component; raspivid uses the Video Encode’s component; and raspiyuv and raspividyuv do not use an encoder, and send their YUV or RGB output directly to the file from the component of the camera.

The preview screen is optional, but it can be used full-screen or redirected to a particular rectangular region of the screen. The null sink component is used to 'absorb' the preview frames if the preview is disabled. Even if these are not needed for display, the camera must generate preview frames, as they are used for measuring exposure and white balance settings.

In addition, the filename option can be skipped (in which case the preview is shown but no file is written), or all output can be redirected to stdout.

Command line support is accessible by entering only the name of the program on the command line.

Setting Up > See Setup for Camera > Troubleshooting here

There are a range of items to try if the camera module is not working correctly:

• Is the ribbon cord, not the Monitor Serial Interface (DSI), connected to the Camera Serial Interface (CSI)? In either port, the ribbon connector will suit. The camera port is near the HDMI connector.

• Are all the ribbon connectors securely seated, and are they round in the right way? They must be straight in their holes.

• Is the Camera Module connector securely connected between the smaller black Camera Module itself and the PCB? This connection can come loose during transit or when placing the Camera Module in a case. Flip up the connector on the PCB using a fingernail, then reconnect it with gentle pressure. It engages with a very slight click. Don't push it; it's possibly slightly misaligned if it does not engage.

• Have sudo apt and sudo apt full-upgrade been upgraded?

• Has raspi-config been executed and allowed the Camera Module?

• Is your power supply adequate? The Camera Module adds between 200-250mA to your Raspberry Pi's power requirements.

Try the following if things are still not working:

• Error: the command raspistill / raspivid is not found. This possibly means that somehow your update / upgrade failed. Again, try it.

• Error: ENOMEM. The Camera Module does not start. Re-check all the links.

•Mistake: ENOSPC. It is possible that the Camera Module will run out of GPU memory. In the /boot/ folder, search config.txt. The choice for gpu mem should be at least 128. Alternatively, in the Advanced section of raspi-config, use the Memory Split option to describe this.

If you've tested all the above problems and the Camera Module still doesn't fit, try posting for more support on our forums.

Popular Options on Command Line

• Window of Preview: —preview, -p Settings for the preview window < 'x,y,w,h' >

Allows the user to specify the size and screen position of the preview window. Note that this will be superimposed on all other windows / graphics at the end.

• Fullscreen Preview: —fullscreen, -f

Forces the whole screen to use the preview window. Notice that it will retain the aspect ratio of the incoming image, so there may be bars on some edges.

• Preview Window does not Appear: —nopreview, -n

It totally disables the preview window. Notice that, while the preview is disabled, frames will still be generated by the camera, so power will be used.

Preview Window Opacity: —opacity, -op

Configures the opacity of the preview windows. 0 = translucent, 255 = opaque completely.

Choices for Camera Control

• Set Image Sharpness: —Sharpness, -sh (-100-100)

Configures the sharpness of the frame. 0 is the default.

• Set Image Contrast: —contrast, -co (-100-100)

Set the picture contrast. 0 is the default.

•  Set Image Brightness: —brightness, -br (0-100)

Configures the image's brightness. 50 is the default option. 0 is black, 100 is white.

• Set Image Saturation: —saturation, -sa (-100-100)

Sets the image's colour saturation. 0 is the default.

• Set ISO Capture: —ISO, -ISO (100-800)

Sets the ISO to be used for screenshots.

• Turn on the Stabilization Video: —vstab, -vs

Switch on video stabilization in video mode only.

• Set EV Compensation: —ev, -ev (-10-10)

Sets the image's EV compensation. The default setting is 0.

•  Set Exposure Mode: —exposure, -ex

Possible scenarios are:

• Auto: using automatic exposure mode

• Night: pick a setting for shooting at night

• Backlight: pick the backlit subject setting

• Flashlight

• Spotlight

• Sports: select sports settings (fast shutter, etc.)

• Snow: pick an optimal setting for snowy scenery

• Beach: pick beach-optimized settings

• Very long: pick a long exposure setting

• Fixedfps: restrict fps to a fixed value

• Antishake: mode antishake

• Fireworks: pick the optimized setting for fireworks

Note that, depending on the camera tuning, not all of these settings can be applied.

•  Set Avoidance Mode for Flicker: —flicker, -fli

Set a mode to compensate for lights that flicker at the frequency of the mains, which can be seen through a picture as a dark horizontal band. Flicker avoidance locks the exposure time (8.33ms for 60Hz, or 10ms for 50Hz) to a multiple of the mains flicker frequency. This implies that photos can be noisier since the control algorithm needs to increase the gain if it requires an intermediate exposure value instead of exposure time. Auto may be confused by external variables, so unless actually needed, it is preferable to leave this setting off.

Possible scenarios are:

• Off: turn off flicker prevention

• Auto: Detect mains frequency automatically

• 50hz: avoidance set at 50Hz

• 60hz: avoidance set at 60Hz

•  Set White Balance Automatic (AWB) Mode—awb, -awb

These settings are set in brackets for the modes for which color temperature ranges (K) are available.

• Off: switching off the measurement of white balance

• Auto: automatic (default) mode

• Sun: sunny (between 5000 K and 6500 K) mode

• Cloud: gloomy (between 6500 K and 12000 K) mode

• Shade: mode of shade

• Tungsten: mode of tungsten illumination (between 2500 K and 3500 K)

• Fluorescent: fluorescent (between 2500 K and 4500 K) lighting mode

• Incandescent: mode of incandescent lighting

• Flash: flash mode

• Horizon: form of horizon

• Greyworld: Use this on the NoIR camera due to the absence of the IR filter to repair incorrect AWB results.

Notice that, depending on the type of camera, not all of these settings can be applied.

•  Set Image Effect Environment—imxfx, -ifx

Set the effect to apply to a picture:

• None: no impact (default)

• Negative: inverting the colors of the picture

• Solarize: solarization of the image

• Posterisation: posterisation of the picture

• Whiteboard: impact whiteboard

• Blackboard: impact blackboard

• Drawing: sketch impact

• Denoise: denoise the photo

• Emboss: emboss the photo

• Oil paint: oil paint effect

• Hatch: hatch sketch effects

• Gpen: impact of graphite sketch

• Pastel: pastel impact

• Aquarell effect: watercolour effect

• Movie: film grain impact

• Blur: the picture gets blurred

• Saturation: saturate image’s color

• Colourswap: not completely enforced

• Washedout: not completely introduced

• Colourpoint: not completely introduced

• Colourbalance: not completely applied

• Cartoon: not completely launched

Note that, in all cases, not all these settings can be available.

•  Color Effect Package: —colfx, -cfx

The U and V parameters supplied (range 0-255) are added to the image's U and Y channels. For example, a monochrome image should result in —Colfx 128:128.

•  Set Metering Mode: —metering, -mm

Enter the metering mode that is used to preview and capture:

• Average: the whole frame average for metering

• Spot: spot metering

• Backlit: Suppose a backlit picture

• Matrix: metering matrix

Time-Lapse Photography command-line

You simply configure the Raspberry Pi to take a picture at a regular interval to produce a time-lapse video, such as once a minute, then use an application to stitch the pictures together into a video. There are a few ways to do this.

Using the integrated time-lapse mode of Raspistill

Raspistill has a built-in time-lapse mode program that uses the command line switch —timelapse (or -tl). The time between shots in milliseconds is the value which follows the switch:

Raspistill -t 30000 -tl 2000 -o percentage of images 04d.jpgg

Note in the output filename the percentage of 04d: this indicates the point in the filename where you want the amount of the frame count to appear. The above instruction, for example, produces a capture every two seconds (2000ms), over a total duration of 30 seconds (30000ms), called image0001.jpg, image0002.jpg, and so on, through to image0015.jpg.

The percentage of 04d indicates a four-digit number, with added leading zeros to make up the number of digits needed. For instance, a percentage of 08d will lead to an eight-digit number. If you don't want leading zeros, you might skip 0, too.

If a timelapse value of 0 is entered, photographs will be taken as quickly as possible by the application. To ensure that exposure measurements can be made, remember that there is a minimum enforced delay of approximately 30 milliseconds between captures.

Cron Use

Cron is a good way to automate the taking of an image at a regular interval. Open the Cron edit table to edit:

Crontab -e — e

This either asks the editor you want to use or opens it in your default editor. If the file is opened in an editor, add the following line to schedule each minute to take an image.

Save and exit and the message should be seen:

Crontab: new crontab installed:

Make sure that you use e.g. percent 04d to output each image to a new file with raspistill: if you don't, then raspistill will overwrite the same file every time you write an image.

Stitching together photos

You're going to need to stitch the images together into a video now. Using mencoder, you can do this on the Pi, but processing will be slow. You may prefer to move the image files to your laptop or desktop computer and create the video there.

Navigate to a folder that contains your photos and list the file names in a text file. For instance:

Ls * .jpg > stills.txt text

On the Pi Raspberry

Although it will be sluggish (due to software encoding rather than using the Raspberry Pi hardware acceleration), using various available tools, you can stitch your JPEG images together. Avconv, which must be mounted, will be included in this documentation.

Download sudo apt libav-tools

You can now use these tools to convert your JPEG files to H264 video files:

Image percentage of avconv -r 10 -i 04d.jpg -r 10 -vcodec libx264 -vf scale=1280:720 timelapse.mp4

This can encode a little more than a frame per second on a Raspberry Pi 3. Other Pi models' efficiency can vary. The parameters used are:

• -r 10 For input and output files, presume ten frames per second.

• -i image percent 04.jpg Specification of the input file (to fit the files produced during the capture).

• -vcodec libx264 Use the x264 encoder software.

• -vf scale=1280:720 720p scale. Depending on the specifications, you can also use 1920: 1080, or lower resolutions. Notice that the Pi can only play back up to 1080p video, but you might set it here if you intend to play back at 4 K, for instance.

• timelapse.mp4 The output file's name.

Avconv has a detailed set of parameters for different choices for encoding and other settings. It is possible to list these using avconv —support.

On another machine with Linux

You may use the same Raspberry Pi instructions, or an alternative set such as the mencoder:

Mencoder sudo apt installation

Now run the command below:

You should have a video file called timelapse.avi containing a time-lapse of your photos until that's done.

Chapter Sixteen

Add-On Hardware

The add-on can apply to:

1. Any third-party software application or script that is applied to a program to give it additional functionality and abilities is a software add-on or extension.

For instance, an excellent example of a software add-on is Adobe Flash, which allows users to watch videos or play games on an Internet browser.

Add-ons are often produced using a software option or via a third-party platform by individuals or organizations not associated with the original developer and added.

Note: An add-on is referred to by browsers such as Google Chrome as an extension.

Tip: An add-in ("in" not "on") refers to additional software giving additional features to a software program. For describing a car, an add-in can also be used.

2. When referring to hardware, any component that improves your computer's functionality or performance is an add-on. Additional RAM, a new CPU, or a faster video card, for instance, could all be called add-ons.

Raspberry Pi Case Official

Three interchangeable lids are part of the official Raspberry Pi Zero case from the Raspberry Pi Foundation: the Camera Cover, the GPIO Lid, and the Regular Lid. It also requires a short cable from the Pi Zero Camera.

Compatible with the Raspberry Pi Zero and Wireless Raspberry Pi Zero.

Touchscreen Monitor for Raspberry Pi 7

This 7′′ Raspberry Pi touchscreen monitor allows users the opportunity to build all-in-one, integrated projects such as tablets, infotainment systems and embedded projects. The 800 x 480 display connects with an adapter board that handles the conversion of power and signal. Only two Pi connections are required; power from the GPIO port of the Pi and a ribbon cable that connects to the current DSI port.

Turn your Raspberry Pi into a phone, infotainment system, or standalone computer with a touch screen.

Truly interactive: a virtual 'on-screen' keyboard would support the new device drivers, so there is no need to plug a keyboard and mouse in.

Make a visual display of your own Internet of Things (IoT) devices. Simply attach your Raspberry Pi, construct a Python script to communicate with the display, and you're ready to install your own touch screen home automation devices.

A number of educational applications and programs available on the Raspberry Pi would be touch-enabled, making the Raspberry Pi easier for learning and programming.

HAT Meaning

The Sense HAT is a Raspberry Pi add-on board, created specifically for the Astro Pi mission-launched in December 2015 at the International Space Station-and is now available for purchase.

The Sense HAT has an 8 ⁇ 8 RGB LED matrix, a five-button joystick and the following sensors are included:

• Gyroscope

• Accelerometer

• Magnetometer

• Temperature

• Barometric pressure

• Humidity

PART V:

APPENDIXES

Appendix A: Python Recipes

Snake Raspberry

Angry Birds, step aside! Pokémon Go! On your bike! Snake holds the top position when it comes to the cream of the crop of cell phone sports.

Snake Game Nokia

The drawer that won't open all the way because anything inside is stuck at an odd angle may still have an old Nokia 3310 lost somewhere in the depths of a drawer. So grab your Pi and Sense HAT, or the free Sense HAT simulator (online or on Raspbian), and Snake SLUG code yourself will be much simpler. In doing so, you can introduce your household 's smaller residents to the best reptile-focused game ever made ... now with added shellfish.

The Solution

Travel to our resource page to check out the game for yourself, where you can find the online Sense HAT simulator embedded and ready to go.

Free resource for Raspberry Pi Sense HAT Slug

It will look just like this, and you can use the arrow keys of your machine to steer your slug toward her delicious treats.

From there, when coding your own version of the game in Python, you'll be taken on a step-by - step journey from zero to SLUG glory. You'll learn to deal with two-dimensional lists along the way and to use the pixel display and joystick feedback of the Sense HAT. And, in line with our Digital Making Program, by finishing the resource, you can extend your understanding of applying abstraction and decomposition to solve more complex issues.

The Meaning of HAT

As part of the Astro Pi mission in December 2015, the Raspberry Pi Sense HAT was originally developed and made. It is a perfect add-on for your digital making toolkit, with an 8-8 RGB LED matrix, a joystick, and a plethora of on-board sensors including an accelerometer, gyroscope, and magnetometer, and is excellent for data collection and evaluation ventures.

User List of IRC

In a network with hundreds of chat rooms, the /list command helps you to find only channels with a certain number of participants, a very useful function.

There are several different channels sponsored by each IRC network. Once you are linked, a list of channels on that network can be obtained with the /list command:

/listing

The listing report shows the name of the site, the number of individuals linked to each channel, and often a channel-related statement or explanation. There are also thousands of different channels on various topics on larger networks, which are also too many to learn, so you can use the following tricks to get listings that are actually usable:

• List of sites. By typing /set hold mode on before entering the list command, you can get a page by page list. A listing consisting of one screen at a time will be given by this option. To switch the page function off, you can type /set hold mode off.

• Min or max. Since there are only one or two people on the vast majority of channels, and you typically want to find rooms with a lot of people in them and a lively discussion, one of the most helpful things you can do is get a list of channels with the "min" option with a minimum number of users. You can limit the listing to those with a maximum number of users with the 'max' option if you want to find only sparser spaces.

/list -min 30 -min 30

/list -max 5 Max 5

• Min and limit. You can combine the "min" and "max" options to list only certain platforms with the number of people you are interested in, for greater versatility.

/list -min 25 -max 30 -min 30

/list -min 40 -max 50 -max 50

Input and Output GPIO

A GPIO pin is a generic pin whose value is composed of one of two (high or low) voltage settings and whose action can be programmed by software. A GPIO port is a platform-defined group (often 4 or more pins) of GPIO pins. GPIO pins that are part of a GPIO port cannot be individually retrieved or operated as GPIO pins, however.

An application should first open and obtain a GPIOPin or GPIOPort instance for the pin or port it wants to use, using its numerical ID, name, type (interface), or properties, in order to use a particular pin or port.

Here's an example of using its ID to obtain a GPIOPin and a GPIOPort:

PeripheralManager.open(1); GPIOPin pin = (GPIOPin)

PeripheralManager.open(0);; GPIOPort port = (GPIOPort)

An example of using its name and interface is here:

PeripheralManager.open('LED PIN, 'GPIOPin.class, null); GPIOPin pin = (GPIOPin)

Port GPIOPort = PeripheralManager.open("LCD DATA PORT,, " (GPIOPort)

Null, GPIOPort.class);

Once a pin is opened, by calling the GPIOPin.getValue) (method, an application can get the current value of a GPIO pin and set its value by calling the GPIOPin.setValue(boolean) method. Similarly, once a port is opened, by calling the GPIOPort.getValue) (method, an application can obtain the current value of a GPIO port and set its value by calling the GPIOPort.setValue(int) method.

(true); pin.setValue(true);

The.setValue(0xFF) port;

When completed, GPIOPin.close) (or GPIOPort.close) (should be called by the application to release the pin or port, respectively.

Hey, pin.close);

Port.close););)

An example of using the GPIO API is given in Example 7-1. First, it records a pin listener for the GPIO input pin to which a switch button is connected. The listener is alerted when the button is pressed. By setting the GPIO output pin that the LED is connected to accordingly, the listener then turns the LED on or off.

Example 7-1 Use of the APIs of the GPIO

Com.oracle.deviceaccess. PeripheralManager importation;

Import com.oracle.deviceaccess. PeripheralExceptionNotAvailable;

Com.oracle.deviceaccess. PeripheralNotFoundException importation;

Com.oracle.deviceaccess.gpio. GPIOPin import;

Com.oracle.deviceaccess.gpio. PinEvent import;

Com.oracle.deviceaccess.gpio. PinListener imports;

Java.io. IOException for importing;

GPIODemo Public Class

SwitchPin for GPIOPin = null;

LedPin GPIOPin = null;

GPIODemo) (Public

Try {Try

PeripheralManager.open(1); switchPin = (GPIOPin)

PeripheralManager.open(3); ledPin = (GPIOPin)

{New PinListener) ({switchPin.setInputListener)

Changed (PinEvent event) public void value

Try {Try

((GPIOPin) occurrence.getPeripheral)).).

SetValue(event.getValue)); (/ Turn on or off the LED /

} catch (IOException ex)} {{catch

Ignored /

} (PeripheralNotAvailableException ex) catch

Ignored /

}

}

});;

} catch (IOException ex)} {{catch

/ Manage exception / handle exception

} (PeripheralNotFoundException ex) catch

/ Manage exception / handle exception

} (PeripheralNotAvailableException ex) catch

/ Manage exception / handle exception

} Finally} {Finally

If (switchPin! = null)

Try {Try

(); switchPin.close();

} catch (IOException ex)} {{catch

}

}

If (ledPin! = null)

Try {Try

();; ledPin.close();

} catch (IOException ex)} {{catch

}

}

}

}

}

Notice that the underlying configuration of the platform can allow an application to set certain GPIO pins or ports for either output or input, while others may be used for input only or output only, and the application cannot change its path. Notice also that asynchronous notification of changes in pin or port value is only loosely tied to interrupt requests at the hardware stage. The platform does not guarantee notification in a deterministic or timely way.

Procedures that handle GPIO pins, and particularly event listeners, should be implemented as quickly as possible due to performance problems.

Appendix B: Camera Module Quick Reference of Raspberry Pi

SHARED OPTIONS

Samba is an SMB / CIFS networking protocol implementation that Windows devices use to provide mutual access to files, printers, serial ports, etc. A detailed Wikipedia page on Samba and its capabilities is open.

This page will describe how to install a shared folder on a Windows computer so that it appears on your Raspberry Pi, or to share a folder on your Raspberry Pi so that it can be accessed by a Windows client, using a subset of the Samba method.

Installing support for CIFS / Samba

Raspberry Pi OS does not provide CIFS / Samba support by default, but this can be added easily. All the necessary components to use Samba as a server or client are installed with the following commands.

Sudo Update Apt

Samba samba-common-bin smbclient cifs-utils sudo apt install install

Using a Windows folder that is shared

Firstly, on your Windows system, you need to share a folder. This method is very convoluted!

Switch sharing:

1. By right-clicking on the device tray and choosing it, open the Networking and Sharing Centre

2. Click Change Advanced Settings for Sharing

3. Pick Turn on exploration of networks

4. Pick Switching on File Sharing and Print Share

5. Save Modifications

Share a folder:

You can share any folder you like, but simply create a folder called share for this case.

1. Creating a share folder on your desktop.

2. Right-click and pick Properties in the new folder.

3. Click the Sharing tab and then click the Sharing Advanced button.

4. Select Share this folder; the name of the shared folder is the name of the folder by default.

5. Click on the button for Permissions

6. Select Anyone and Full Control for this example (you can restrict access to particular users if required); click OK when done, then OK again to exit the Advanced Sharing tab.

7. Click the Protection tab because we need to configure the same privileges now.

8. Select the same settings as the Permissions tab and, if necessary, add the chosen user.

9. Click on OK

Now the folder should be shared.

Windows 10 Wizard for sharing

There is a Sharing Wizard on Windows 10 that assists with some of these moves.

1. Run the application for Device Management from the Start Bar

2. Choose Shared Directories, then Share Shares

3. Right-click and choose New Share to start the Sharing Assistant; click Next.

4. Choose a folder that you want to post, and then press Next

5. To use all the defaults for sharing, press Next

6. Select Custom and set the permissions required, and then click OK, then click Finish.

Install the folder on the Raspberry Pi

In Linux, mounting is the process of adding a folder to a location, so we need that location first:

Windowshare mkdir

Now, we need the remote folder to be installed to that spot. The remote folder is the Windows PC host name or IP address and the share name used when it is shared. The Windows username that will be used to access the remote machine needs to be given as well.

/<hostname or IP address>/share /home / pi / windowshare -o user=<name > /sudo mount.cifs

You should now be able to access the content of your Raspberry Pi 's Windows share:

Windowshare cd

Ls

Sharing a folder for Windows use

First, create a sharing folder. This example creates a folder called shared in the current user's home folder, and assumes pi is the current user.

~ cd ~

Linked Mkdir

We need to tell Samba to share this folder now, using the configuration file for Samba.

Nano /etc / samba / smb.conf sudo

Add the following at the end of the file to share the archive, granting the remote user permission to read / write:

[share] [share]

Path = /pi / home / shared

Just read = no

Public = Yes = Yes

Writable = yes, writable =

Locate the workgroup line in the same file and change it to the workgroup name of your local Windows network if necessary.

Workgroup = < the name of your workgroup here >

That should be enough to share the folder. On your Windows system, the folder should appear when you browse the network and you should be able to connect to it.

Options for Raspistill

Raspistill is a command line tool with a Raspberry Pi camera module to take still photographs.

Basic Application of Raspistill

Enter the following command from the terminal to take a picture when the camera module is attached and enabled:

The camera was placed upside-down in this example. If the camera is positioned in this location, it is important to flip the picture to appear in the correct way.

Flip vertical and flip horizontal

The picture must be rotated 180 ° to view correctly with the camera positioned upside-down. By passing the -vf and -hf flags, the way to correct this is to add both a vertical and a horizontal flip:

Now the photo has been properly recorded.

The Resolution

At a resolution of 2592 x 1944, which is 5,038,848 pixels or 5 megapixels, the camera module takes photographs.

Width of File

There will be about 2.4 MB for a picture taken with the camera module. This is around 425 per GB of images.

It will take up to 1 GB in about 7 hours to take 1 photo per minute. This is a pace of around 3.3 GB per day or 144 MB per hour.

Script from Bash

You can build a Bash script which uses the camera to take an image. Open your editor of choice to construct a script and write the following sample code:

#! About /bin / bash

DATE=$(date + "percent Y- percent m- percent d percent H percent M")

This script will take an image and use a timestamp to name the file. By building the camera folder, you'll also need to make sure the route exists:

MKDIR Camera Camera

Say we saved it as camera.sh, so we'd make the file executable first:

+ x chmod camera.sh

Run then with:

The./camera.sh

More choices

For a complete list of choices, run raspistill without any arguments. Retransfer stderr to stdout to scroll and pipe the output to less:

Raspistill 2>&1 smaller

RASPIVID OPTIONS

Raspivid is a video capture command line tool with a Raspberry Pi camera module.

Raspivid Simple Use

Record a video using the following command when the camera module is attached and enabled:

-o vid.h2644 raspivid

Remember to use -hf and -vf, such as raspistill, to flip the image if necessary.

This will save a video file of 5 seconds to the path provided here as vid.h264 (default time length).

Specify video length

Pass the -t flag with a number of milliseconds to determine the length of the video taken. For instance:

Raspivid -o for video.h264 -t 1000000

It will record a video for 10 seconds.

More choices

Run raspivid with no reasons for a complete list of potential choices, or pipe this command with less and scroll through:

Raspivid 2>&1 Smaller

Scroll and type q to exit using the arrow keys.

Image Format for MP4

As a raw H264 video stream, the Pi captures video. Unless it is "wrapped" in an appropriate container format like MP4, many media players may fail to play it, or play it at an incorrect pace. Using MP4Box is the best way to get an MP4 file from the Raspivid button.

Download the MP4Box using the following command:

Download sudo apt -y gpacac install.

Capture your raw video with Raspivid and package it like this in an MP4 container:

# Record 30 seconds of 640x480 raw video with a bit rate of 150kB / s in a pivideo.h264 file:

Raspivid -t 30000 -w 640 -h 480 -fps 25 -b 1200000 -p 0,0,640,480 -o Pivideo.h2640,480

# RAW video bundled in an MP4 container:

Pivideo.h264 pivideo.mp4Box -add pivideo.h264 pivideo.mp4Box

# Delete the raw file from the source, leaving the remaining pivideo.mp4 file to play.

Pivideo.h2644rm rm

Alternatively, wrap your current Raspivid output around MP4

Appendix C: HDMI Display Modes

Options on composite video mode

Sdtv mode for sdtv

A TV standard used for composite video output is specified by the sdtv mode command. On the original Raspberry Pi, the RCA socket produces composite video. Composite video is output along with sound on the 4 pole TRRS (headphone) socket on other Raspberry Pis, except for Pi Zero and Compute Module. There is an unpopulated header called 'TV' on the Pi Zero that outputs composite video. Composite video is accessible via the TVDAC pin on the Compute Module. The default sdtv mode value is 0.0.

Outcome of sdtv mode

0 NTSC NORMAL

1 NTSC Japanese edition- no pedestal

2 Regular Friend

3 Brazilian PAL version-525/60 rather than 625/50, various subcarriers

16 NTSC Progressive Scan

18 PAL’s Progressive Scan

Sdtv aspect

The sdtv aspect command determines the composite video output aspect ratio. The value is 1. by default.

Product of sdtv aspect

1 4:3

2 14:9

3 16:9

Sdtv-disable-colourburst

Setting sdtv disable colourburst to 1 on composite video output disables colourburst. The image will be shown in monochrome but may be clearer in appearance.

Enable tvout (only Pi 4B)

Composite performance is disabled on the Raspberry Pi 4 by default because of the way the internal clocks are interrelated and allocated. Since composite video requires a very specific clock, setting the clock on the Pi 4 to the necessary speed means that other clocks linked to it are adversely affected, slowing down the entire device slightly. Since composite video is a less widely used feature, to avoid this device slowdown, we decided to disable it by design.

Use the enable tvout=1 option to allow composite output. This will detrimentally affect performance to a limited degree, as mentioned above.

The composite behavior stays the same on older Pi models.

Options for HDMI mode

Note for Raspberry Pi4B users: Since there are two HDMI ports on the Raspberry Pi 4B, some HDMI commands can be applied to either port. You may use the < command>:<port > notation, where the port is 0 or 1, to define the port to which the setting should be applied. If no port is defined, 0. is the default. If a port number is defined for a command that does not need a port number, the port will be ignored. For more information on the syntax and alternative mechanisms, please refer to the HDMI section on the Documentation Conditionals tab.

The Raspberrry Pi 4 has upgraded video hardware to accommodate dual 4k displays, which imposes slight limitations on the modes supported. For more info, please see here.

Secure hdmi safe

To try to boot with full HDMI compatibility, setting hdmi safe to 1 would lead to "safe mode" settings being used. This is the same as setting the parameters that follow:

Hdmi force hotplug=1

Hdmi ignore edid=0xa5000080

Configuration-hdmi-boost=4

Hdmi group=2

Hdmi mode=4

Disable overscan=0 Overscan=0

Overscan-left=24

Overscan-right=24

Top=24 overscan-top=24

Bottom=24 overscan

Hdmi ignore edid

If your display does not have an accurate EDID, setting hdmi ignore edid to 0xa5000080 allows the ignoring of EDID / display data. To ensure that it is not activated inadvertently, it needs this unusual value.

Hdmi edid file

Instead of reading it from the display, setting hdmi edid file to 1 would cause the GPU to read EDID data from the edid.dat file stored in the boot partition. There's more stuff available here.

Hdmi edid filename

You may use the hdmi edid filename command on the Raspberry Pi 4B to define the filename of the EDID file to be used, as well as which port to apply the file to. To allow EDID files, it also needs hdmi edid file=1.

For instance:

File hdmi edid file=1

Hdmi edid filename:0 = FileForPortZero.edid FileName:0 = FileForPortZero.edid

Hdmi edid filename:1 = FileForPortOne.edidid filename:1=

Hdmi force edid audio

Setting hdmi force edid audio to 1 pretends that the monitor supports all audio formats, allowing DTS / AC3 passthrough even when this is not recorded as supported.

Hdmi ignore edid audio

Setting hdmi ignore edid audio to 1 pretends that the monitor does not accept all audio formats. This means the analog audio (headphone) jack will switch to ALSA.

Hdmi force edid 3dd

Even though the EDID does not imply support for this, setting hdmi force edid 3d to 1 pretends that all CEA modes support 3D.

Init hdmi ignore cec init

During bootup, setting hdmi ignore cec init to 1 will avoid the initial active source message being sent. This prevents your Raspberry Pi from coming out of standby and channel-switching when you reboot a CEC-enabled TV.

Hdmi ignore cec-cec

Setting hdmi ignore cec to 1 pretends that the TV does not at all support CEC. There will be no CEC functions supported.

Name of cec osd name

The cec osd name command sets the device's initial CEC name. The Raspberry Pi is the norm.

Encoding hdmi pixel

The command hdmi pixel encoding forces the mode for pixel encoding. By default, the mode requested by the EDID will be used, so you do not need to change it.

Outcome of hdmi pixel encoding

Default 0 (RGB for CEA minimal, RGB for DMT full)

1 Minimal RGB (16-235)

Total 2 RGB (0-255)

3 Minimal YCbCr (16-235)

4 Absolute YCbCr (0-255)

Hdmi blanking

The hdmi-blanking command controls what happens when, using DPMS, the operating system demands that the monitor be put into standby mode to conserve power. The HDMI output is blanked but not turned off if this option is not set or set to 0. You can also set the HDMI output to shut off by setting this option to 1 to imitate the actions of other computers: the attached monitor will go into a low-power standby mode.

Setting hdmi blanking=1 will not cause the HDMI output to be turned off on the Raspberry Pi 4, as this function has not yet been implemented.

Note: When using applications that do not use the framebuffer, such as omxplayer, this feature may cause problems.

Outcome of hdmi blanking

0 The HDMI output is blanked out

1 You can turn off and blank the HDMI output

The hdmi drive

The hdmi drive command allows you to choose between performance modes for HDMI and DVI.

Outcome of hdmi drive

1 Normal mode for DVI (no sound)

2 Normal HDMI mode (if supported and allowed, sound will be sent)

Configuration hdmi boost

Configures the HDMI interface signal power. There is a minimum value of 0 and a maximum value of 11. For the original Model B and A, the default value is 2. For Model B+ and all later versions, the default value is 5.

If HDMI problems (speckling, interference) are seen, then try 7. Up to 11 can require very long HDMI cables, but values this high should not be used unless absolutely necessary.

On the Raspberry Pi 4, this option is ignored.

The hdmi group

The hdmi group command identifies either CEA (Consumer Electronics Association, the norm typically used by TVs) or DMT (Display Monitor Timings, the norm typically used by monitors) as the HDMI output group. You can use this setting in conjunction with hdmi mode.

Table of Contents

Welcome To Python

Advantages Of Becoming A Programmer

Why Choose Python?

Programming Languages

What Is A Programming Language?

Programming Languages Structure

Low And High-Level Languages

What Languages Exist For Programming?

The Python Language

Project: Hello World

Basic Types

Numeric Types

Boolean Types

String Types

Collections

Lists

Tuple

Set

Dictionaries

Flow Control

Conditional Control Structures

Iterative Control Structures

Functions

How To Define A Function In Python

Control Flow

Arguments And Parameters

Modules And Packages

Modules

Packages

Object-Oriented Programming

Elements And Characteristics Of Oop

Heritage

Polymorphism

Method Overload

Encapsulation

Functional Programming

Higher-Order Functions

Lambda Functions

Text Files

About Files

Read From A Text File

Append Text To An Existing Text File

Binary Files

Regular Expressions

Metacharacters

Sets

Regex Module

Databases

Database Peculiarities

Creating A Database Table

Sql Basics

Error Handling In Python

Syntax Errors

Exceptions

Records

Python Web Development

Contributions Of Python To Web Development

Web Frameworks For Python

Using Django

Website Project: Blog

Final Words

Introduction

Part I:

The Board

Chapter One

The Raspberry Pi

The Raspberry Pi Components

Configuring The Raspberry Pi 4

Why Pick A Raspberry Pi?

Distributions Of Linux For Raspberry Pi

Why Choose The Raspberry Pi And Not Anything Else?

Olpc, Sweets From Cotton, And Arduino

What Are The Raspberry Pi 3's Specs?

How Can I Use My Raspberry Pi 3 To Get The Most?

Chapter Two

Getting Started With The Raspberry Pi

Pi Drawbacks

Raspberry Pi Benefits

Set Up & Launch Your Raspberry Pi

Applications Of Raspberry Pi

Chapter Three

Linux System Administration

An Overview

Introducing Raspbian

Pi Safe Shutdown

Chapter Four

Setting Up The Troubleshooting

Chapter Five

Configuring The Network

Networking (Wired)

Wireless Networking

Wi-Fi2

Chapter Six

Tool For Raspberry Pi Configuration

User Account Update

Options For The Network

Options For Booting

Choices For Internationalisation

Advanced Options Section

Chapter Seven

Advanced Raspberry Pi Configuration

Part II:

Building A Media Centre Or Productivity Machine

Chapter Eight

The Pi: A Home Theatre Pc

Get The Relevant Hardware

Cases With Raspberry Pi

Raspberry Pi Add-Ons Optional

Chapter Nine

The Pi As A Productivity Machine

How Critical Is The Cloud?

Part III:

Programming The Pi

Chapter Ten

An Introduction To Scratch

Understanding The Scratch Editor: Scratch Coding Functions Like This

Programming With Scratch: An Example Of A Simple Projec

"Blue Sky" Backdrop Of Scratch

Easy Commands Introduction (15 Minutes)

Introduction To A Command Sequence (15 Minutes)

Introduction (15 Minutes) Of Iteration

Chapter Eleven

An Introduction To Python

Python Syntax Compared To Other Programming Languages

Features Of Python Programming Language

Chapter Twelve

Minecraft Pi Edition

Tips For Keeping The Process As Fluid As Possible

Part IV:

Hardware Hacking

Chapter Thirteen

Learning To Hack Hardware

A Short Soldering Guide

How To Properly Solder

Protection Checklist For Soldering

During Welding:

Chapter Fourteen

The Gpio Port

Pins From Gpio

Chapter Fifteen

The Raspberry Pi (Camera Module)

Chapter Sixteen

Add-On Hardware

Raspberry Pi Case Official

Hat Meaning

Part V:

Appendixes

Appendix A: Python Recipes

Appendix B: Camera Module Quick Reference Of Raspberry Pi

Shared Options

Raspivid Options

Appendix C: Hdmi Display Modes