Python Made Easy - Kevin Wilson - E-Book

Python Made Easy E-Book

Kevin Wilson

0,0
8,49 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.
Mehr erfahren.
Beschreibung

"Python Made Easy" is designed to transform beginners into proficient Python programmers. The journey begins with an introduction to Python, covering basic concepts and syntax that lay the foundation for your coding skills. As you progress, you'll dive into essential programming constructs like data structures, functions, and file handling.
In the second phase of the course, you'll explore more complex topics such as object-oriented programming, modules, and libraries. These sections will give you the tools to write efficient, reusable, and modular code. You'll also learn how to handle exceptions, ensuring your programs are robust and error-resistant. Special attention is given to graphical user interfaces (GUIs) and game development, making your Python skills applicable to a wide range of projects.
The final part of the course covers advanced topics like debugging, testing, and deploying Python applications. You'll also delve into web development, where you'll learn to build and deploy web applications using Python. The course concludes with valuable video resources to reinforce your learning and provide additional insights. By the end of this course, you'll have a solid understanding of Python and be ready to tackle real-world programming challenges.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 211

Veröffentlichungsjahr: 2024

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Python Made Easy

A First Course in Computer Programming using Python

Kevin Wilson

Python Made Easy

Copyright © 2024 Elluminet Press

This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed. Exempted from this legal reservation are brief excerpts in connection with reviews or scholarly analysis or material supplied specifically for the purpose of being entered and executed on a computer system, for exclusive use by the purchaser of the work. Duplication of this publication or parts thereof is permitted only under the provisions of the Copyright Law of the Publisher’s location, in its current version, and permission for use must always be obtained from the Publisher. Permissions for use may be obtained through Rights Link at the Copyright Clearance Centre. Violations are liable to prosecution under the respective Copyright Law.

Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark.

The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights.

While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein.

iStock.com/golibo, PeopleImages, ymgerman. Photo 130859010 © Kaspars Grinvalds - Dreamstime.com. Photo 103557713 © Konstantin Kolosov - Dreamstime.com. Yuri Arcurs via Getty Images

Publisher: Elluminet Press

Director: Kevin Wilson

Lead Editor: Steven Ashmore

Technical Reviewer: Mike Taylor, Robert Ashcroft

Copy Editors: Joanne Taylor, James Marsh

Proof Reader: Steven Ashmore

Indexer: James Marsh

Cover Designer: Kevin Wilson

For detailed information about how to locate your book’s resources, go to

www.elluminetpress.com/resources

Contents

Getting Started

What is Python

Installing Python

Install on Windows

Install on MacOS

Install on Linux

Setting up a Development Environment

Code Editor vs IDE

Visual Studio Code (VS Code)

PyCharm

Sublime Text

IDLE

Jupyter Notebook

Summary

Python Basics

Language Syntax

Reserved Words

Indentation

Comments

Dynamic and Duck Typing

Lab Exercises 2.1

Basic Input & Output

Displaying Output

Accepting Input

Lab Exercises 2.2

Variables and Data Types

Numeric Data Types

Strings

Boolean Data Type

Lab Exercises 2.3

Operators and Expressions

Arithmetic Operators

Performing Arithmetic

Comparison Operators

Assignment Operators

Making Expressions

Operator Precedence

Type Casting

Lab Exercises 2.4

Conditional Statements

If Statement

If…Else

Elif Statement

Nested If Statements

Lab Exercises 2.5

Iteration

For Loop

While Loop

Break and Continue Statements

Looping Over Data

Nested Loops

Iterators and Iterables

Lab Exercises 2.6

Summary

Data Structures

Lists

2D Lists

Lab Exercises 3.1

Tuples

Sets

Lab Exercises 3.2

Dictionaries

Lab Exercises 3.3

Summary

File Handling

Opening a File

Writing to a File

Reading Data

Opening a Binary File

Writing to a Binary File

Reading a Binary File

Random File Access

File Handling Methods

Data Serialisation

Pickle

JSON

Error Handling

Lab Exercises 4.1

Summary

Python Functions

Declaring Functions

Calling Functions

Lab Exercise 5.1

Function Argument Types

Positional Arguments

Default Arguments

Keyword Arguments

Variable Length

Lab Exercise 5.2

Function Scope

Decorator Functions

Lambda Functions

Recursive Functions

Lab Exercises 5.3

Exception Handling

Handling an Exception

Lab Exercise 6.1

Custom Exceptions

Lab Exercises 6.2

Summary

Object Oriented Programming

Classes & Objects

Defining a Class

Creating & Using Objects

Lab Exercise 7.1

Inheritance

Defining a Child Class

Lab Exercise 7.2

Method Overriding

Lab Exercise 7.3

Polymorphism

Encapsulation

Access Modifiers

Getters & Setters

Lab Exercises 7.4

Summary

Modules & Libraries

Commonly Used Libraries

Importing Libraries

Creating your Own Libraries

Lab Exercises 8.1

Summary

Graphics and GUIs

Using Tkinter

Creating a Window

Adding Widgets

Simple Calculator Project using Tkinter

Using PyQt

Creating a Window

Menus

Images

Buttons

Message Boxes

Text Field

Listbox

Checkbox

Labels

Simple Unit Converter Project using PyQt

Lab Exercises 9.1

Turtle Graphics

Setting up Turtle Graphics

Basic Turtle Commands

Drawing Shapes & Patterns

Lab Exercises 10.1

Summary

Game Development

Install Pygame

Creating a Window

Setting up the Game Loop

Drawing Basic Shapes

Square

Circle

Line

Loading Images

Keyboard Events

Sprites & Animation

Creating a Simple Animation

Music

Sound Effects

Invaders Project

Specification

Building the Application

Breakout Project

Lab Exercises 11.1

Summary

Debugging and Testing

Unit Testing

Pytest

Debugging

Lab Exercises 12.1

Deploying Apps

Creating a Standalone App

PyInstaller

CX_Freeze

Creating an Installer

Create App on MacOS

Lab Exercises 13.1

Summary

Web Development

Frameworks

Django

Flask

Django

Create a Virtual Environment

Install Django

Create a Project

Creating an App

Configure the App

Define Views

Create a Template

Define URL

Add URL to Project

Using Models

Lab Exercises 14.1

Summary

Video Resources

Using the Videos

File Resources

About the Author

With over 20 years’ experience in the computer industry, Kevin Wilson has made a career out of technology and showing others how to use it. After earning a master’s degree in computer science, software engineering, and multimedia systems, Kevin has held various positions in the IT industry including graphic & web design, programming, building & managing corporate networks, and IT support.

He serves as senior writer and director at Elluminet Press Ltd, he periodically teaches computer science at college, and works as an IT trainer in England while researching for his PhD. His books have become a valuable resource among the students in England, South Africa, Canada, and in the United States.

Kevin’s motto is clear: “If you can’t explain something simply, then you haven’t understood it well enough.” To that end, he has created the Exploring Tech Computing series, in which he breaks down complex technological subjects into smaller, easy-to-follow steps that students and ordinary computer users can put into practice.

Acknowledgements

Thanks to all the staff at Luminescent Media & Elluminet Press for their passion, dedication and hard work in the preparation and production of this book.

To all my friends and family for their continued support and encouragement in all my writing projects.

To all my colleagues, students and testers who took the time to test procedures and offer feedback on the book

Finally thanks to you the reader for choosing this book. I hope it helps you gain a better understanding of Python Programming.

Have fun!

Getting Started

The aim of this book is to provide a first course in the use of a methodical and effective approach to the development of computer programs using the Python Programming Language.

Chapters have been deliberately kept short with a learn by doing approach. Along the way, you’ll find various video tutorials and demonstrations you can access using the various links throughout the book.

Chapter by chapter, we’ll explore the ins and outs of Python with illustrations, worked examples, lab exercises and projects for you to complete yourself. For this purpose, we’ve included all the source code for this book in the following repository:

elluminetpress.com/python2

Have Fun!

What is Python

Python is a high-level programming language created by Guido van Rossum and first released in 1991. The name “Python” was inspired by Guido’s love for the British comedy series “Monty Python’s Flying Circus”.

Python emphasizes code readability and aims to provide a clear and concise syntax, making it easier for programmers to express concepts and ideas in fewer lines of code compared to other programming languages. There is also a comprehensive library that provides a wide range of built in modules and functions for common programming tasks. This philosophy encourages the reuse of existing code and reduces the need for developers to rely heavily on third-party libraries for basic functionalities. Over the years, Python has attracted a large community of developers who contribute to its extensive ecosystem of third-party libraries and frameworks, further expanding its capabilities.

Python is designed to be a versatile language and is widely used in web development, data analysis, artificial intelligence, scientific computing, and automation.

Installing Python

In this section, we’ll take a look at how to install the python interpreter and development environment.

Python has multiple versions available, such as Python 2.x and Python 3.x. It is recommended to install the latest stable version, which is Python 3.x. Python 2.x is no longer actively supported, and most new projects and libraries are designed for Python 3.x.

You can install python on Windows, Mac, or linux.

Install on Windows

In our lab, we’re using windows workstations, so we’ll need to install the Python Development Environment for Windows.

Open your web browser and navigate to the following website:

www.python.org/downloads/windows

From the downloads page, select the ‘executable installer’ of latest stable release.

Click ‘run’ when prompted by your browser. Or click ‘python-x.x.x-amd64.exe’ if you’re using Chrome.

Once the installer starts, make sure ‘add python 3.x to path’ is selected, then click ‘customize installation’ to run through the steps to complete the installation.

Make sure you select all the tick boxes for all the optional features. Click ‘next’.

Make sure ‘install for all users’ is selected at the top of the dialog box. Click ‘install’ to begin.

Click ‘disable path length limit’ to make sure Python runs smoothly on Windows and allow long file names.

Click ‘close’ to finish the installation.

You’ll find the Python Development Environment (IDLE) and the Python interpreter, in the Python folder on your start menu.

Install on MacOS

To install Python 3 with the Official Installer, open your web browser and navigate to the following website

www.python.org/downloads/macos

Click download python.

You’ll find the package in your downloads folder. Double click on the package to begin the installation

Run through the installation wizard. Click ‘continue’.

Once the installation is complete, you’ll find python in the applications folder in finder, or on the launch pad.

Install on Linux

If you are running a linux distribution such as Ubuntu or have a Raspberry Pi, you can install python using the terminal. You’ll find the terminal app in your applications. You can also press Control Alt T on your keyboard.

At the terminal command prompt, type the following commands. Press enter after each line.

sudo apt update

sudo apt upgrade

Type the following command to install Python.

sudo apt install python3 -y

Once the Python is installed, we need to install IDLE, the development environment. To do this, type the following command at the prompt

sudo apt-get install idle3 -y

Once installed, you’ll find IDLE in your applications.

Or you can type the following command at the prompt

idle

Setting up a Development Environment

A good development environment enhances productivity by providing features such as code editing, debugging, and testing capabilities.

There are several code editors and Integrated Development Environments (IDEs) available for Python programming. Once you have installed the python interpreter as discussed above, you should install a code editor or IDE. What you choose is personal preference and depends on the specific requirements of your project.

Try a few difference ones until you find the one that suits your needs the best.

Code Editor vs IDE

A code editor is a lightweight tool focused primarily on editing code. It provides features such as syntax highlighting, code completion, and basic code formatting. Some popular code editors are Visual Studio Code and Sublime Text.

An IDE is a comprehensive software suite that combines a code editor with additional tools and features specifically designed for software development. In addition to code editing capabilities, IDEs typically provide features like debugging, code refactoring, project management, and version control integration. Examples of popular IDEs include PyCharm, IDLE and Eclipse.

You should also consider an interactive computing environment. This is a software environment that allows you to interactively write and execute code while providing immediate feedback and results. Within this environment you can write code, run it, and see the output in real-time, facilitating an iterative and exploratory approach to programming.

Jupyter Notebook is a popular interactive computing environment that allows you to create and share documents containing live code, visualizations, and explanatory text.

Visual Studio Code (VS Code)

Visual Studio Code is a lightweight and highly customizable code editor developed by Microsoft.

code.visualstudio.com

It has excellent Python support with features such as IntelliSense which provides context-aware suggestions for functions, methods, variables, and modules as you type, helping you write code faster and with fewer errors.

VS Code also offers debugging tools and a wide range of extensions that enhance Python development experience.

PyCharm

PyCharm is a powerful IDE specifically designed for Python development. You can download the software here:

www.jetbrains.com/pycharm

It provides advanced features like intelligent code completion, refactoring tools, debugging, testing frameworks integration, and support for web development frameworks like Django and Flask.

PyCharm is available in both free Community Edition and paid Professional Edition versions.

Sublime Text

Sublime Text is a popular cross-platform code editor known for its speed and simplicity. You can download the software here:

www.sublimetext.com

It supports Python development through various community-developed packages. Sublime Text offers a distraction-free writing mode, multiple cursors, and powerful search and navigation features.

IDLE

IDLE (Integrated Development and Learning Environment) is a basic Python IDE that comes bundled with the Python installation. It provides a simple and beginner-friendly environment for writing and running Python code.

While IDLE is a convenient option for beginners or when you need a lightweight and straightforward development environment, however it lacks some advanced features and customization options compared to other IDEs. As your Python programming skills and projects become more complex, you may want to explore other IDEs mentioned earlier to leverage additional functionalities and tools for efficient development.

Jupyter Notebook

Jupyter Notebook is an open-source web-based interactive computing environment that allows users to create and share documents called notebooks. To install jupyter notebook, open the command prompt, then run the following command.

pip install jupyter

Run the following command to run Jupyter Notebook.

jupyter notebook

Notebook will pop up in your web browser. If it doesn’t open your browser and navigate to

http://localhost:8888/tree

You’ll land on the jupyter page.

Anaconda is a popular Python distribution that comes bundled with Jupyter Notebook. You can download this here.

www.anaconda.com/products/individual

Once you download the installer, run through the setup process.

You’ll find Anaconda Navigator, and Anaconda Spyder. Anaconda Navigator allows you to create and manage isolated Python environments, switch between different versions of Python, and install/uninstall packages. Spyder is an integrated development environment specifically designed for scientific Python programming and data analysis. It provides a powerful and feature-rich environment for writing, testing, and debugging Python code.

Summary

Python is a high-level programming language created by Guido van Rossum in 1991, known for its readability and concise syntax.Python has a comprehensive library that includes built-in modules and functions for common programming tasks, reducing the need for third-party libraries.Python is versatile and widely used in web development, data analysis, artificial intelligence, scientific computing, and automation.Code editors such as Visual Studio Code and Sublime Text offer lightweight tools for editing code.Integrated Development Environments (IDEs) such as PyCharm, IDLE, and Eclipse provide additional features like debugging, code refactoring, and project management.Visual Studio Code is recommended in the book, with excellent Python support, debugging tools, and a wide range of extensions.PyCharm is a powerful IDE specifically designed for Python development, available in both free and paid versions.Sublime Text is a popular cross-platform code editor with support for Python development through community-developed packages.IDLE is a basic Python IDE bundled with the Python installation, suitable for beginners or lightweight development but lacking advanced features.Jupyter Notebook is an open-source web-based interactive computing environment that allows users to create and share documents called notebooks. Anaconda is a popular Python distribution that comes bundled with Jupyter Notebook.

Python Basics

Python is an interpreted programming language, meaning the source code is executed line by line at runtime without the need for prior compilation into machine code.

When you run a Python program, the interpreter translates the source code into bytecode which is then executed by the Python Virtual Machine (PVM). The PVM is responsible for executing the bytecode and managing the memory, objects, and other runtime aspects of the Python program.

Python’s appeal lies in its simplicity and readability. The syntax emphasizes code clarity, using indentation rather than traditional braces or keywords to delimit blocks of code.

For this chapter, you’ll need to download the source code files from:

elluminetpress.com/pyb

You’ll also find various video demos and tutorials.

Language Syntax

Syntax refers to the set of rules and structure that define the correct arrangement and usage of elements in a programming language. The rules specify how the code should be structured, including the order and placement of keywords, operators, variables, and other elements. Adhering to the syntax rules is crucial because even small deviations can result in code that produces syntax errors.

Reserved Words

Reserved words, also known as keywords, are words that have special meaning and are reserved for specific purposes. These words cannot be used as variable names or other identifiers because they are already used by the language itself.

Indentation

Python uses indentation to define code blocks instead of using braces or keywords like “begin” and “end” as in other languages. Code blocks are usually indented using spaces or tabs (eg use four spaces per indentation level).

Consistent indentation is crucial in Python because it determines the grouping and hierarchy of code. It is important to note that mixing spaces and tabs for indentation can lead to errors, so it’s best to choose one and stick to it. In the example below, notice how the indentation is used to define the code blocks within the greet function.

The lines of code inside the if and else blocks are indented, indicating that they are part of those blocks.

The line that prints “Nice to meet you” is indented at the same level as the if and else blocks, indicating that it is executed after the conditional statements.

See ‘conditional statements’ later in this chapter for more information on if-else statements.

Comments

Comments are used to provide explanatory notes or documentation within the code. They are ignored by the Python interpreter and do not affect the execution of the program.

Comments help explain the purpose and functionality of code. They provide additional information for other programmers (and yourself) to understand what the code does, how it works, and why certain decisions were made during its implementation. Well-placed comments can significantly enhance the clarity and readability of code.

You can add single line comments using hash #

# This is a single-line comment

Or you can add multi line comments. To do this enclose your comments in triple quotes “““

”””

This is a multi-line comment.

It can span across multiple lines

and is enclosed by triple quotes.

”””

Comments also facilitate code maintenance and collaboration. When multiple developers work on a project, comments help communication and understanding of each other’s code. They provide a way to leave notes, suggestions, or explanations for future modifications or bug fixes, making it easier for developers to work together effectively.

Comments are often used to temporarily disable or comment out blocks of code during development or debugging. This can be useful when testing alternative code paths, isolating issues, or removing sections of code without permanently deleting them. However, it’s important to avoid leaving commented-out code in production codebases, as it can confuse and clutter the codebase over time.

Many Python projects and organizations follow specific commenting guidelines or style guides to ensure consistency across the codebase.

Some popular style guides, such as PEP 8 (Python Enhancement Proposal), provide recommendations for commenting conventions, including the use of sentence case or imperative mood for comments, appropriate line lengths, and formatting guidelines. You can find more information this here:

peps.python.org/pep-0008

Lab Exercises 2.1

What is syntax in programming, and why is it important to adhere to syntax rules?What are reserved words or keywords in Python? Why can’t they be used as variable names or identifiers?Identify three reserved words in Python and explain their purpose.How does Python use indentation to define code blocks? Why is consistent indentation important?Write a code snippet that demonstrates the use of indentation to define code blocks in Python.What is the purpose of comments in programming? How do they enhance code clarity and readability?How can comments facilitate code maintenance and collaboration in a team setting?Why would you temporarily disable or comment out blocks of code during development or debugging? What should be avoided when using commented-out code in production codebases?

Basic Input & Output

Basic input and output operations allow your program to interact with the user, read data from external sources, and display results. In Python, there are several ways to handle input and output.

Here, we’ll take a look at the print() function and the input() function.

Displaying Output

The print() function is commonly used to display output to the console. You can pass one or more arguments to the print() function.

print(“This is some text to print”)

Or you can concatenate different variables to print to the console.

print(“Name: “ + name + “, Age: “ + str(age))



Tausende von E-Books und Hörbücher

Ihre Zahl wächst ständig und Sie haben eine Fixpreisgarantie.