Introduction to Python for Beginners PDF

Document Details

CrisperAnecdote

Uploaded by CrisperAnecdote

2024

Christian Thompson

Tags

python programming beginner's guide introduction to programming computer science

Summary

This introduction to Python is a beginner-friendly guide for those new to programming. Topics covered include variables, functions, loops, and graphical user interfaces. Designed by Christian Thompson AKA TokyoEdtech, the book contains video tutorials.

Full Transcript

TokyEdtech’s Introduction to Python for Beginners Christian Thompson AKA TokyoEdtech Feb 2024 ii Contents Chapter 0: Introduction 1...

TokyEdtech’s Introduction to Python for Beginners Christian Thompson AKA TokyoEdtech Feb 2024 ii Contents Chapter 0: Introduction 1 Discord.......................................... 1 What this Book is and What it is Not........................... 1 How this Book was Created............................... 2 Creative Commons Licensed............................... 2 Chapter 1: Welcome to Python 3 Why Python?....................................... 3 Hello World in Three Different Languages........................ 3 Java........................................ 3 JavaScript..................................... 4 Python....................................... 4 Downloading and Installing Python............................ 4 Instructions..................................... 5 IDLE........................................ 5 Alternative Editors................................. 5 Online Coding Environments............................ 7 Running Hello World................................... 7 Commenting Your Code................................. 8 Chapter 2: Printing with Variables 11 Escape Characters.................................... 11 Printing Without the Newline Character...................... 12 “Printing” Sound..................................... 12 Variables......................................... 13 Variable Naming Rules.................................. 14 Boolean Naming.................................. 15 Constant Values.................................. 15 Printing With Variables................................. 15 Casting (Converting Between Variable Types)...................... 16 Casting Commands................................. 16 Changing the Text Color................................. 17 Why Data Types?.................................... 17 Video Tutorials...................................... 18 iii iv CONTENTS Chapter 3: Using Variables - Math and Strings 19 Math and Variables.................................... 19 Add........................................ 19 Subtract...................................... 20 Multiply...................................... 20 Divide....................................... 20 Power....................................... 20 Modulus...................................... 21 Incrementing and Decrementing............................. 21 Incrementing.................................... 21 Decrementing................................... 22 Combined Assignment Operators............................. 22 Math Module....................................... 23 math.pow...................................... 23 math.sqrt...................................... 23 Other Useful Math Module Methods........................ 24 Math Module Constants.............................. 24 More About Strings................................... 24 String Concatenation................................ 25 String Multiplication................................ 26 String Methods................................... 26 String Length.................................... 26 Slices........................................ 27........................................... 29 Chapter 4: Conditionals 31 Basic if Statement.................................... 31 Types of Comparisons.................................. 32 and/or.......................................... 32 else............................................ 33 elif............................................ 33 Combining if, elif, and else................................ 34 Determining If a String Contains a Particular Character................. 34 Determining if a Number is Even or Odd......................... 35 Extension Activity.................................... 35 Video Tutorial...................................... 35 Chapter 5: Loops 37 For Loops........................................ 37 Counting Up.................................... 37 Counting Up by Twos............................... 38 Counting Down.................................. 38 Traversing a String................................. 39 Counting...................................... 40 Variable Names and Readability.......................... 41 CONTENTS v While loops....................................... 41 Counting Up.................................... 41 Counting Up by Twos............................... 42 Counting Down.................................. 43 Traversing a String................................. 44 Combining Loops with Conditionals........................ 44 End a Loop Early using Break.............................. 45 Continuing a Loop.................................... 45 While True Loop..................................... 46 Extension Activity.................................... 46 Video Tutorial...................................... 47 Chapter 6: Functions 49 Basic Structure...................................... 49 Sending Values to a function............................... 50 Returning values from a function............................. 50 Scope.......................................... 51 Accessing A Global Variable from Inside a Function................ 51 Changing A Global Variable from Inside a Function................ 51 Combining Conditionals, Loops, and Functions...................... 53 Extension Activity.................................... 53 Video Tutorial...................................... 53 Chapter 7: Lists and Tuples 55 Basic Structure...................................... 55 List Indicies....................................... 55 Iterating Through a List................................. 56 Iterating with a For Loop.............................. 56 Iterating with a For Each Loop........................... 56 Determining If a Value is in a List............................ 57 Slices........................................... 57 List Methods....................................... 58 More About Lists..................................... 59 Len......................................... 59 Sum........................................ 60 Calculating the Average of a List.......................... 60 Tuples.......................................... 60 List Comprehensions................................... 61 Capitalize All Words in a List........................... 62 Video Tutorial...................................... 62 Chapter 8: Dictionaries 63 Basic Structure...................................... 63 Accessing the Keys and Values.............................. 64 Iterate through a Dictionary............................... 64 vi CONTENTS Iterate through the Keys and Print the Values.................... 65 Notes on Dictionaries.................................. 65 Keys Must Be Unique............................... 65 Lists Cannot Be Used as a Key but Tuples Can................... 66 Video Tutorial...................................... 66 Chapter 9: Classes 67 Basic Structure...................................... 67 Adding Methods to a Class................................ 68 Basic Inheritance..................................... 69 Overriding Methods................................... 70 Video Tutorial...................................... 71 Chapter 10: More About Classes 73 Class Variables and Methods............................... 73 Public, Protected, and Private.............................. 74 Public....................................... 74 Protected...................................... 74 Private....................................... 75 Chapter 11: User Input 79 Basic Structure...................................... 79 Input Statement and Data Types............................. 79 Validating Input..................................... 80 Asking for Multiple Values................................ 80 Video Tutorial...................................... 81 Chapter 12: Graphical User Interfaces with Tkinter 83 Getting Started...................................... 83 Temperature Converter.................................. 84 Creating a Widget................................. 85 Adding the Widget to Our Window......................... 86 Adding the Rest of the Widgets.......................... 86 Adding the Celsius to Fahrenheit Function..................... 87 Extension Activity.................................... 88 Video Tutorial...................................... 89 Chapter 13: Turtle Module 91 Getting Started...................................... 91 Basic Turtle Methods................................ 92 Moving the Turtle................................. 92 Using Loops and Functions................................ 95 Adding a Loop................................... 97 Adding a Function................................. 97 Using Loops and Functions Part 1............................ 98 CONTENTS vii Using Loops and Functions Part 2............................ 100 Cleaning Up the Function Part 1............................. 100 Cleaning Up the Function Part 2............................. 101 Extension Activity.................................... 102 Video Tutorial...................................... 102 Chapter 14: Miscellaneous Tips and Tricks 103 OS Module........................................ 103 Playing Sounds...................................... 103 Windows...................................... 104 Mac........................................ 104 Linux........................................ 104 Time Module....................................... 104 Pausing the Program Execution using time.sleep()................. 105 Saving and Loading Data with the Pickle Module.................... 105 Saving Data.................................... 105 Loading Data.................................... 106 Chapter 15: Code Organization and Importing 107 One File Code Organization............................... 107 Organizing with Functions................................ 108 Importing Functions from a Separate File........................ 109 Namespace and Importing................................ 110 from filename import *............................... 110 import filename.................................. 111 Video Tutorial Links 113 Beginning Python.................................... 113 Python Turtle Module.................................. 113 Python Graphical User Interfaces using tkinter...................... 113 Python Game Programming Concepts.......................... 114 Python Game Programming............................... 114 Live Coding Tutorials.................................. 114 Extension Activity Solutions 117 Chapter 3: Conditionals Extension Activity........................ 117 Chapter 4: Loops Extension Activity........................... 117 Chapter 5 Functions: Extension Activity......................... 118 Chapter 11: GUI Extension Activity........................... 118 Chapter 12: Turtle Module Extension Activity...................... 119 viii CONTENTS Chapter 0: Introduction Welcome to Introduction to Python Coding with TokyoEdtech! My real name is Christian, but I’ve been living in Japan and teaching here since 2003 - hence, TokyoEdtech. I am a middle school and high school computer science teacher and am currently enrolled in GA Tech’s Online Master of Science in Computer Science program. This book is based on what I teach my students in my Introduction to Computer Science with Python class - it started out as a nice set of notes and review guide for them, but evolved into something bigger. I love coding, and want to share that passion with as many people as possible! You may know me from my YouTube channel, my Twitter account (@tokyoedtech), my Instagram account (tokyoedtech), or my website (https://christianthompson.com/). You can also find me on GITHUB at https://github.com/wynand1004/. A lot of what you’ll see in this book can also be found on my YouTube channel – so if you are interested in learning more, subscribe to me there, and follow me on Twitter and/or Instagram. There is a list of videos near end of this book in the Video Tutorial Links chapter and there are links to videos throughout the book as well. Discord In addition to my YouTube channel, Twitter account, Instagram account, and website, you can also connect with me on my Discord server here: https://discord.gg/A7qrBg73AK What this Book is and What it is Not This book is aimed at helping beginners learn the basics of the Python programming language along with a few extras. While it does cover most major Python coding and data structures, it is limited in scope so that beginners do not get overwhelmed with information. It is not intended as a complete guide to everything Python has to offer. More advanced topics such as graphical user interfaces and basic graphics coding with the turtle module are covered as well. Each of these topics could easily take up an entire book themselves - they are introduced here to give beginning coders a taste of what is possible and to encourage them to go on to learn more. 1 2 CHAPTER 0: INTRODUCTION How this Book was Created This book was created using all free and open source software including: The Joplin note-taking app: https://joplinapp.org/ The Pandoc document converter: https://pandoc.org/ The Ubuntu Linux operating system: https://ubuntu.com/ The Geany coding editor: https://www.geany.org/ The GIMP photo editor: https://www.gimp.org/ Creative Commons Licensed Figure 1: cc_license.png This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License. You may use it, and any information in it for any purpose (even commercial), as long as you attribute the source (me), and allow others to do the same. Chapter 1: Welcome to Python NOTE: If you just want to get started as quickly as possible, check out my video, Getting Started with Python for Complete Noobs!. It goes over a lot of what I will talk about in at the start of this chapter. Why Python? There are many programming languages in the world. Popular languages include classic ones such as Java, JavaScript, and C++ along with newer languages such as Rust, Kotlin, and Swift. Students always wonder what language they should learn. As a beginner, the specific language is less important than learning coding concepts such as conditionals, loops, functions, and classes. Every language has its strong points and weak points. That said, Python is, in my opinion, the best language for beginners to start with. It is relatively simple in its syntax, and is flexible enough for beginners to not get caught up in coding minutiae. Another strong point of Python is that it is cross-platform. This means that it runs on Linux, MacOS, and Windows. For the most part, programs written on one platform will work on another; however, there are minor differences you need to take into account, especially when it comes to file access. You can learn more about Python and the history of Python here: https://en.wikipedia.org/wiki/Py thon_(programming_language) Hello World in Three Different Languages Traditionally, beginning programmers start with the Hello World program, which prints the words Hello World! on the screen. Here it is in three different languages: Java, JavaScript, and Python. Java public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); 3 4 CHAPTER 1: WELCOME TO PYTHON } } As you can see, there is a lot of code there just to print something on the screen. This is because Java enforces what is known as Object Oriented Programming (OOP) style on the programmer – this is a powerful tool, but confusing for beginners. Python allows you to use OOP, but it is not required. We will cover the basics of OOP later in this book in later chapters of this book. JavaScript In JavaScript, there are several different ways to print (or show) information to a user. // Print to the console console.log("Hello World!"); or // Show a popup window alert("Hello World!"); or // Write text to a webpage document.write("Hello World!") As you can see, JavaScript is simpler than Java, but because it began as a scripting language for web pages, there can be a lot of complexity when dealing with web browsers – this complexity is confusing for beginners. Note: JavaScript has grown far beyond its origins as a scripting language for web pages and can be found almost everywhere from servers, to games, to apps. Python print("Hello World!") As you can see, Python is the easiest of the three. Easy is good. Let’s stick with that. Note: If you’re interested in seeing how other languages do Hello World, click this link: Hello World on Rosetta Code Downloading and Installing Python Python, the programming language, needs to be downloaded to your computer before you can use it. Note, some systems may already have it installed - however, it may be an earlier version. So first, let’s make sure we have the latest version. DOWNLOADING AND INSTALLING PYTHON 5 Instructions 1. Go to Python website: https://www.python.org/downloads/ 1. You should see a button that says “Download Python 3.X.X”. As of the writing of this book, the current Python version is 3.11.1. 2. Click the button and it should download the correct version for your system 3. Install it IDLE Once you install Python, a program called IDLE should open up. IDLE is the default editor that comes with Python. You are welcome to use this; however, I would recommend something a little more robust. Alternative Editors Geany I am a big fan of Geany. It is free, open source, cross-platform, and very lightweight compared to most other options. It supports over 50 different coding languages and is translated in to over 40 human languages. Here is what Geany looks like (in dark mode) on Ubuntu Linux: You can download it here: https://www.geany.org/download/releases/. Be sure to download the correct version for your operating system. VIDEO: If you want to learn more about Geany, check out this video introduction: https://youtu.be /quemIgUn4C8 PyCharm PyCharm, by JetBrains, is a full-featured Python editor and coding environment. There is a paid version and free community version available as well. You can download it here: https://www.jetbrains.com/pycharm/download/. Your browser should auto-detect the correct version for your operating system. Visual Studio Code Visual Studio Code, from Microsoft, is a free feature-packed editor you can use to code in Python (and a huge number of other languages). I like Visual Studio Code, but find it has a pretty steep learning curve, especially for beginners. You can download it here: https://code.visualstudio.com/download. Be sure to download the correct version for your operating system. 6 CHAPTER 1: WELCOME TO PYTHON Figure 2: IDLE.png RUNNING HELLO WORLD 7 Figure 3: geany_ide.png Other Alternatives There are any number of alternatives to the editors listed above. Feel free to play around and find the one that best suits your needs. For this book, all examples shown will be using the Geany editor running on the Ubuntu Linux operating system. Online Coding Environments If, for some reason, you are unable to install Python and an editor, there are a number of fully online alternatives. These online coding editors are useful for learning basic programming, but may or may not work with more advanced features such as GUIs, or turtle graphics. REPLIT REPLIT is a great online editor. To use it, you simply go to https://replit.com and create a free account. Once you do so, click Create, choose Python (or Python with Turtle) as your template and you should be good to go. Running Hello World Once you’ve downloaded and installed both Python and an editor such as Geany, or signed up for an online editor such as REPLIT, it’s time to try writing your first line of code. Since we talked about it 8 CHAPTER 1: WELCOME TO PYTHON Figure 4: repl_it_hello_world.png up above, let’s go ahead and give Hello World! a try. So, open your editor and type the following: print("Hello World!") IMPORTANT: Save your file with the.py extension. In my case I saved my file as hello_world.py. Be careful not to add an extra space after.py as this may cause your programming editor to not recognize your file as a Python file. Your screen should look something like this (depending on your system and settings): Then click the Execute button which looks like this: If all goes well, you should see a popup window and the following: Hello World! If you don’t see this, there is likely something wrong with your computer set up. Since everyone’s system is different, it is hard to tell you what to do at this point, except to try reinstalling Python and Geany and hoping for the best, or finding someone knowledgeable such as a friend, family member, or teacher to help you get started. Commenting Your Code In Python, any lines that starts with a # is a comment. Comments are ignored by Python - they are there only so programmers can describe what their code is doing – both to remind themselves and as a guide to other programmers working on their code. COMMENTING YOUR CODE 9 Figure 5: geany_hello_world.png Figure 6: geany_execute.png 10 CHAPTER 1: WELCOME TO PYTHON As a beginner, commenting your code will help you to cement your understanding of what your code does, and to help you review later as you learn more and more. Example # This is a comment. # This is another comment. # Good things come in threes. If you typed this code into Python and ran it, there would be no output. Chapter 2: Printing with Variables Welcome to Chapter 2. Congratulations on making it this far! As you saw in Chapter 1, printing text to the screen in Python is very easy. However, there is quite a lot more we can do with printing. To review, printing to the screen is rather straightforward - you simply type the text you want to see between the quotation marks between the parentheses after the print method. Example print("This is my program. There are many like it,\ but this one is mine.") Output This is my program. There are many like it, but this one is mine. The print method shows output on the terminal screen. Once you learn to make GUIs (Graphical User Interfaces) in Chapter 11, you will no longer need to use the print method. Escape Characters Escape characters are special characters that appear differently on the screen than they appear when you type them in your code. Typically they are used to print characters that are typically part of the code itself, or to change the text color. Escape characters are preceded by a backslash like so \. Example # Print a tab print("Hello\tWorld!") # Print a newline character print("Hello\nWorld!") # Print a quotation mark print("Hello \"World!\"") # Print a backslash print("Hello \\World!\\") 11 12 CHAPTER 2: PRINTING WITH VARIABLES Output Hello World! Hello World! Hello "World!" Hello \World!\ Printing Without the Newline Character Try the following: print("2 + 2 = ") print("4") Output 2 + 2 = 4 Notice that each print method adds a newline at the end by default. Sometimes this is what you want to happen, while other times this is not what you want to happen. If you want to keep printing on the same line rather than jumping down to the next line, try the following instead: print("2 + 2 = ", end="") print("4") Output 2 + 2 = 4 The end = "" part changes the end of the printing output from a newline character to nothing (as nothing is between the quotation marks). Note, you can also use two apostrophes instead, like so: end = '' “Printing” Sound There is one other escape character you may find useful – it is used to play a sound. This is a holdover from the old teletype days. print("\a") Output Note: Nothing will be printed, but you should hear a sound from your computer – the exact sound will be determined by your computer’s settings. VARIABLES 13 If you are using Linux (and you should be), you may have to enable the terminal sound by opening the terminal, choosing preferences, choosing your profile, and ticking the “Terminal bell” checkbox as shown below. Figure 7: linux_preferences_sound_terminal_bell.png Variables Variables are used to store information for later use. For example, you might want to keep track of the score in the World Cup like so: team_a_score = 0 team_b_score = 0 # Team A scores a goal team_a_score = 1 Variables come in types such as integer, float, boolean, or string. The meaning of these data types is explained below. The reason why variables have a type is a bit technical, but is explained down below in the “Why Data Types?” section. Here are some examples of variables: 14 CHAPTER 2: PRINTING WITH VARIABLES # Integer the_answer = 42 # Float gigawatts = 1.21 # Boolean is_thirsty = True # String title = "Casablanca" An integer is a whole number (positive or negative). A float is a number with a decimal in it (positive or negative). A boolean is a value that is either True or False. A string is a text value. Type Example integer 2112 float 279.5 boolean True string “OMG!” Try the following: the_answer = 42 print(f"The answer is to Life, the Universe, and Everything\ is {the_answer}.") Important: It is important to understand that 42 as an integer is completely different to “42” as a string. See the section down below called “Why Data Types?” for an explanation of why this is so. Output The answer is to Life, the Universe, and Everything is 42. Variable Naming Rules If you look at the example variables from above, you may notice some similarities. the_answer = 42 gigawatts = 1.21 is_thirsty = True title = "Casablanca" As you can see, all the variables are lower case. Variables with two words in them are separated by underscores (this is referred to as snake case). Another rule which you don’t see here is that variables may not start with a number, or contain special characters such as !, “, or #. PRINTING WITH VARIABLES 15 You can learn more about Python’s naming conventions here: https://peps.python.org/pep-0008/#na ming-conventions Boolean Naming Boolean values are limited to True and False. So, as you can see in the example above, the variable name is_thirsty is used. This is a common boolean naming convention, since someone is either thirsty or not. Here are a few more examples: has_permission = True is_rich = False can_enter = True Constant Values A constant value is something that does not change. It could be a physical constant such as the speed of light, or a constant related to the program or system, for example, the width of the screen. For constant values, Python uses all capital letters like so: SPEED_OF_LIGHT = 299792458 SCREEN_WIDTH = 800 PYTHON_VERSION = "3.11.0" Printing With Variables Printing in Python has evolved over the years. For example in Python 2.x, print was a statement, and not a method. print "In Python 2.x print is a statement." In Python 3.x print is a method. You have 4 ways to use variables in printing: Example title = "Casablanca" print("My favorite movie is " + title + ".") print("My favorite movie is %s." %title) print("My favorite movie is {}.".format(title)) print(f"My favorite movie is {title}.") Output My favorite movie is Casablanca. My favorite movie is Casablanca. My favorite movie is Casablanca. My favorite movie is Casablanca. 16 CHAPTER 2: PRINTING WITH VARIABLES Note: f-strings were added in Python 3.6. Note: There is another data type called complex which combines real numbers and imaginary num- bers. You can learn more about it here: https://docs.python.org/3/library/functions.html#complex Casting (Converting Between Variable Types) There will be times when you will need to convert a variable from one type to another. One common place is with the input statment. Take for example, the following code: x = input("x: > ") print(x * 2) Output x: > 5 55 Note how the code above does not cause an error, but rather, it prints an unexpected value, 55. So the question is, what is going on here? In Python, if you multiply an integer or a float, it will return a number. However, if you multiply a string, it repeats that string the number of times you multiplied it by. So, in the example above, the user entered 5. The input statement always returns a string, mearning that the 5 was a string, and not an integer. Please see the section at the end of this chapter called “Why Data Types?” for a more detailed explanation of what is going on. The fix for this is very simple - we need to cast the string to an integer (convert from a string to an integer) like so: x = input("x: > ") # Convert the string x to an integer x = int(x) print(x * 2) Output x: > 5 10 Casting Commands The following commands can be used to cast to another data type. Note, if the information is not compatible, there will be an error. For example, we cannot cast the string “A” to an integer. Example Meaning x = int(x) Cast x to an integer x = float(x) Cast x to a float CHANGING THE TEXT COLOR 17 Example Meaning x = str(x) Cast x to a string Changing the Text Color It is possible to change the color of the text that is being printed on the screen by using more escape characters, in this case, ANSI Color Codes. Basic ANSI Color Codes Color Code Black \u001b[30m Blue \u001b[34m Cyan \u001b[36m Green \u001b[32m Magenta \u001b[35m Red \u001b[31m Yellow \u001b[33m Reset \u001b[0m Note, reset is not a color, but rather it resets the colors back to your terminal default. Here is an example that prints different colors on the screen: # Define the color and reset constants RED = "\u001b[31m" GREEN = "\u001b[32m" BLUE = "\u001b[34m" RESET = "\u001b[0m" print(f"Roses are {RED}red{RESET}.") print(f"Violets are {BLUE}blue{RESET}.") print(f"I like {GREEN}green{RESET} eggs and ham.") print("Because Sam I am.") Output The following website has a ton of information about ANSI color codes and was the source I used for the table up above: https://www.lihaoyi.com/post/BuildyourownCommandLinewithANSIescapecodes.html Why Data Types? Data types are related to how the information is stored in your computer’s memory. As you may or may not know, information is stored in the computer’s memory using binary numbers – numbers with just zeros and ones. So, for example: 18 CHAPTER 2: PRINTING WITH VARIABLES Figure 8: ansi_color_example.png 1 = 00000001 2 = 00000010 3 = 00000011 … 255 = 11111111 Integers are stored this way in the computer’s memory. However, let’s say we want to determine if a number is positive or negative – we need to use a bit to determine that information. So, instead of 11111111 representing 255, it could represent +127 while 01111111 could represent -127. Floating point numbers are stored as binary numbers – it’s actually a bit complex, at least to me. Check out this video for more information: https://www.youtube.com/watch?v=1GSjbWt0c9M Booleans are the easiest to represent – one bit in a memory address in the computer somewhere is used to represent the value of a particular boolean. If that value is 1, then the boolean is True, if it is 0, then the boolean is False. Strings use up quite a bit of memory, at least compared to the other types mentioned above. For strings, each character needs to be represented. In the old days, a systems called ASCII was invented – it was a standardized encoding method for characters. However, it did not have encoding for other languages such as Korean, Chinese, and Japanese which have thousands of characters or character combinations. So, an extension of ASCII called UTF-8 was invented. Anyhoo, to encode TokyoEdtech, you would need to store the following ASCII numbers in memory: 84 111 107 121 111 69 100 116 101 99 104 \0 T o k y o E d t e c h END Note: The \0 means the string has come to an end. Video Tutorials Here are some links to some introductory videos I did on this topic: Introduction, Comments, and Printing: https://youtu.be/rxSyXBq9zq0 String Variables: https://youtu.be/IOSOCAIc0H8 Integers and Floats: https://youtu.be/B2OoMUcXRcI Chapter 3: Using Variables - Math and Strings In this unit we will look a little more at how we can perform math operations using integers and floats. We will also see how we can use strings and learn about the various string methods that are available. Math and Variables It goes without saying that programming languages give you the ability to do math operations on variables and numbers. To do this, we use various math operators. The common math operators are +, -, *, /, **, and %. Here is a table explaining what each operator does. Below you will see example code for each operator. Operator Meaning + Add - Subtract * Multiply / Divide ** Power % Modulus Add # Add x = 5 # Add 3 to x x = x + 3 print(x) Output 8 19 20 CHAPTER 3: USING VARIABLES - MATH AND STRINGS Subtract # Subtract x = 5 #Subtract 3 from x x = x - 3 print(x) Output 2 Multiply # Multiply x = 5 # Multiply x by 3 x = x * 3 print(x) Output 15 Divide # Divide x = 5 # Divide x by 3 x = x / 3 print(x) Output 1.6666666666666667 Power # Power x = 5 # Raise x to the second power x = x ** 2 print(x) Output INCREMENTING AND DECREMENTING 21 25 Modulus # Modulus x = 5 # The modulus gives the remainder of a division operation # In this example, 5 % 2 means # 5 divided by 2 equals 2 with a remainder of 1 x = x % 2 print(x) Output 1 Incrementing and Decrementing It is common to add one to integers (and floats) and to subtract one from integers (and floats). You saw how to do this above. However, there is also a shortcut method for doing so. Incrementing Incrementing is just a fancy way to say “add one”. x = 1 # Add one to x x = x + 1 print(x) Output 2 Shortcut Version There is a shorter more handy way to increment like so: x = 1 # Add one to x x += 1 print(x) Output 22 CHAPTER 3: USING VARIABLES - MATH AND STRINGS 2 Note that the output has not changed. Be careful, beginners often make the mistake of typing x =+ 1 instead. This will set the value of x to 1. Decrementing Decrementing is just a fancy way to say “subtract one”. x = 1 # Subtract one from x x = x - 1 print(x) Output 0 Shortcut Version There is a shorter more handy way to increment like so: x = 1 # Subtract one from x x -= 1 print(x) Output 0 You can see that the output has not changed. Be careful, though, as beginners often make the mistake of typing x =- 1 instead. This will set the value of x to -1. Note: In other programming languages, such as Java and C++, you can increment by using the ++ operator and decrement using --. However, this does not work in Python. Combined Assignment Operators As you saw above, we can write our code in a more compact way by combining our operators with the equals sign. Here is a chart showing the combined assignment operators: Regular Combined x=x+2 x += 2 x=x-2 x -= 2 x=x*2 x *= 2 MATH MODULE 23 Regular Combined x=x/2 x /= 2 x = x ** 2 x **= 2 x=x%2 x %= 2 Math Module In Python, there are modules that add functionality to Python. These modules are not part of the core Python language, but are provided to enhance its functionality. Python comes with many modules preinstalled (and you can download and install others). One such module is the math module which provides a number of math functions for you to use. math.pow # To use a module, you must import it first import math x = 2 # This returns x to the power of 3 # It is equivalent to y = x ** 3 y = math.pow(x, 3) print(y) Output 8 math.sqrt Another useful math function is sqrt which returns the square root. x = 16 # Take the square root of x # It is equivalent to y = x ** 0.5 y = math.sqrt(x) print(y) Output 4 24 CHAPTER 3: USING VARIABLES - MATH AND STRINGS Other Useful Math Module Methods Method What it Does math.sin(x) sine x (in radians) math.cos(x) cosine x (in radians) math.tan(x) tangent x (in radians) math.degrees(x) convert x from radians to degrees math.radians(x) convert x from degrees to radians Math Module Constants The math module also has predefined constants for you to use. Here are a few common ones: Value Meaning math.pi PI math.e Euler’s number math.inf Infinity import math # Math constants print(math.pi) print(math.e) print(math.inf) Output 3.141592653589793 2.718281828459045 inf Note: The output (number of decimal places) may differ depending on your system settings. To learn more about the math module and its methods and constants click this link: https://docs.pyt hon.org/3/library/math.html More About Strings Strings are one of the most important Python data types. No matter what type of program you create, you will likely have to deal with strings. As a reminder, strings are information in text format. Here are some example strings: favorite_movie = "Casablanca" firstname = "Christian" wednesday_in_japanese = "suiyoubi" MORE ABOUT STRINGS 25 String Concatenation String concatentation is a fancy way to say combining strings. You can combine strings by using the + operator. firstname = "Robert" lastname = "Smith" # Concatentate firstname and lastname fullname = firstname + lastname print(fullname) Output RobertSmith Notice that there is no space between Robert and Smith. If you want a space, you need to add one like so: fullname = firstname + " " + lastname Note: Alternatively, you can use f-strings here as well. For example: fullname = f"{firstname} {lastname}" String Concatenation with Integers and Floats As mentioned previously, integers, floats, and strings are different data types. Although when printed they look the same to you, to the computer they are very different. This was explained in the previous chapter. Try the following code: the_answer = 42 print("The answer is " + the_answer + ".") Output Traceback (most recent call last): File "string_concatenation.py", line 2, in print("The answer is " + the_answer + ".") TypeError: can only concatenate str (not "int") to str This results in a TypeError since you cannot combine an int and a string. To fix this error, you need to convert the int to a string like so: the_answer = 42 print("The answer is " + str(the_answer) + ".") Alternatively, you can use one of the other printing methods we learned previously - for example, using an f-string automatically converts the given data type to a string. 26 CHAPTER 3: USING VARIABLES - MATH AND STRINGS String Multiplication We can also “multiply” strings by using the * operator. If you multiply a string, it is repeated like so: name = "Yeah" print(name * 3) Output YeahYeahYeah String Methods Python has a number of built-in string methods you can use. Here is a partial list of string methods you might find useful. title = "pIctures OF yoU" # Return the string with the first letter capitalized print(title.capitalize()) # Return the string as a title (each word capitalized) print(title.title()) # Return the lowercase string print(title.lower()) # Return the uppercase string print(title.upper()) # Note, the original string is unchanged print(title) Output Pictures of you Pictures Of You pictures of you PICTURES OF YOU pIctures OF yoU It is important to note that the original string is unchanged - this is because strings are what is known as immutable. String Length Sometimes it is very useful to know the length of a string. The length is the number of characters in the string. Note that spaces count as one character. MORE ABOUT STRINGS 27 title = "pIctures OF yoU" print(len(title)) Output 15 This is just a small sampling of the various string methods. To learn more, click the following link: https://docs.python.org/3/library/stdtypes.html#string-methods Slices A slice is just what it sounds like - you take a string and slice a part of it out. In other programming languages, this is often referred to as a substring. Slices require you to use the index of a particular character as starting and end point. Here is an example. song = "Push" print(song) Output P Important: The first letter has an index of 0, not 1. So, for the word Push we have the following letter and index combinations: Letter P u s h Index 0 1 2 3 Important The index of the very last letter is always the length of the string minus 1. In this case, Push has a length of 4. The index of h is 4 - 1, which equals 3. Negative Indices In most programming languages, it is not possible to have a negative index for a string. However, in Python this is possible. So, for the word push, we would have the following: Letter P u s h Index 0 1 2 3 Index -4 -3 -2 -1 So, for any string, the index of the last letter can be obtained by one of the following methods: 28 CHAPTER 3: USING VARIABLES - MATH AND STRINGS song = "Push" print(song[len(song)-1]) print(song[-1]) Output h h Selecting a Slice The pattern for slicing a string is the following: string_name[start_index:end_index+1] So, for the word “Push”, let’s say we wanted to get the slice “us”. The starting index would 1 (for u) and 3 (index of s is 2 and then we add 1). song = "Push" print(song[1:3]) Output us More Slicing Slices also have a few convenient shortcuts. Instead of the 0 index, we can simpluy leave that part of the slice blank, like so: song = "Push" print(song[0:2]) print(song[:2]) Output Pu Pu Note that the 0 and blank are the same thing. We can do the same thing with the ending index song = "Push" print(song[2:len(song)]) print(song[2:]) Output MORE ABOUT STRINGS 29 sh sh Note that the len(song) and blank result in the same output. Reversing a String If we combine what we learned above, we can also reverse a string very easily using a slice like so: alphabet = "abcdefghijklmnopqrstuvwxyz" reverse_alphabet = alphabet[::-1] print(reverse_alphabet) Output zyxwvutsrqponmlkjihgfedcba You can think of this as starting at 0, ending at the last character, and then incrementing by -1 each time instead of positive 1. 30 CHAPTER 3: USING VARIABLES - MATH AND STRINGS Chapter 4: Conditionals Computers, like people, need to be able to make decisions. For example, when you enter your pass- word, it would be nice if the computer checked to see if it was correct before allowing access. Basic if Statement When we want a computer to make a decision, we use what is known as an if statement. If statements are in the following format: if condition: do something There are two parts - the condition, and the code block to be executed. Here is an example where we ask the user the enter the password: # Use the input command to get input from the user # The input command is covered in more detail in Chapter 11 password = input("Password > ") # Compare what the user entered to "Joshua" # If they are equal, then print the message. if password == "Joshua": print("Greetings, Professor Falken.") Output Password > Joshua Greetings, Professor Falken. Important: In Python, indentation controls the program flow. In the example above, the print state- ment is indented (four spaces) under the if statement. This tells us the print statement is executed only if the condition is true. In this case, the condition is that the password entered is equal to “Joshua”. Some people prefer to use tabs instead of spaces, however, according to the official Python Style Guide (PEP 8), the preferred indentation method is four spaces. Most programming editors can be configured to convert tabs into spaces so that you don’t have to type so many spaces. It is important to remember that if you mix tabs and spaces your code will not run - you will get an error. 31 32 CHAPTER 4: CONDITIONALS Note: When comparing values, we use TWO equals signs. When we are assigning a value, we use ONE equals sign. Also, note that “Joshua” and “joshua” are NOT equal to the computer because one starts with a capital letter and the other one does not. # One equals sign means we are assigning a value x = 42 # Two equals signs means we are comparing values if x == 42: print("X equals 42") Types of Comparisons Here are the basic comparison operators: Operator Meaning == Equal to > Greater than < Less than >= Greater than or equal to = 1.21: print("You have enough gigawatts!") and/or Sometimes you need multiple conditions for something to happen. Or sometimes you need one of any number of conditions. In these cases we use and or or. Example: if gigawatts >= 1.21 and speed >= 88: print("Welcome to 1985!") Example: password = input("Password > ") ELSE 33 if password == "Joshua" or password == "joshua": print("Greetings, Professor Falken.") Note:: A very common beginner mistake is to omit the repeated variable and just use or. For example: password = input("Password > ") # This will not work as expected if password == "Joshua" or "joshua": print("Greetings, Professor Falken.") else There are times when you have two and only two options. For example, you’re either a crook, or you are not a crook. Example: if papa_doc == "crook": print("Papa Doc is a crook.") else: print("Ain't no such things as halfway crooks.") In the above code, if the value of papa_doc is “crook” then we print “Papa Doc is a crook.” Otherwise, we print “Ain’t no such things as halfway crooks.” elif There are times when we have multiple possible outcomes. So, could code it like this, using multiple if statements: mood = "happy" if mood == "happy": print(":)") if mood == "sad": print(":(") The code above will work; however, it is not efficient, and programmers always want to be efficient. Consider the following. If the mood is “happy”, is it possible for it to be “sad” at the same time? Of course not. So, once we know the mood is “happy”, we know it cannot be “sad”, so checking just wastes time. So, the solution to this is to use elif. mood = "happy" 34 CHAPTER 4: CONDITIONALS if mood == "happy": print(":)") elif mood == "sad": print(":(") In the code above, the line elif mood == "sad": is only executed if the mood is not “happy”. Output: :) Combining if, elif, and else By combining if, elif, and else, we can create code that is efficient, and provides for a default output if none of the conditions we are testing for are true. grade = 12 if grade == 12: print("You are a Senior...congrats!") elif grade == 11: print("You are a Junior...almost there!") elif grade == 10: print("You are a Sophomore...beats being a freshman!") elif grade == 9: print("You are a Freshman...I feel sorry for you!") else: print("You are not a high school student.") In the example above, there are four possible grade levels that we want to check for. Note that as soon as one option is found to be true, the rest of the if block is ignored. The else statement is there to catch any value that falls outside of the 9-12 range. Determining If a String Contains a Particular Character To determine if a particular character is in a particular string, you can use the in keyword. if "x" in "xylophone": print("There is an x in xylophone.") This comes in handy if you want to determine if a particular character is the member of a group, for example, a vowel. As a reminder, “a” and “A” are different letters to the computer (since they have different ASCII values) so we have to make sure this is reflected in our code. letter = "a" DETERMINING IF A NUMBER IS EVEN OR ODD 35 if letter in "aeiouAEIOU": print(f"{letter} is a vowel.") Determining if a Number is Even or Odd To determine if a number is even or odd, we can use the modulus operator (%). The modulus operator gives the remainder of an integer division operation. For example: # 0 divided by 2 is 0 with no remainder 0 % 2 = 0 # 1 divided by 2 is 0 with a remainder of 1 1 % 2 = 1 # 2 divided by 2 is 1 with no remainder 2 % 2 = 0 # 3 divided by 2 is 1 with a remainder of 1 3 % 2 = 1 Based on the pattern above, you can see that numbers evenly divisible by 2 are even, while numbers with a remainder are odd. Therefore: x = 2 if x % 2 == 0: print(f"{x} is even.") else: print(f"{x} is odd.") Notice that we used if and else above because a number cannot be even and odd at the same time - there are two possibilities and they are mutually exclusive. Extension Activity Using the above code as a model, determine if a number is divisible by 3 and print appropriate output. Check the Solutions chapter for a solution to this extension activity. Video Tutorial Here is a link to an introductory video I did on the topic of conditionals: https://youtu.be/wfNHiay 97vw 36 CHAPTER 4: CONDITIONALS Chapter 5: Loops Our programs would be pretty boring if you ran them and then they just stopped! To keep our programs running, and to make our code shorter, we use loops to avoid repeated code. There are two basic loop types in Python - the for loop, and the while loop. For Loops A for loop is a type of loop that is often used in cases where you have a defined start and ending point. It is sometimes referred to as a definite loop. Counting Up Take a look at the following code: print(0) print(1) print(2) print(3) print(4) print(5) Output 0 1 2 3 4 5 The code above works just fine, but consider this. What if you wanted to print 1 to 1,000,000? Clearly, you would not want to have one million lines of print statements in your code. In this case you would use a for loop with the range method. Example 37 38 CHAPTER 5: LOOPS for i in range(0, 6): print(i) Output 0 1 2 3 4 5 Note: In the range method, we started at 0 and we went to 5. But, we actually typed 6 since the final number is not inclusive. So, if you want to count to 5, you need to add one, which is 6. Also, note that you could also do the following with the range method: for i in range(6): print(i) If there is only one number in the range method, it assumes that the starting number is 0, and that the given number is the max (plus 1). Also note that just like with conditional statements, indentation is used to indicate which lines of code are part of the loop and which lines are not. Counting Up by Twos As you can observe from the code and output above, the range method automatically increments by 1. But, let’s say you wanted to count by twos instead. Example for i in range(0, 11, 2): print(i) Output 0 2 4 6 8 10 The 2 in range(0, 11, 2) is referred to as the step. Counting Down Counting down is very similar to counting up; however, in this case, the step is negative. FOR LOOPS 39 Example for i in range(5, 0, -1): print(i) Before you look below, what do you think the output will be? Output 5 4 3 2 1 Were you suprised that the 0 was not included? Remember, the first number is inclusive, while the second number is not inclusive. So, if we want to include the zero, we’d need to do the following: for i in range(5, -1, -1): print(i) The second number is -1 because we want to stop at 0 - since we are counting down, we need to go one number past where we want to stop, which in this case is negative one. Traversing a String There is another very useful way to utilize loops in your code. We will be using this often in this book, and in your real-life coding. We can use a for loop to traverse a string starting with the first character and ending with the last letter. If you recall, string indexes start at 0 and go up to the length of the string minus 1. We can use this fact to traverse a string using a for loop and the range method like so: Example name = "The Cure" for i in range(0, len(name)): character = name[i] print(character) Output T h e C u r e 40 CHAPTER 5: LOOPS Note that we could shorten the code like so: name = "The Cure" for i in range(0, len(name)): print(name[i]) Alternatively, since in this case we are starting at the beginning of the string and going all the way to the end one-by-one, we can also use what is called a for each loop, or as it is sometimes referred to an enhanced for loop. Example name = "The Cure" for character in name: print(character) Output T h e C u r e What the for each loop does is iterate through each character in the string one-by-one and assign that value to character. It starts with the first character and ends with the last character. Note: In the example above I used character to represent the text - I did not need to do this. The computer doesn’t know or care, but I chose that as it makes sense to me as a human. I could have used c, or even thx1138 as my variable name. Counting Now that we know how to traverse a string, we can use conditional statements to count certain ele- ments. Example # Count the number of spaces quote = "I'm gonna make him an offer he can't refuse." number_of_spaces = 0 # We start with 0 for character in quote: if character == " ": number_of_spaces += 1 WHILE LOOPS 41 print(f"There are {number_of_spaces} spaces.") Output There are 8 spaces. Variable Names and Readability Take a look at the following code. q = "I'm gonna make him an offer he can't refuse." n = 0 for c in q: if c == " ": n += 1 print(f"There are {n} spaces.") Compared to the previous code, it is definitely harder to understand what the code does, although you can probably figure it out. Using comments in your code and, more importantly, good variable names is key to making your code readable and maintainable. Extension Activity Using the above pattern, count the number of vowels (a, e, i, o, u) - don’t forget about capitals! See the Solutions Appendix for a solution to this programming activity. While loops Anything that can be done with a for loop can also be done with a while loop. However, where and how the incrementor variable, condition, and step are different. I’m going to do the above exercises, but this time with a while loop instead. Counting Up Take a look at the following code: print(0) print(1) print(2) print(3) print(4) print(5) 42 CHAPTER 5: LOOPS Output 0 1 2 3 4 5 Just as we saw previously with the for loop, we can avoid repeated code using a while loop. Example # Increment variable i = 0 # The condition is while i is less than 6 while i < 6: print(i) # This is the step i += 1 Output 0 1 2 3 4 5 Note: Again, we started at 0 and we went to 5. But, we actually typed 6 since the final number is not inclusive. So, if you want to count to 5, you need to add one, which is 6. Alternatively we could change the condition to i ). So, if we want to include the zero, we’d need to do the following: i = 5 while i > -1: print(i) i -= 1 The second number is -1 because we want to stop at 0 - since we are counting down, we need to go negative. Note: As mentioned previously, we could also write the code the following way, using >= instead of >. i = 5 while i >= 0: print(i) i -= 1 44 CHAPTER 5: LOOPS Again, I would recommend using the first method to keep it more consistent, but as you learn more and become more comfortable coding, feel free to use whichever method suits you best. Traversing a String In our example above when we traversed the string, we used a for each loop. Unfortunately, there is no while each loop, so we’ll have to deal with string indices. Example name = "The Cure" i = 0 while i < len(name): character = name[i] print(character) i += 1 Output T h e C u r e Combining Loops with Conditionals Now that we know how to traverse a string, we can use conditional statements to count certain ele- ments. Example # Count the number of spaces quote = "I'm gonna make him an offer he can't refuse." # We start with 0 number_of_spaces = 0 i = 0 while i < len(quote): # Choose the character in position i character = quote[i] # Check if it is a space if character == " ": # If so, add 1 to the number_of_spaces END A LOOP EARLY USING BREAK 45 number_of_spaces += 1 i += 1 print(f"There are {number_of_spaces} spaces.") Output There are 8 spaces. End a Loop Early using Break In all of the examples we’ve seen so far, the loop starts at a certain value and continues to the end of the loop. However, there may be times when you want a loop to end early. In cases like that, you can use the break command. Let’s say you are looking to find if the letter a is in a particular string, you could write the following code. quote = "Here's looking at you kid." for character in quote: if character == "a": print("a was found") If you look at the quote, you can see there is a lower case a at index 15. However, the computer will keep searching after it has found the letter a, even though in this case, it does not need to. So, in a case like this, we would add a break statement. Once the break statement is reached, the loop ends, and execution continues after the loop. quote = "Here's looking at you kid." for character in quote: if character == "a": print("a was found") break While it may not seem like a big deal in this case to keep searching since there are only ten more letters to search, imagine you were searching DNA base pairs of a particular human’s genome - you’d have to search through approximately 3 billion base pairs. Continuing a Loop In contrast to the break command, there are times when you will want to end the code inside a loop early, but continue to the next iterationi of the loop. Take a look at the following code. What do you think the output will be? 46 CHAPTER 5: LOOPS for x in range(0, 11): if x % 2== 0: continue print(x) Output 1 3 5 7 9 Everytime the condition x % 2 == 0 is true, the program goes back to the start of the loop, and x is incremented. Because of this, the number is not printed since the print statement is after continue. Here is the same code using a while loop instead. Remember to increment the variable before con- tinuing, otherwise you’ll be stuck in an infinite loop. x = 0 while x < 11: if x % 2== 0: x += 1 continue print(x) x += 1 While True Loop There is another type of while loop you will see. It is a called a while true loop, which is an infinite loop that will run until the break command is reached, or the program ends. These are useful for programs like games that have a main game loop that runs continuously throughout the game. while True: print("This will print forever!") If you are stuck in an infinite loop like this, you can stop the program execution by typing Control + z on the keyboard. Be sure to click in the terminal window first so it has focus. Extension Activity Using the above pattern, count the number of vowels (a, e, i, o, u) - don’t forget about capitals! VIDEO TUTORIAL 47 Check the Solutions chapter for a solution to this extension activity. Video Tutorial Here is a link to an introductory video I did on the topic of loops: https://youtu.be/pV6bkk1UxI8 48 CHAPTER 5: LOOPS Chapter 6: Functions Thus far, our code starts at the top of the program, and executes line by line until the end (depending on conditional statements or loops). In this chapter we are going to learn how to create functions which allow us to jump around to different sections of the code. Functions allow us to group our code into logical sections that may be reused. This shortens our overall program length and makes it easier to maintain and update code. Basic Structure A function starts out with a function declaration which defines the function. To do this, we use the def keyword. def print_the_answer(): print(42) In the example above, we have created a function called print_the_answer. The function only has one line of code inside of it which prints the number forty-two when the function is called. Also note that just like with conditional statements and loops, indentation is used to indicate which lines of code are part of the function and which lines are not. Type the code above into your computer and run it, what do you see on the screen? If all goes well, you will see nothing on the screen. This is because defining a function does not cause the function to run - it will only run when called. To call a function, we use it’s name like so: print_the_answer() Now if you run the code, you should see 42 on the screen. Note:* print_the_answer is the name we have given the function - the computer does not understand what the means. We could call it pta, p_t_a, or kotaeru_o_insatsu, and it would still work the same. The function name is just a convenience for humans - the computer doesn’t know or care as long as the function name is unique and follows the Python naming rules. That said, meaningful function names are extremely helpful in making code readable and maintainable. 49 50 CHAPTER 6: FUNCTIONS Sending Values to a function One of the things that makes a function powerful is the fact that values can be sent to the function. Take a look at the following example: def show_countdown(seconds): for i in range(seconds, 0, -1): print(i) print("Boom!") show_countdown(10) Output 10 9 8 7 6 5 4 3 2 1 Boom! In the code above, the value 10 is sent to the function. Notice the variable seconds in the paren- theses of the function definition. So, this is the same as saying seconds = 10. You may be wondering why we would want to do this. Why can’t you just put the countdown code into the program directly instead of defining and calling the function? Well, you can do it like that, however, consider a program that has 3 different countdowns - 10 seconds, 20 seconds, and 30 seconds. You only need to define what the countdown is one time and then call it so you save all the extra loop code. show_countdown(30) show_countdown(20) show_countdown(10) Returning values from a function Functions can also return values. Take a look at the following example: def get_double(x): return x * 2 SCOPE 51 y = get_double(5) print(y) What do you think the output will be? If you said, 10 then you’d be correct. What happens above is the following: The value of 5 is sent to the get_double function where it is assigned to x. The value of x * 2 is returned from the function. In this case it is 10. The returned value 10 is assigned to the variable y. The value of y is printed. Scope Scope is a somewhat more advanced topic and is often confusing to beginners. Scope refers to how and where a variable may be accessed in a program. Take a look at the following examples. Accessing A Global Variable from Inside a Function # x is defined in the global space x = 5 def print_double(): # There is no x in the local function # So, we look to the global variable x print(x * 2) print_double() Output 10 In the code above, we defined x outside of the function in what is called the global space. When we call the function, it tries to multiply x by 2. Since there is no x inside the function to multiply, the function then looks to the global space for x and finds it. So, it uses that value. Note: In the example above we are merely using the value of x. We are not trying to change it. Changing A Global Variable from Inside a Function Now, take a look at the following example. Here we are trying to change the value of the global variable from inside the function. # x is defined in the global space x = 5 def print_double(): 52 CHAPTER 6: FUNCTIONS # We are trying to change x (multiply by 2) x = x * 2 print(x) print_double() Output UnboundLocalError: local variable 'x' referenced before assignment In this case, because you are trying to change a global variable from inside a function, you get an UnboundLocalError message and the program stops running. If you want to change a global variable from inside a function, you can use the global keyword. Note that while you can do this, it is not considered good coding practice. # x is defined in the global space x = 5 def print_double(): # Use the global variable x global x x = x * 2 print(x) print_double() print(x) Output 10 10 Notice that the value of x is changed inside and outside of the function since there is only one x, in this case a global variable. As mentioned above, using global variables inside of functions is frowned upon. It is better to use a local variable inside the function like so. # x is defined in the global space x = 5 # This x is the local variable x # It is NOT the global variable x def print_double(x): x = x * 2 print(x) print_double(x) print(x) COMBINING CONDITIONALS, LOOPS, AND FUNCTIONS 53 Output 10 5 Notice that the value of x is not changed outside of the function - it is still 5. In the example code above, I used x for both the global variable and the local variable inside the function. I didn’t have to do this, but did it to illustrate the point that although to the human eye, the variables are the same, they are different to the computer. Combining Conditionals, Loops, and Functions Let’s say you are doing some text analysis and you need a function that would tell you how many times a particular letter appears in a given string. We can combine conditionals, loops, and functions to do this. # Define the function def letter_count(target_letter, string): count = 0 for letter in string: if letter == target_letter: count += 1 return count # Call the function quote = "Here's looking at you, kid." a_count = letter_count("a", quote) print(a_count) Output 1 Extension Activity In the previous unit’s extension activity, we counted the number of vowels in a string. For practice, create a function called get_vowel_count. The function should accept a string value and return the number of vowels in the function. Check the Solutions chapter for the answer. Video Tutorial Here is a link to an introductory video I did on the topic of functions: https://youtu.be/zZ2IC_uebjg 54 CHAPTER 6: FUNCTIONS Chapter 7: Lists and Tuples Up until now, we have focused on various coding structures. For this chapter, we are going to look at our first data structure, the Python list. A list is just what it sounds like - a list of data in a particular order. Basic Structure Imagine you have three students in your class, Mieko, Jason, and Bob. You could store their names in variables like so: name0 = "Mieko" name1 = "Jason" name2 = "Bob" That works, but what happens when you want to add another student? You’ll need another variable like name3. For small amounts of data, you could do this, but what if you needed to store the names of all the students in a class; you can see that the number of variables increases, not to mention the fact that when you write the program, you don’t know how many students there could be someday. The solution here is to use a list like so: avengers = ["Iron Man", "Thor", "Black Widow", "The Hulk"] Notice that I used a plural noun for the list variable name. This isn’t required, but really helps make your code more readable. List Indicies To access a given item in the list, you use its index. Just like with strings, the the first index is index 0. So, to print the first item on the list you would do the following: print(avengers) Output Iron Man 55 56 CHAPTER 7: LISTS AND TUPLES Item Iron Man Thor Black Widow The Hulk Index 0 1 2 3 Index -4 -3 -2 -1 So, for any list, the index of the last item can be obtained by one of the following methods: avengers = ["Iron Man", "Thor", "Black Widow", "The Hulk"] print(avengers[len(avengers)-1]) print(avengers[-1]) Output The Hulk The Hulk Iterating Through a List Iterating with a For Loop In the loops chapter, we we learned how to iterate through a string using the index of each character. We can do the same thing with lists like so: avengers = ["Iron Man", "Thor", "Black Widow", "The Hulk"] for i in range(0, len(avengers)): avenger = avengers[i] print(avenger) Output Iron Man Thor Black Widow The Hulk So, you can see that the list has 4 items on it. So, we again use len to find the length. Then we use the range method just like we did with strings. Iterating with a For Each Loop Just like with strings, we can use a for each loop. Note that in this case we are not iterating through individual characters, but rather through items in a list like so: avengers = ["Iron Man", "Thor", "Black Widow", "The Hulk"] DETERMINING IF A VALUE IS IN A LIST 57 for avenger in avengers: print(avenger) Output Iron Man Thor Black Widow The Hulk Note the grammatical pattern in the for each loop above. The code says for avenger in avengers. This is a clear pattern to use - plural for the list, singular for each item. Determining If a Value is in a List The easiest way to determine if an element is in list is to use the in keyword - just like we did with characters and strings: avengers = ["Iron Man", "Thor", "Black Widow", "The Hulk"] name = "Thor" if name in avengers: print(f"{name} is an Avenger!") else: print(f"{name} is not an Avenger!") Output Thor is an Avenger! Slices Just like we did with strings, lists can be sliced as well. In this case, rather than slicing letters, we are slicing list items. The pattern for slicing a list is the same as a string: list_name[start_index:end_index+1] So, for the avengers list, let’s say we wanted to get the slice that includes “Thor” and “Black Widow”. The starting index would 1 (for Thor) and 3 (index of Black Widow is 2 and then we add 1). avengers = ["Iron Man", "Thor", "Black Widow", "The Hulk"] print(avengers[1:3]) Output 58 CHAPTER 7: LISTS AND TUPLES ['Thor', 'Black Widow'] Important: Notice that when we use a single index such as avengers, it returns a list item, in this case a string. However, when we are slicing muliple items such as avengers[0:2], it returns a list. More Slicing As we saw with strings, slices also have a few convenient shortcuts. Instead of the 0 index, we can simpluy leave that part of the slice blank, like so: avengers = ["Iron Man", "Thor", "Black Widow", "The Hulk"] print(avengers[0:2]) print(avengers[:2]) Output ['Iron Man', 'Thor'] ['Iron Man', 'Thor'] Note that the 0 and blank are the same thing. We can do the same thing with the ending index avengers = ["Iron Man", "Thor", "Black Widow", "The Hulk"] print(avengers[2:len(avengers)]) print(avengers[2:]) Output ['Black Widow', 'The Hulk'] ['Black Widow', 'The Hulk'] Note that the len(avengers) and blank are the same thing. List Methods There are a variety of methods we can use on lists. Here are some of the more common and useful ones: scores = [90, 80, 100] # Adding # Adds the value to the end of the list scores.append(value) # Adds the given value at the given index # (other elements shifted right) MORE ABOUT LISTS 59 scores.insert(indes, value) # Removing # Removes the first item with the given value from the list scores.remove(value) # Removes the last item from the list and returns it scores.pop() # Removes item at index from the list and returns it scores.pop(index) # Clear all items from the list scores.clear() # Finding and Counting # Returns the index of the first item with that value scores.index(value) # Returns the count of the number of items in the list # with the given value scores.count(value) # Sorting and Reversing # Sort the list from lowest to highest # (or in alphabetical order) scores.sort() # Reverse the order of the list scores.reverse() This is not a complete list of list methods - you can find more about list methods here: https://docs.p ython.org/3/tutorial/datastructures.html#more-on-lists More About Lists Python has a few more conventient commands you can use with lists. Len You’ve already seen that we can get the number of items on a list using len like so: scores = [70, 80, 90, 100] print(len(scores)) Output 4 60 CHAPTER 7: LISTS AND TUPLES Sum Python also has a convenient way to find the sum of the values in a list of numbers using the sum command. scores = [70, 80, 90, 100] print(sum(scores)) Output 340 Calculating the Average of a List We can combine len with sum to find the average value of a list of numbers. scores = [70, 80, 90, 100] average = sum(scores) / len(scores) print(average) Output 85.0 Note that even though the scores were integers, the average is a float - it has a decimal point. Tuples A tuple is a data structure that is very similar to a list, but with one important difference. A tuple cannot be changed once it is created. It cannot be sorted, appended, popped, or altered in any way. In programming this is referred to as being immutable. Here are some examples of some tuples. Note that instead of [] we use () to indicate it is a tuple, and not a list. weekdays = ("Mon", "Tue", "Wed", "Thur", "Fri") print(weekdays) Output Fri If you try to change one of the values in the tuple, this is what happens: weekdays = ("Mon", "Tue", "Wed", "Thur", "Fri") weekdays = "MON" print(weekdays) LIST COMPREHENSIONS 61 Output File "tuple.py", line 3, in weekdays = "MON" TypeError: 'tuple' object does not support item assignment As you can see, there is a TypeError since tuple values cannot be changed. You can however make a new tuple using the same variable name if you’d like. List Comprehensions List comprehensions are a shortcut method for iterating through lists and performing some sort of operation on the values in the list. I usually don’t teach this to my students since it is pretty much a Python-specific feature. I prefer that students understand the basics that can be applied across languages first, before learning these types of things. That said, I’m including a brief introduction to the topic here. Let’s say you have the a set of scores for a particular student. Furthermore, your policy is to ignore any score under 20 percent. You could do something like the following: scores = [80, 18, 94, 9, 99, 76] final_scores = [] for score in scores: if score >= 20: final_scores.append(score) print(final_scores) Output [80, 94, 99, 76] As you can see, the scores lower than 20 were filtered out. We can do the same thing using a list comprehension like so: scores = [80, 18, 94, 9, 99, 76] # Add the score to the final_scores list # If the score is greater than or equal to 20 final_scores = [score for score in scores if score >= 20] print(final_scores) Output [80, 94, 99, 76] 62 CHAPTER 7: LISTS AND TUPLES As you can see, there is no difference between the output - it’s just a more compact way of doing the same thing. Capitalize All Words in a List Let’s say you wanted to capitalize all the words in a given list. You could easily do this with a list comprehension like so: words = ["Love", "Me", "Do"] capitalized_words = [word.upper() for word in words] print(capitalized_words) Output ['LOVE', "ME", 'DO'] Note that there was no condition in this example like there was in the first one. This is because we are applying the.upper method to all the items in the words list. Video Tutorial Here is a link to an introductory video I did on the topic of lists: https://youtu.be/lQ52sNF_d2o Chapter 8: Dictionaries A former student of mine once referred to dictionaries as “lists on steroids”. In our previous chapter, we learned about lists which store information in order and are accessed by index. In contrast, a dictionary stores information in what is known as a key-value pair. Basic Structure Take the following information: tokyoedtech_age = 51 tokyoedtech_height = 175.0 tokyoedtech_weight = 98.0 Instead of separate variables, we could combine the information into a dictionary like so: tokyoedtech = { # The first key is age (string) # The first value is 51 (int) "age": 51, "height": 175.0, "weight": 98.0 } To access the information: print(tokyoedtech["age"]) print(tokyoedtech["height"]) print(tokyoedtech["weight"]) Output 51 175.0 98.0 To add more key-value pairs to the dictionary, you can do this: tokyoedtech["city"] = "Tokyo" By the same token, to change a value, we would do the same: 63 64 CHAPTER 8: DICTIONARIES tokyoedtech["weight"] = 80 Accessing the Keys and Values To pull out the keys from a dictionary, you can do the following: keys = tokyoedtech.keys() print(keys) Output dict_keys(['age', 'height', 'weight']) Note that the keys data is NOT a list, rather it is a dict_keys object. You can iterate through the keys, but if you try to use list methods such as sort, it will not work and your program will have an error. You can however convert the dict_keys object to a list by doing the following: keys = tokyoedtech.keys() keys = list(keys) You can, of course, do this in one line of code as well: keys = list(tokyoedtech.keys()) By the same token, you can access the values as well in the same way. values = tokyoedtech.values() print(values) Output dict_values([51, 175.0, 98.0]) Note that the values data is NOT a list, rather it is a dict_values object. You can iterate through the keys, but if you try to use list methods such as sort, it will not work and your program will have an error. Iterate through a Dictionary To iterate through a dictionary, you have a couple of options. 1. You can get the keys as shown above and iterate through them. 2. You can get the values as shown above and iterate through them. 3. Iterate through the keys directly like so: for key in tokyoedtech: print(key) Output NOTES ON DICTIONARIES 65 age height weight Iterate through the Keys and Print the Values for key in tokyoedtech: print(tokyoeedtech[key]) Output 51 175.0 98.0 Of course, it goes without saying you can also do the following: for key in tokyoedtech: print(f"{key}: {tokyoedtech[key]}") Output age: 51 height: 175.0 weight: 98.0 Notes on Dictionaries Dictionaries are a powerful data strucure. If you are familiar with other languages such as Java, they are referred to as hashmaps. You might also recognize them as being very similar to a data format known as JSON (JavaScript Object Notation). However, there are some things to keep in mind when using dictionaries. Keys Must Be Unique You cannot have two of the same key with separate values. For example, take a look at the following code: scores = { "test": 75, "hw": 85, "participation": 90, "test": 85 } print(scores["test"]) 66 CHAPTER 8: DICTIONARIES Output 85 Notice that the value of 75 for the first test is lost because the second “test” value overwrites the first. Lists Cannot Be Used as a Key but Tuples Can It is not possible to use a list as a key because it is mutable - this is a fancy way of saying changeable. Mutability is a somewhat advanced topic, but we know that we can change a list by sorting it, or appending, or popping a value. Because of this, it cannot be used as a key in a dictionary - the reasoning is quite technical, so just trust me on this one. However, a tuple is immutable - this is a fancy way of saying unchangeable. In this case we mean it cannot be changed by a method such as sort, and it cannot be appended, or popped. Here is an example of where you might use a tuple for a key. In this case, the key is a tuple with the latitude and longitude of a particular city. cities = { (35, 139): "Tokyo", (37, 126): "Seoul", (39, 116): "Beijing" } print(cities[35, 139]) Output Tokyo Video Tutorial Here is a link to an introductory video I did on the topic of dictionaries: https://youtu.be/vFRI5D_ nnCw Chapter 9: Classes You may recall from the chapter on dictionaries that one of my former students referred to dictionaries as “lists of steroids”. She also referred to classes as “dictionaries on steroids”. It’s a good way to think about classes. Classes take the simplicity and compactness of dictionaries and add in functions to the mix. The classic definition of a class is a “blueprint for an object”. Then object is defined as a self-contained data structure with methods that is defined by a class. It’s kinda circular, but once you learn the details, it’ll all make sense. Basic Structure It’s helpful to stop and think of objects as something concrete we can relate to. So, for this example, I’m going to use a person as an example. Classes are made of up three main parts: attributes, constructor(s), and methods. Note, a method is another word for function, but typically when we refer to functions in classes, we use method instead. So, back to our person, TokyoEdtech. Let’s give our person two attributes, name and age. Here is the basic class definition: class Person(): # Constructor def __init__(self): self.name = "" self.age = 0 In the above code, we have definied what a person is - an object with a name and an age. Please note the following: 1. The name of the class is capitalized. 2. The constructor is a special method (__init__) that is called when an object is first created. 3. The keyword self is used to refer to the current object. For example, we could have a Person object called bob and another named sue. Since we don’t know what objects are going to be created ahead of time, we use self as a placeholder. To create an object with these attributes, we would do the following: tokyoedtech = Person() 67 68 CHAPTER 9: CLASSES tokyoedtech.name = "Christian" tokyoedtech.age = 51 To access the above values, we would do the following: print(f"{tokyoedtech.name} is {tokyoedtech.age} years old.") Output Christian is 51 years old. Thus far, you can hopefully see the similarities and differences between this and a dictionary. How- ever, what makes classes powerful is the ability to add methods to the class. Adding Methods to a Class It can be helpful to think of attributes as nouns and adjectives, while methods are verbs - the things that an object can do. For example, a person can speak. So, let’s create a class method called speak. class Person(): # Constructor def __init__(self): self.name = "" self.age = 0 def speak(self): print(f"Hi. My name is {self.name}.") In the code above, we’ve created a method that will print a particular phrase on the screen when the speak method is called on a Person object like so: tokyoedtech = Person() tokyoedtech.name = "Christian" tokyoedtech.age = 51 tokyoedtech.speak() Output Hi. My name is Christian. Note the pattern of object.method and object.attribute. This pattern is referred to as dot notation. We’ve seen this before with string methods and list methods. The difference here is that we are creating our own objects and methods. BASIC INHERITANCE 69 Basic Inheritance One of the great strengths of object oriented programming is the fact that classes can inherit attributes and methods from another class. Take for example a boy named Sue. He is 17. Using our Person class, we would create the object like so: sue = Person() sue.name = "Sue" sue.age = 17 Thus far, there is nothing different - the sue object is simply another instance of the Person class. However, think about the following - let’s say that Sue is a student. As a student, Sue also has a grade that he is in. So how do we deal with this? One way, would be to create a separate Student class that is a copy of the Person class with an extra attribute like so: class Student(): # Constructor def __init__(self): self.name = "" self.age = 0 self.grade = 0 def speak(self): print(f"Hi. My name is {self.name}.") We could then create the sue object like so: sue = Student() sue.name = "Sue" sue.age = 17 # Sue is a senior. sue.grade = 12 You can probably already see that this is not a great solution - we always want to avoid repeated code when and where we can. The solution to this is to use inheritance. Inheritance is just what it sounds like - a child class inherits the attributes and methods from its parent class. Note, a parent class is also referred to as a superclass. A child class is sometimes referred to as a subclass. To use inheritance we need to do two things - tell the child class which parent class to inherit from and to call the parent class constructor directly. # Note the super class goes inside the parentheses class Student(Person): # Constructor def __init__(self): # Call the constructor of the super class 70 CHAPTER 9: CLASSES super().__init__(self) self.grade = 0 Now, we can create a Student object called sue. Even though name and age are not mentioned (neither is the speak method) in the Student class, the Student class inherits them from the superclass, in this case, Person. sue = Student() sue.name = "Sue" sue.age = 17 # Sue is a senior. sue.grade = 12 sue.speak() Output Hi. My name is Sue. Overriding Methods Overriding methods is another useful ability of using classes and inheritance. In our Person class, we have a method called speak. It stands to reason, that a student might say something different that a person who is not a student. So, we can replicate this in our code like so: class Student(Person): # Constructor def __init__(self): super().__init__(self) self.grade = 0 # This method overrides the superclass method def speak(self): print(f"Hi. My name is {self.name} and I am in grade {self.grade}.") Now if we call the speak method, it will call the one in the Student class and the output will be different. sue = Student() sue.name = "Sue" sue.age = 17 sue.grade = 12 # Sue is a senior. sue.speak() Output Hi. My name is Sue and I am in grade 12. VIDEO TUTORIAL 71 Video Tutorial Here is a link to an introductory video I did on the topic of object oriented programming and classes: https://youtu.be/DWccYUiPO0E 72 CHAPTER 9: CLASSES Chapter 10: More About Classes In the last chapter, we we learned about classes, how to instantiate an object, and inheritance. In addition there are attributes and methods that belong to the class itself rather than to an individual object. Also, variables and methods have limitations placed on how and from where they can be accessed. This is referred to as public, protected, and ****private**** attributes and methods. Class Variables and Methods Let’s revisit our Person class from the previous chapter. class Person(): # Constructor def __init__(self): self.name = "" self.age = 0 def speak(self): print(f"Hi. My name is {self.name}.") Note that all variables are referenced using self. By using self, we mean the value for the current object. But, let’s say we wanted to keep track of how many people there are automatically. To do this, we would use a class variable. class Person(): # Class variables number_of_people = 0 # Constructor def __init__(self): self.name = "" self.age = 0 # When we create a new person object, # add one to number_of_people Person.number_of_people += 1 def speak(self): 73 74 CHAPTER 10: MORE ABOUT CLASSES print(f"Hi. My name is {self.name}.") bob = Person() sue = Person() jason = Person() print(Person.number_of_people) Note, that in the class declaration above, the variable number_of_people does not have self attached. This tells us that it is a class variable and not an instance variable. Later, when we reference the variable (both inside and outside the class), we use the class name like so: Person.number_of_people. This is another example of dot notation. Public, Protected, and Private Public A variable or method that is public is accessible from both inside and outside of the class. This is the default. As we saw in the previous chapter since the attributes name and age are public (by default) we can access them anywhere - even outside the class like so: class Person(): def __init__(self): self.name = "" self.age = 0 tokyoedtech = Person() tokyoedtech.name = "Christian" tokyoedtech.age = 51 tokyoedtech.speak() Protected A variable or method that is protected is only accessible from within the class itself, or one of its subclasses. To show a variable or method as protected you simply add one underscore (_) before the variable name like so: _age The underscore tells us that the variable age is protected and should not be accessed directly. class Person(): # Constructor def __init__(self, name, age): PUBLIC, PROTECTED, AND PRIVATE

Use Quizgecko on...
Browser
Browser