Effortless Introduction to Python For All Ages A languid stroll through the garden of Python concepts

An introduction to coding should feel like a walk through a beautiful park in full bloom. All too often, such learnings

125 59 8MB

English Pages 329 Year 2024

Report DMCA / Copyright

DOWNLOAD FILE

Polecaj historie

Effortless Introduction to Python For All Ages A languid stroll through the garden of Python concepts

Citation preview

Foreword It is our great pleasure to introduce you to the book “Effortless Intro to Python For All Ages”. This book is designed to be a fun and easy-to-read guide for anyone who wants to learn Python. The book is organized with easy to understand real world analogies, making it a perfect choice for beginners who are new to programming. Python is a powerful and versatile programming language that is used in a wide range of applications, from web development to data analysis. With this book, you will learn the basics of Python programming in a fun and engaging way. The book is designed to be ready easy like a storybook, so you can learn at your own pace and enjoy the process. Whether you are a student, a professional, or just someone who wants to learn a new skill, this book is the perfect choice for you. With its clear explanations, real-world examples, and easy-to-understand analogies, you will be able to master Python in no time. So, sit back, relax, and get ready to embark on a journey of discovery with “Effortless Intro to Python For All Ages”. Happy coding! 🐍 1

About the book

An introduction to coding should feel like a walk through a beautiful park in full bloom. All too often, such learnings are structured to feel like a forced run up a hill on a cold, rainy day. This book is our attempt to provide an option that speaks to the former. 2

About the book : Continued The book is a result of the realization that we need a shift in how programming languages such as Python are usually learnt. One of the key things to realize with coding is that it is NOT easily relatable to things we do naturally. When we count or use money, we relate to Math. Speaking, watching shows relates to language arts and grammar. Biology, physics and chemistry happens all around us all the time. Technology, however, works like magic. It is not at all intuitive or obvious on how it does its thing. The need to have an active and strong ability to imagine makes learning about technology all the more daunting. There are a lot of speed bumps and potholes that will test you on your Python learning journey. First thing is with the introduction of new words and phrases. New terminology, if it is not declared, addressed and acknowledged properly, carries a presumption of prior knowledge. It is easy to understand how disconcerting this can be. By using a dedicated vocabulary section upfront, our book addresses this issue front and center. Students have a place to quickly scroll as and when they encounter these new terms. Vocabulary Section Example ● ●

● ●

Variable: a container that can store data of different types Data Type: ….

3

Integer: a whole number Float: …

About the book : Continued Focus on one concept at a time E X P L A N A T I O N

E X A M P L E

Every page is dedicated on focusing on and teaching one thing. With clearly defined and visually separated sections further allows students to easily discern between examples and explanations - The two key components of learning. Colorful illustrations round things off while making it catchy and fun.

Examples are clearly presented with emphasis on the concept being covered

Syntax Explanation These sections offer a quick, easy way to understand semantics and structure of code. Your conditional

if 5 < 4: print(“Correct”)

Print this if it’s true If it’s not true

else: print(“Are you sure”)

Print this instead

name = input("Please enter your name: ") Variable to store the input in

Input function

Prompt that shows up as a question to the user

4

About the book : Continued So… Python language is easy to learn. But why should that be any reason to spend your precious time and attention on it ? 1. Instagram 2. Youtube 3. Pinterest 4. Dropbox 5. Reddit 6. Uber 7. Quora … and many more popular apps have been built with Python! Python is THE key language for writing AI applications. The biggest and baddest AI tools are in Python 1. 2. 3. 4.

Tensorflow Keras Pytorch SciKit Learn and more …

MicroPython is the most popular language used to code with robots made with hardware such as Arduino. Bottomline, if you are good at python and its libraries, you unlock some awesome abilities to write apps, create robots and everything else in between. That will make you quite valuable, don’t you think ?

5

Chapter 1

Introduction

6

Introduction Summary

In this lesson, we will explore the fundamental elements of Python, including data types, variables, how to distinguish between them, identify when they’re useful, and producing output. We’ll also manipulate variables by practicing arithmetic operations and concatenating strings to create new values.

Objective

Students will be understand how and when to use the appropriate data types which will aid them in all assignments moving forward. Variables and data types are critical in python code and will be used every time a practice or assignments is started.

Vocabulary ● ●

● ●

● ● ●

Variable: a container that can store data of different types Data Type: a particular kind of data item where only certain operations can be performed on Output: The information generated by your program Concatenate: adding multiple string types together to create one

● ●

7

Integer: a whole number Float: a number with decimals Boolean: A value is either true or false NoneType: A data type that contains no information String: letters or words in the form of text

Understanding Variables

Using Variables E X P L A N A T I O N

What are Variables? ● ●



Variables are containers of information They can contain a lot of different types of information This includes, words, numbers, lists, and much more

How Do We Create Variables C R E A T I N G

● ●

Variables can be represented using a letter or word Creating a variable has three basic parts ○ The name of the variable ○ An equal sign ○ The information

8

Let’s Start Simple

Variable Syntax

E X P L A N A T I O N

X is the name of our variable We can call it anything we like

x

=

5

Set your variable equal to something

X is now equal to the number 5

T O G E T H E R

How Do We Create Variables ● ●

This is pretty helpful, but let’s do it together in our code We need to learn how to print the information

Let’s this break down

9

The information we want to set equal to x In this case, the information is the number 5

Our First Code Snippet

Using the Print Function E X P L A N A T I O N

How Do We Print Our Code? ●



To print our code we use something called the print function, print() The information want to print goes inside the parentheses

Some Helpful Tips E X A M P L E S





The print statement must be in all lowercase letters ○ Python is case sensitive The parentheses are placed after functions, we’ll explain these more in the future

10

Data Types

Strings vs Numbers E X P L A N A T I O N

E X A M P L E S

What is a string? ● ● ●

A string is a series of numbers and/or characters together Strings are always kept inside parenthesis This is how python knows we’re using a string

Numbers ● ●

There are different types of numbers, including integers, floats, and real numbers Numbers are helpful for performing math

11

Data Types

Strings vs Numbers E X P L A N A T I O N

What is a string? ●

● ●

A string is a series of numbers and/or characters together Strings are always kept inside parenthesis This is how python knows we’re using a string

Numbers E X A M P L E S





There are different types of numbers, including integers, floats, and real numbers Numbers are helpful for performing math

12

Numbers

What Are the Different Kinds? Types of Numbers E X P L A N A T I O N

● ●



Integers are whole numbers Floats have a specific amount of numbers after the decimal point Real numbers have infinite amount of numbers after the decimal point

Why Is This Important E X A M P L E S





This will always depend on the type of work we’re doing Sometimes decimals won’t even matter when you’re doing math

13

Arithmetic

How Do We Do Math? Without Variables E X P L A N A T I O N

E X A M P L E S

● ●

We can perform math directly inside of the print statement Mathematical operations in Python are: ○ +, -, /, and * ○ Add, subtract, divide, and multiply ○ There are many more, but we’ll worry about those in the future

With Variables ●

We can perform math on variables instead of using simple numbers

14

Concatenation

We Can Even “Add” Strings E X P L A N A T I O N

E X A M P L E S

But How? ● ● ● ●

● ●

The idea of adding words might seem weird at first, but it’s very common in python Of course the words “apple” and “banana” don’t add up to create a new word But we can take two strings and put them together This is called concatenation

There is a problem with this The words are squished together, and there’s no space between them

15

Data Types

Boolean and Nonetype E X P L A N A T I O N

Boolean ● ● ●

A Boolean value is used to determine if something is true or false Example: if you flip a coin, did you get heads? If you did, then heads = true ○ If not, heads = false

Nonetype E X A M P L E S

● ●

A nonetype is a value that contains literally nothing Truthfully, we won’t be using them super often, but they’re the fourth and final primitive data type in python

16

Chapter 2

Conditional Statements

17

Lesson 2: Conditional Statements Summary

In this lesson, we will discuss conditional statements in Python. Conditional statements occur when we want to perform a specific operation only if a specific condition or criteria is met. If that condition is not met, then we want to either perform a different action or stop our code altogether. Conditional statements are helpful when making decisions or when our actions can result in several different outcomes.

Objective

The objective of this lesson is to learn the syntax and decision making required in conditional statements.

Vocabulary ●



Condition: a requirement or criteria needed to perform an action If: Keyword to begin an if-statement, requires a condition and ends with a semicolon





18

Elif: an optional keyword used in if-statements, after the if keyword and before the else keyword, that requires a condition and adds more flexibility to your code Else: an optional keyword in if-statements that does not accept condition and is the default output

Conditionals Statements

What are Conditions? When we are coding Python, the same goes. Sometimes we want to do something specific if a certain condition is met, and if it’s not, do something else. User pressed yes button no

yes Go outside and play basketball

Stay inside and watch TV

19

Conditionals Statements

What are Conditions? E X● P L A N A● T I O● N

What are conditions? Conditional statements execute code only if a certain criteria is or isn’t met We want to perform an action if something happens But we also need to react if that thing never happens

Examples of Conditions E X A M P L E S

● ● ●

We use plenty of conditions everyday just went we speak If it’s cold, you’ll wear a jacket, if it’s warm, you’ll wear shorts Our code works the same way

20

Syntax

If Statement Syntax Your conditional Print this if it’s true If it’s not true Print this instead

E X P L A N A T I O N

if 5 < 4: print(“Correct”) else: print(“Are you sure”)



In Line 1, we can observe two important parts ○ All if statements begin with the keyword if ○ Next, we have our condition, 5 < 4



In other words, we want to print “Correct” if our condition, 5 < 4, is True ○ And we want to print “Are you sure” if it’s False



It should indent automatically, but if it doesn’t, use the tab key, not the spacebar, to indent

21

Syntax

If Statement Syntax

Your conditional

if 5 < 4: print(“Correct”)

Print this if it’s true E X P L A N A T I O N

If it’s not true

else: print(“Are you sure”)

Print this instead ● ● ● ● ●

In Line 3, we can observe another important keyword, else Else, is an incredibly helpful keyword in if-statements Else does not allow a condition Else is our default output if our if statement is never true Else is not required, but highly recommended

22

Syntax

If Statement Syntax if 5 < 4:

Conditional statements end with a “:”

print(“Correct”) E X P L A N A T I O N

else:

Everything related is indented Conditional statements end with a “:”

print(“Are you sure”) ●



Indented again

Similar to loops, lines that contain keywords for if statements, such as if, elif, and else, always end with a colon Code following the keywords is always indented ○ This lets us know which code belongs to that part of the if statement

23

Syntax

If Statement Syntax Your conditional Print this if it’s true Another conditional Print this instead E X P L A N A T I O N

Another conditional Print this instead If everything is wrong Print this instead

● ● ● ●

If food < 12: print(“Breakfast”) Elif food >= 12 and food < 17: print(“Lunch!”) Elif food >= 17 and food =

Greater-than or equal to







25

We use conditionals to compare one variable or datatype to another Typically, when we comparing numbers, we use comparison operators An example of using this operators is saying 4 < 5, or 4 is less than 5 We can also use variables instead, such as a < b

Conditionals

Examples of Different Conditionals ● ==

Equal to

● E X P L A N A T I O N

and

All conditions must be met

● or

At least one condition must be met



26

Here are three more conditionals that can be a little tricky If we want to compare two strings, we use two equal signs instead of one Example, if a == “Apple” Note: this is different than saying a = “Apple”, where we’re setting the variable a equal to Apple

Conditionals

Examples of Different Conditionals ● ==

Equal to

● E X P L A N A T I O N

and

All conditions must be met



or

At least one condition must be met



27

Sometimes we want to have more than one condition If we want, all conditions to be met, we use the and conditional If we have several conditions, and at least one needs to be true, we use or Example: if you’re hungry AND it’s the morning, you should have breakfast

Chapter 3

Loops

28

Loops Summary

In this lesson we will discuss what a loop is, why they’re helpful, and the two types of loops that we can use in Python. Loops are powerful and simple tools that we can use to complete code much faster than we can without them. We can use while loops to run code until a specific condition is met. Or we can use for loops to iterate over a given list and perform some kind of action on it.

Objective

The objective of this lesson is to understand how loops are used and when is it appropriate to use a for loops vs a while loop. We will review the syntax and how to prevent errors to make sure our code runs perfectly every time.

Vocabulary ●





Loop: used to iterate over a sequence, such as a list, to complete code fast and efficiently While Loop: a loop used to repeat until a specific condition is met For Loop: a loop used to iterate through a given sequence, such as a list







29

Counter: a variable used to keep track of how often a loop is iterated through Iterate: to actually go through each individual element with in iterable Iterable: a representation of a series of elements, such as a list, dictionary, tuple, or set

Understanding Loops

Using Loops E X P L A N A T I O N

E X A M P L E S

What are loops? ●



Loops repeat a set of instructions until a specific condition is met Loops encourage reusability when you need to use the same code many times

Where do we see loops in real life? ● ● ● ●

Everyday! You’re awake until you’re tired While you’re in school, you’re learning For every dollar you make, you spend some of it on food

30

Understanding Loops

What’s wrong with this Instructions: Print the numbers 0 - 9

E X P L A N A T I O N

Input

Output

print(‘0’) print(‘1’) print(‘2’) print(‘3’) print(‘4’) print(‘5’) print(‘6’) print(‘7’) print(‘8’) print(‘9’)

0 1 2 3 4 5 6 7 8 9

31

Understanding Loops

What’s Wrong With This? Some Frustrations: ●

E X P L A N A T I O N



We’re repeating almost the same thing ○ We used the print statement 10 times and the only thing that changed was the string Could we use a variable? ○ How would that look?

32

Input i=0 print(i) print(i + 1) print(i + 2) print(i + 3) print(i + 4) print(i + 5) print(i + 6) print(i + 7) print(i + 8) print(i + 9)

Understanding Loops

What’s Wrong With This? Some Frustrations: ●

E X P L A N A T I O N

● ●

We’re repeating almost the same thing ○ We used the print statement 10 times and the only thing that changed was the string Could we use a variable? ○ How would that look? It looks like we can! ○ But it’s still a lot of repetition ○ Let’s break this down some more

33

Input i=0 print(i) print(i + 1) print(i + 2) print(i + 3) print(i + 4) print(i + 5) print(i + 6) print(i + 7) print(i + 8) print(i + 9)

Understanding Loops

Breaking Down Our Problem What do we need? E X P L A N A T I O N

E X A M P L E S

● ● ● ●

We have a variable ○ Which is i We have a starting point ○ Which is i = 1 We have a limit ○ Which is 10 We’re increasing i by a certain amount ○ Which is i + 1

Let’s verbally talk about what we want to do: We want to print the numbers 0-9 ● While i is less than 10, we want to increase i by 1 Good thing we know inequalities :) Time to use a while loop! ●

34

Input i=0 print(i) print(i + 1) print(i + 2) print(i + 3) print(i + 4) print(i + 5) print(i + 6) print(i + 7) print(i + 8) print(i + 9)

Using While Loops

While Loop Syntax

E X P L A N A T I O N

Create a counter

count = 0

Initiate our While-loop

while count < 10:

Indented Our code Increase our counter

Our condition Ends with a colon

print(count) count += 1 | count = count + 1

Two methods to increase a counter Both have the same impact

Let’s this break down

35

Using While Loops

while count < 10: E X P L A N A T I O N

Here we have two major pieces of syntax

E X P L A N A T I O N

Second: ● Every while loop has a conditional component ● Our condition controls how many times we want to execute the code ● Every conditional ends with a ‘:’

First: ● Every while loop begins with the ‘while’ keyword ○ You’ll see it change color when you type it into python

36

Using While Loops

Inside the Loop E X P L A N A T I O N

E X P L A N A T I O N

Everything indented belongs to the loop Count is initially set to 0, so 0 will be the first output Count is than increased by 1 in the next code, so ‘1’ will print next After reaching the final sentence

● ●



What happens at the bottom? ●



After reaching the final line, the code loops around, back to the top The code will continue to repeat until the condition is met

37

Understanding Counters

Using a Counter E X P L A N A T I O N

E X P L A N A T I O N

count = count + 1 ●



The following code keeps track of our old total, and our new total Our new total is increased until the loop is complete

count += 1 ● ● ●

The following code is exactly the same as above On the left, the variable to keep count of On the right, how much you want to increase your count by

Another way to look at it

38

Using While Loops

While Loop Syntax

Create a counter Initiate our While-loop E Indented X Our code P Increase our L counter A N A T I O N

count = 0 while count < 10:

Our condition Ends with a colon

print(count) count += 1 | count = count + 1

Two methods to increase a counter Both have the same impact

Let’s this break down

39

Using While Loops

While Loop Syntax count = 0 while count 1: T duplicate = True A X

if duplicate: print("Duplicate item found!") else: print("No duplicates here...")

221

Tuple Exercise 3: Days of the Week Write a function that, when given the current day of the week, returns the next day and the amount of days left in the week until Friday. For example, if given “Tuesday”, would return “Wednesday” and 3, meaning 3 days until the end of the week.

222

Tuple Exercise 3: Days of the Week Key daysofweek = ("monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday") dayinput = input("enter a day of the week: ") def daysLeft(dayinput): index = daysofweek.index(dayinput) S Y N T A X

# days in week - current day = days left daysleft = len(daysofweek) - index - 1 # next day, but mod 7 to wrap around to beginning of week nextday = daysofweek[(index+1)%7] return daysleft, nextday print(daysLeft(dayinput))

223

Chapter 10

Dictionaries

224

Dictionaries Summary

In this lesson, we will be introducing Python Dictionaries - a powerful data structure that allows you to store data in key : value pairs. This allows for a convenient way to organize your data, and allows for values to be easily looked up. Dictionaries are also great for representing objects!

Objective

Students will understand practical and critical uses for Dictionaries in Python. Students will also understand how to create, update, and delete their own dictionaries.

Vocabulary ● ● ● ●

Dictionary: A data structure in python that allows you to store your data in key:value pairs Data Structure: A data storage structure that allows efficient access and manipulation. Key: A unique value that has a value attached to it. Think of it like a word in the dictionary. Value: The value associated with the unique key - think of it as the definition of a word in a dictionary

225

Understanding Dictionaries

Real Life Example: E X P L A N A T I O N

C R E A T I N G

Think of a dictionary: ●

● ●

A book of words and definitions (keys and values) Each word is unique (each key is unique) Each word has a definition (each key has a value)

How about in Python? ● A collection of keys and values ● Each key has a value associated with it ● No two keys can be the same ● Values are referenced by their keys

226

Let’s Start Simple

Dictionary Syntax

E X P L A N A T I O N

T O G E T H E R

Curly Braces

Dictionary Name

Set your variable equal to something

Keys



We make a dictionary by making a variable name, curly brackets, and then our key:value pairs separated by commas!

How Do We Make A Dictionary? ● ●

Values

Curly braces with key:value pairs inside, separated by commas! Let’s do an example together and make a dictionary for our favorite car

Let’s this break down

227

Understanding Dictionaries Dictionaries in Python are very powerful tools, and to understand them better, you are gonna need to understand how they work, too! ● ● ●

Dictionaries are ordered as of python 3.7 They are changeable - meaning that you can change elements in them! They don’t allow duplicate keys

For example: this code would throw an error:

my_dict = { "brand" : "chevrolet", "model" : "camaro", "color" : "red", "color" : "blue" }

There are duplicate keys here, and that doesn’t work! Python doesn’t know what the actual color of the car is!

228

Understanding Dictionaries Dictionaries in Python are very flexible with the data type of the values. They can be strings, ints, booleans, lists, and even other dictionaries! This gives us a lot of flexibility for customizing our dictionary car

As you can see - we are using strings, int, boolean, and even a list in this dictionary. Keys can ALSO be string, int, and boolean:

229

Understanding Dictionaries Keys can also be string, int, boolean? Say what?! Yes, I’m as baffled as you are. Let’s switch this dictionary up and take a look:

output:

This does allow for a lot of flexibility - but can get confusing fast! Make sure your keys have meaning so that your dictionary is effective and convenient!

230

Dictionary Operations So, we created a dictionary - cool. What can we do with it, you might ask? Well, in Python, we can do a lot: ● ● ● ● ● ●

Add items Change items Delete items Update/add items at the same time Iterate through items Nest dictionaries

A lot, right? Dictionaries are a very powerful and convenient tool in our Python Toolbox. Let’s start with some examples so that you can better understand some of these operations. Fear not! By the end of this, you will be a dictionary pro!

231

Accessing in Dictionaries Accessing the values in our dictionary is really easy just like accessing an item in a list! But, instead of an index, we just give the key inside the brackets. E X A M P L E

We can also use the .get() method to retrieve a value from our dictionary - like so:

E X A M P L E

232

Adding Items To Dictionaries We have our dictionary - what if we want to add an item to it? Let’s start with our base dictionary again: E X A M P L E

What if we want to add a year to our car? Well, it’s super easy!

E X A M P L E

233

Deleting items from dictionaries What if we want to delete the ‘year’ item we added to this dictionary? Well, in Python there are two ways we can achieve this:

Our two options for deleting an item are using the pop() method or the del keyword. Both methods work exactly the same, so it’s up to you! For option 1: all you have to do is put the del keyword before the item in the dictionary that you want to delete. For option 2: all you have to do is use the .pop() method and pass the key of the item you want to delete as an argument!

234

Updating our dictionaries Dictionaries in Python have a very helpful way to update and add items all at once - it’s called the update() method. The update() method allows us to pass in a dictionary as an argument that it will use to update/add to our dictionary! Any keys that exist will have their values updated, and any keys that don’t will be added to your dictionary! E X A M P L E

Let’s say we want to make some changes to our car: We want to update our year and color and also add a new item for our license plate. In Python, we can use the update() method to achieve this all in one line of code.

E dictionary X A Our dictionary M with P L E

update method the method to use

235

data to update with data to update

Iterating through dictionaries In Python, we can also use loops to iterate through dictionaries. There are many ways to do this! We can iterate through the keys, values, and both of them together.

K E Y S

V A L U E

B O T H

236

Iterating through dictionaries In Python, we can also use loops to iterate through dictionaries. There are many ways to do this! We can iterate through the keys, values, and both of them together.

K E Y S

V A L U E

B O T H

237

Nesting Dictionaries Did you know? You can put a dictionary as a value of another dictionary! Let’s say we wanted to add a rival car dictionary inside of our dictionary!

E X A M P L E

What if we want to access the items inside the rival dictionary? Easy. E X A M P L E

238

Python’s Dictionary Methods Python has included a bunch of methods (a.k.a. actions) that dictionaries can perform. They all can help you do different things with your dictionary - anywhere from clearing all the items to updating your dictionary!

● ● ● M E T H O D S

● ● ● ● ● ● ●

clear() - Removes all the elements from the dictionary copy() - Returns a copy of the dictionary fromkeys() - Returns a dictionary with the specified keys and value get() - Returns the value associated with the given key items() - Returns a list containing a tuple for every key:value pair pop() - Removes the element with the specified key popitem() - Removes the last inserted key:value pair setdefault() - Returns the value of the specified key. If the key doesn’t exist - insert the key with the specified value. update() - Updates the dictionary with the set of key:value pairs values() - Returns a list of all the values in the dictionary

239

Exercise #1: My Dictionary What better way to experience dictionaries than to create one ourselves… OF OURSELVES? Yes, it’s time to create a dictionary that represents yourself.

E X E R C I S E

1. 2.

Create a dictionary that represents yourself Keys for your dictionary should include: a. Name (string) b. Age (int) c. School (string) d. Favorite colors e. Favorite foods (list)

3. 4.

Use your dictionary to print your name and age IT’S YOUR BIRTHDAY. Add code to increase your age by 1. Print “it’s my birthday, I’m _” then your new age. Use a loop to print all your favorite foods in your favorite foods list.

5.

240

Exercise #1: My Dictionary Key

241

Exercise #2: Dictionary Manipulation Follow the steps below on your own ‘car’ dictionary. 1.

E X E R C I S E

2. 3. 4. 5. 6. 7.

Create a dictionary for your own car, include the following keys: a. Brand, model, list of colors, top speed, wheel color, and year Print “My favorite car: “ then print the brand of your car. Use the update() method to add a ‘license plate’ number and to update your color Remove wheel color from your car Add a nested dictionary that represents the rival car (including brand and model) Print out the rival cars model using the .get() methods only. Print your dictionary in an appealing way using a for loop

242

Exercise #2: Dictionary Manipulation Key

243

Exercise #3: Car Customization Program So - we have a program that creates a car dictionary. Let’s spice it up. In this problem, you’ll be transforming the simple little program into a full car customization program! 1. E 2. X E R C I S E

Modify your program to welcome the user Once the car is created, show the user a menu with the following options a. Print the car b. Add a trait to the car c. Update a trait of the car d. Delete a trait of the car e. Quit

E X E R C I S E

244

Chapter 11

String and List Functions

245

String and List Functions Summary

In this lesson, we will be talking about a few of the many string and collection functions that python has included. These range from the split function to the join and zip functions. These various tools will give you even more flexibility with strings in this language.

Objective

Students will gain knowledge over various string functions and will be able to recognize when they are necessary and helpful in their problem solving endeavors

Vocabulary ● ● ● ● ● ●

Split: Python String’s built-in method for splitting a string into a list. Delimiter: Used to determine the boundaries between given substrings in a string Strip: String function that trims extra whitespace or special characters from either side of a string. Join: a string function that takes an iterable and joins each element with the given separator Zip: a function that zips together multiple iterables, returning a zip object. The zip object is a pairing of each element in the iterable into tuples. Iterable:

246

What does split do? Let’s say we have a program that asks your teacher for all the test scores for your most recent test. Here’s the catch: your teacher enters them all in as a single string with each test score separated by a space.

P R O B L E M

The test scores are entered as a string, so we don’t necessarily have access to each individual test score easily. It would be nice to have an easy way to convert it into a list of strings...

"95 86 23 57 76 66 68 92 95 100 97 97 65"

["95","86","23","57","76","66","68","92"," 95","100","97","97","65"]

247

What does split do? The solution: use the built-in split method to convert the string of words to a list of words. Let’s take a look at the syntax.

248

What does split do? So, what happened? Python’s built-in split method took our string of test scores separated by a space and split them into a list of each test score. How does this work?

D O C U M E N T A T I O N

Description Returns a list of words in the string, separated by the delimiter string Syntax

str.split(sep, maxSplit)

sep Optional. Character that divides the string into split groups. Default is space. maxSplit Optional. Max amount of splits to do. Default is -1 which means everything.

249

Example #1 What if the string of test scores was separated by commas instead of spaces? We can specify the delimiter character as an argument.

The delimiter character’s default value is a space, but if we specify that we want our string to be split by the commas, then we can give it as an argument to the split function.

250

Example #2 What if we only want to split a certain number of times and leave the rest together? We can specify a maxSplit in the arguments to do just that:

251

Example #3 We can also include full strings as a delimiter and combine that with a maxSplit argument to get even more flexibility

252

What does join do? Join does basically the opposite of split! It takes an iterable (a list, tuple, etc) and joins all the elements together with a given separator. Let’s say we have a list of letters and want to build a word out of it. P R O B L E M

We want to turn a list of characters into a string. For example, ["C","o","d","e"," ", "H", "e", "r", "o"] would turn into "Code Hero"

["C","o","d","e"," ", "H", "e", "r", "o"]

"Code Hero"

253

What does join do? The solution: use the built-in join method to convert the list of characters into a string. Let’s take a look at the syntax.

254

What does join do? So, what happened? Python’s built-in join method took our list of characters and joined them together with the given delimiter (which was an empty string, meaning no spaces in between the letters) How does this work? Description Returns a string made from the elements of an iterable. D O C U M E N T A T I O N

Syntax

str.join(iterable)

str The given delimiter string that will join the iterable. iterable The iterable used for creating the string. For example, a list of characters.

255

Example #1 We can use other delimiters and symbols to separate our elements once joined. Take a look.

256

Example #2 We can shorten the amount of code too by specifying the delimiter in-line with the join call. Take a look:

257

Example #3 We can take a list of people in a friend group and make a string with all of them in it separated by “and”!

258

What does strip do? The strip function in Python is used to clear off unnecessary whitespace or characters before or after your string. This is especially useful when trying to clean data from a large string!

P R O B L E M

We want to clear off unnecessary whitespace and characters around our string. For example, if our string was " hello world "

would turn into "hello world"

" hello world "

"hello world"

259

What does strip do? The solution: use the built-in strip function to clean up both ends of our string. Let’s take a look at the syntax.

260

What does strip do? So, what happened? Python’s built-in strip function took our string that had a lot of whitespace before and after our content and cleaned it up. How does this work?

Description Returns a copy of the string with the leading and trailing characters removed. D O C U M E N T A T I O N

Syntax

str.strip(chars)

str The string to be stripped. chars Optional. String specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix; rather all combinations of its values are stripped

261

Example #1 We can remove whitespace on both sides of our content by giving no arguments to strip function. See below

262

Example #2 We can remove other characters on both sides of our content by giving them as arguments to the strip function. See below

263

Example #3 We can give multiple characters in the chars argument - this will remove any character within the chars string leading and trailing our string.

264

What does zip do? Let’s say in school your class and another class are pairing up to do a school project. If we have a list or tuple of all the students in both class, we can use the zip function to create pairings in the class!

P R O B L E M

We want to use the class lists to create pairings between the two classes. How can we pair different students up easily using Python?

265

What does zip do? The solution: use the built-in zip function to create pairings between the two class lists. Let’s take a look at the syntax.

266

What does zip do? Python’s zip function takes two or more iterables (lists, etc) and creates pairs or groups as tuples. It basically ‘zips’ the them all together!

D O C U M E N T A T I O N

Description Returns a list of tuples, where the i-th tuple contains the i-th element from each argument sequence. Syntax

zip([iterables,...])

iterables The iterables that you want zipped together

["1", "2", "3" , "4", "5"] ["one", "two", "three", "four", "five"]

267

Example #1 We can zip together two iterables such as lists using just the zip function.

268

Example #2 When one of our iterables has more elements than the other, the pairings only go to the length of the shortest iterable.

269

Example #3 We can also zip more than two iterables together, with each of our tuples having as many elements as iterables we give to zip.

270

Exercise #1: Numbers Create a program that takes user input for numbers 1 through 20 as a single string separated by spaces. Print off each number one by one.

271

Exercise #1: Numbers Key We solve this one by splitting the user input string by spaces (default/no arguments) using the split function. We then use a for loop to print each individual number in the list.

272

Exercise #2: Replace the spaces! Using only string functions, replace every space in the following sentence with underscores (_).

"The quick brown fox jumped over the lazy dog" to "The_quick_brown_fox_jumped_over_the_lazy_dog"

273

Exercise #2: Replace the spaces! Key To replace the spaces with underscores, we use the split function to split by the spaces in the sentence. We then use the join function with “_” as the delimiter.

274

Exercise #3: Calculator The goal in this problem is to create a program that allows users to enter two number math expressions as a string and for you to print the result. The user can use any math operator, including +, -, /, *. For example:

275

Exercise #3: Calculator Key

276

Exercise #4: Friendlist Given the following string, using only string functions, convert it to a string of names like so:

"1.Alex!>>,2.Max!,3.Jack?