Skip to main content

Python for Beginners

Page 1

Python for Beginners: A Slow & Detailed Guide 0 - First, Some Basic Information 0.1 - What is programming? 0.2 - Why Python, specifically? 0.3 - Where to program along with this book 0.4 - What the compiler is actually doing 1 - Printing & Variables 1.1 - Basic printing 1.2 - What are variables? 1.3 - Basic variable types 1.4 - Math 1.5 - Inputs 1.6 - Type-casting & printing together 1.7 - String indexing, formatting, and tricks 2 - Data Structures 2.1 - Lists 2.2 - Dictionary 2.3 - Tuples 3 - Logic Gates 3.2 - If statements 3.3 - Elif & else statements 3.4 - While loops 3.5 - And/Or 3.5 - For loops 4 - Functions & Classes 4.1 - Functions 4.2 - Classes 5 - Libraries 5.1 - What are libraries and how to use them? 5.2 - Example library: random 5.3 - Example library: time 5.4 - Example library: turtle Speedrun Python:

Ideas: Say type in “import this” to console


Chapter 1 Printing & Variables BASIC PRINTING When you send a document to a printer, it etches whatever you tell it onto a physical piece of paper, written in ink. When you tell your computer to print something, it's doing a similar thing. No, it's not spewing ink onto the inside of your screen. Rather, it is taking the value you wish to print (the document) and displaying it on the console (the piece of paper). You can send messages, numbers, even more complex data onto the console. The computer can take what you tell it to print and just convert it into characters like ‘a’, ‘[’, ‘2’, or ‘2.3’, then display it on the console. For instance, try writing this out: _____________________________________________________ CODE: print(“Hello World!”) OUTPUT: Hello World! _____________________________________________________Figure 1.01 The computer took what we gave it, here the words Hello World!, and printed it out just like we said to. We can do that with numbers as well. Let’s say: You have 20 cars at a stop on a full bridge, and Godzilla decides that half of them would make a good breakfast. How many cars would he have for dinner? ____________________________________________________ CODE: print(10) OUTPUT: 10 ____________________________________________________Figure 1.02 Notice here that we didn’t need to put quotations around the number 10. That’s because it’s a number, not a word. The computer can understand that, and won’t yell at us. If you wanted, you could also print a decimal: ____________________________________________________


CODE: print(23.4) OUTPUT: 23.4 ____________________________________________________ Figure 1.03

Thank you Python, almighty coding deity! We had no issue at all here, it was able to take the decimal just as easily as an integer. Now let’s just take these basic examples and put them together, creating a multi-lined program (wow!): ____________________________________________________ CODE:

print(“ten”) print(10) print(10.0) OUTPUT: ten 10 10.0 ____________________________________________________ Figure 1.04

Perfect, we’re basically creating the next Windows at this point. Well, not exactly yet, but we’ll get there. Let’s take a look back at when we printed “Hello World!”. One thought you might have had was why do we need the quotes? In order to understand that, we should try to say something without the quotes. How about we try to say “Hello” to the computer, and just forget the quotes for a second: ____________________________________________________ CODE: print(Hello) OUTPUT: Traceback (most recent call last): File "learn.py", line 1, in <module> print(Hello) NameError: name 'Hello' is not defined ____________________________________________________Figure 1.05 There we go, that’s the essence of programming: having a computer curse your name for forgetting two characters. This is what we call an error, and while yours may not be exactly the same this code should be screaming at you for incorrectness. Why is this an issue? If the compiler can figure out that “Hello” means to print Hello, why can’t it just equate Hello to Hello (that was a confusing sentence).


What does ‘Hello’ not being defined mean? In order to understand that, we’ll need to look at variables.

WHAT ARE VARIABLES? Let’s say that we want to store a value in our code. Maybe at the beginning we need to store the message “hi”, and then tens of lines later need to call back and print out that message. Or, even worse, we wish to change the message. We can rest easy, because these situations can all be fixed with the use of variables: packages for data that we can use wherever we wish in our code. For instance, here’s how we can fix that print(hello) code from earlier: ____________________________________________________ CODE:

Hello = “Hi” print(Hello) OUTPUT: Hi ____________________________________________________ Figure 1.06

No errors at all. Looking at the line: Hello = “Hi” First, the Hello is the name of the variable, it's what we are labeling the data. Then we have =, which means is equal to. Basically, we are telling the compiler that the variable name is going to refer to “Hi”, which is the last part. That third element is the actual data that will be contained inside of the variable Hello.


So when we then try to print(Hello), we are actually printing the value inside of the Hello variable, or “Hi”. And the data that variables contain is not set in stone, it can be re-assigned at any time. For instance, if in a mid-life crisis you choose to change your name: ____________________________________________________ CODE:

name = “Dan” name = “Kyle” print(name) OUTPUT: Kyle ____________________________________________________ Figure 1.07

The name variable originally denoted the name Dan, but was then changed to refer to Kyle. So, when we asked to print the value of name we got Kyle. We can even assign variable values to the values of other variables: ____________________________________________________ CODE:

OUTPUT:

number = 3 number2 = number print(number) print(number2) 3 3


____________________________________________________ Figure 1.08

Here, the value of number2 is assigned to the value of number, and thus both number2 & number have the same value of 3. When both are printed, each contains 3. If we want to be really efficient, we also have some other ways of creating variables: ____________________________________________________ CODE:

a, b = 2, 5 print(a) print(b) OUTPUT: 2 5 ____________________________________________________ Figure 1.09

Or, ____________________________________________________ CODE:

c = d = 4 print(c) print(d) OUTPUT: 4 4 ____________________________________________________ Figure 1.10

In Figure 1.09 above, the variable names line up 1-to-1 with the values, where each is separated by commas (,). The first named variable is assigned to the first value (a equals 2), and the


second to the second (b equals 5), and so on for as many variables as we want to create. Doing all of this in one line saves us a lot of space. In Figure 1.10, all of the variables we wish to create will have the same value. So, here, we can take a shortcut and just say they are equal to one another as well as the desired value (c is equal to d, and both are equal to 4). When programming in Python, sometimes variables will be assigned like varName = (23), for instance. The surrounding parentheses have no effect, and this variable varName will still be assigned to 23. ____________________________________________________ CODE:

varName = (23) print(varName) OUTPUT: 23 ____________________________________________________ Figure 1.11

So, now that we know how to create variables and change their values whenever we wish to, let’s move onto the different types of variables we can create.


BASIC VARIABLE TYPES Variables can hold very different things in them, as we’ve seen. They can have words, numbers, decimals, or whatever else we wish to use. Some of our different basic types are: 1. Strings 2. Integers 3. Floating-point Numbers 4. Booleans First, strings. Strings are a series of characters, like “a”, “5”, “[“, or “~”. If it’s on your keyboard, and you can type it into your code, then it's a valid character to be printed. Strings are always contained within single (“ ”) or double (‘ ’) quotes. Here’s a really long string that contains a bunch of different characters: ____________________________________________________ CODE:

strVar = “yH6-+{/<Hnf1!|&#213LOL” print(strVar) OUTPUT: yH6-+{/<Hnf1!|&#213LOL ____________________________________________________ Figure 1.12

Integers are our most basic type of whole numbers, like “5”, “-10”, “0”, or “12935”. ____________________________________________________


CODE:

intVar = -939 print(intVar) OUTPUT: -939 ____________________________________________________ Figure 1.13

Integers can be zero, positive, or negative. They have no quotes around them, and are whole numbers. You may notice that before we said “5” is a character in a string and 5 is an integer. This is because the first one is surrounded by quotations, making it a word instead of a number. Next you have floating-point numbers, or floats. These are all the non-integer real numbers. For instance: 10.002, 123.5, -92.0, or 0.04. You can also simply print them out: ____________________________________________________ CODE:

floatVar = -23.456 print(floatVar) OUTPUT: -23.456 ____________________________________________________ Figure 1.14

Lastly, it’s time for the most complex type: booleans (not really, they only have two different values). A boolean is a logical statement, they can either be true or false. Here’s an example: if Janet has a pencil, and she says the phrase “this is a pencil” while pointing at the pencil, that is a true statement. However, if she says “this is a ruler”, that would not be correct, it would be a false statement. Booleans can simply be assigned to having true or false values: ____________________________________________________


CODE:

bool = True bool2 = False print(bool) print(bool2) OUTPUT: True False ____________________________________________________ Figure 1.15

Remember, the True and False must be upper-case. The statement bool = true will result in an error. 1 vs. 2 Equal Signs Quickly, let’s look at the difference between one (=) and two (==) equal signs. A single sign means “is equal to”, it is a statement of fact. a = 4 means “a is equal to 4”. Two equals signs, however, is a question. It means “is something equal to something else”, and can be either true or false. If you say that b = 6, then the statement b == 6 is true, while b == 5 is false.

Now, getting back to booleans. We can also assign booleans to the outcome of a logical statement: ____________________________________________________ CODE:

a = 23 bool = (a == 23) print(bool) OUTPUT: True ____________________________________________________ Figure 1.16


In the first line, a is being assigned the value of 23. Thus, we can logically say that a is 23. So, the next line is then evaluating whether a is, in fact, 23: bool = (a == 23) First, the “bool” is of course the name of the variable. It is being assigned to the statement a == 23. Remember, the surrounding parentheses are simply for organization here. They don’t have a bearing on this statement (i.e. the line bool = a == 23 would have the same effect). Since a is 23 here, the claim “a is equal to 23” is true, and so the value of the variable bool is True. This is proven on the next line, as printing bool results in a True output. If, for example, the first line of the program was a = 19, then the code would output False. This is because a is not 23, making the claim incorrect and thus bool be equal to False. ____________________________________________________ CODE:

a = 19 bool = (a == 23) print(bool) OUTPUT: True ____________________________________________________ Figure 1.17


For these logical statements, we also have a few other types of “comparison operations” available to us. In the example above, ‘==’ asked “is something equal to something else”. Now let’s look at some other comparisons we can make: Operator Meaning

Examples

>

“is something greater than something else”

a = 19, b = 14 a > b → True

>=

“is something greater than or equal to something else”

c = 20, d = 20, c >= d → True c = 24, d = 16, c >= d → True

<

“is something less than something else”

e = 21, f = 19 e < f → False

<=

“is something less than or equal to something else”

g = 25, h = 25 g <= h → True i = 14, j = 9 i <= j → False

!=

“is something not equal to something else”

k = 13, l = 19 k != i → True m = 4, n = 4 m != n → False

is

“is something in reference to the same object as something else”

*


is not

“is something not in reference to the same object as something else”

*

*DON’T WORRY ABOUT THESE WE WILL TALK ABOUT THEM LATER Figure 1.18

There are other useful types in Python that we can make use of, such as complex numbers or even entire lists (we’ll talk about those next chapter). But even with the understanding of these basic types, most of your ideas can be built with ease.

MATH Don’t panic. I know that “math” can sound daunting at first, with all of its rules and regulations. But here we’re talking about basic calculator stuff, like adding, dividing, using parentheses, or squaring numbers. With a computer, these operations come very easily to its circuit-riddled brain. It can perform mathematics so quickly that Newton must be a cotton candy mixer in his grave: the average computer nowadays can perform a couple billion operations per second.


Let’s see how you can use a computer as your own personal calculator (just a lot bigger and hopefully not battery operated). Our 6 Basic Operations 1. Addition 2. Subtraction 3. Multiplication 4. Division 5. Modulo 6. Floor Modulo, what’s that? Don’t worry about it, it’s actually not that complicated. But first, let’s delve into addition. Here’s how to add: ____________________________________________________ CODE: print(24 + 3) OUTPUT: 27 ____________________________________________________ Figure 1.18

Here’s how to add with variables, or with 3 different things: ____________________________________________________ CODE:

a, b = 5, 3 print(a + b + 7) OUTPUT: 15 ____________________________________________________ Figure 1.19


All in all, adding is pretty easy in python. There’s also something really cool we can do with a single variable, say to increase its value: ____________________________________________________ CODE:

c = 23 c = c + 3 print(c) c += 4 print(c) OUTPUT: 26 30 ____________________________________________________ Figure 1.20

Let’s walk through this line by line. In the first line, we are setting c to 23. Then, in line 2 we are taking the variable c and re-assigning it to its own value plus 3 (23 + 3 = 26 is printed on line 3). As the compiler reaches that line, the variable c has a value of 23. So we are taking that value and basically using it in our math, as if it was simply a variable in an equation. Then, line 4 is just a shorter way of writing c = c + 4 so that our fingers can have a rest. Now, subtraction: ____________________________________________________ CODE:

a = 34 - 14 print(a) OUTPUT: 20 ____________________________________________________ Figure 1.21

With all the same rules applying as addition:


____________________________________________________ CODE:

d = 4 f = 34 - d print(f) print(f -= d)

OUTPUT:

30 26 ____________________________________________________ Figure 1.22

See, we can even use that one-line shortcut with a different variable (here subtracting d from f). Multiplication uses a *: ____________________________________________________ CODE:

mul = 5 * 3 print(mul) mul *= 2 print(mul) OUTPUT: 15 30 ____________________________________________________ Figure 1.23

Lastly, for the familiar operations, division (/): ____________________________________________________ CODE:

div = 6/3 print(div) div /= 2


print(div) OUTPUT: 2.0 1.0 ____________________________________________________ Figure 1.24

That’s a bit weird, that we’re getting a float from division (2.0) as opposed to what we would expect from 6 divided by 3, an integer (2). This is due to how Python handles division, the result will always be a float. In the second part of this chapter, we’ll go over how to ensure that division results in an integer, and also some other cases where this occurs. But for now, let’s talk about modulo (%): ____________________________________________________ CODE:

a = 20 % 2 print(a) b = 20 % 3 print(b) OUTPUT: 0 2 ____________________________________________________ Figure 1.25

You might have guessed from those examples what modulo does. Here’s another hint: any even number % 2 will be equal to 0. No? Well that’s fine, I always forget what it means too. In division, you have the quotient and remainder. The quotient is the amount of times a number will go into another, while the remainder is what is left over.


The modulo operator gives us the remainder of division, so for the first line: 20 divided by 2 is 10, which means it is exactly divisible. Nothing is left over, and thus the remainder comes out as 0 (and a is assigned to 0). For line 3: 20 divided by 3 is 6 (3 times 6 is 18) with a remainder of 2 (20 - 18 = 2), so b is given the value of 2. The modulo is very closely related to floor (//): ____________________________________________________ CODE:

a = 20 // 2 print(a) b = 20 // 3 print(b) OUTPUT: 10 6 ____________________________________________________ Figure 1.26

Taking our examples from that last explanation, you can probably surmise what floor is doing here: giving us the other part of our division soup, the quotient. 2 goes into 20 ten times, and therefore a is assigned the value of 10. 3 goes into 20 six full times (remember that remainder of 2), and thus b is assigned to 6. With these six operations, we can perform very complex mathematics with Python. The compiler will also take into account parenthesis and order of operations, for instance: ____________________________________________________ CODE:

a = (3 + 4) / 10 + .2 // 100 - 3 * 2 print(a)


OUTPUT: 17.7 ____________________________________________________ Figure 1.26

Just a reminder before we break this whole thing down, the order of operations is PEMDAS: Parentheses, Exponents, Multiplication & Division (and Modulo & Floor), Addition & Subtraction. Python knows this well, and used it on our example: (3 + 4) / 10 + .2 // 100 - 3 * 2 First calculated is the expression inside parentheses: 7 / 10 + .2 // 100 - 3 * 2 Then the multiplication, division, and floor: 0.7 + 0 - 6 And finally the addition and subtraction: -5.3 With some internal logic and knowing how to perform all our basic operations, the Python compiler can be used as a very versatile and useful calculator.

INPUTS Why do you want to learn how to program? So that you can cheat in math class? Have a conversation with a computer? Become the next Bill Gates? No, of course not. You want to know


how to make a game: the best way to show off your computer skills. Well, a game isn’t just you programming a bunch of things for the computer to say to a user. Games require input, and interaction with the code. So let’s talk now about how to get some input from a user. Start off by just writing: ____________________________________________________ CODE: input(“ENTER YOUR NAME: ”) OUTPUT: ENTER YOUR NAME: ____________________________________________________ Figure 1.28

What are you waiting for? Type in your name, be polite. ENTER YOUR NAME: Billy Now press enter. Nothing? Bummer. Now try this: ____________________________________________________ CODE:

name = input(“ENTER YOUR NAME: ”) print(name) OUTPUT: ENTER YOUR NAME: Billy Billy ____________________________________________________ Figure 1.29

See, now that’s a lot cooler. The command input is a function, just like print is. Except, as you remember, for printing you enter what you want to display on the screen, for inputs you are writing what should be the prompt to the user.


Putting input() in your code, when the compiler reaches it, will create a space for the user to enter something after the prompt is printed. Notice how we put quotation marks inside the input(), this is because we are telling it to print the words “ENTER YOUR NAME: ”. And that extra space after the :? Just because it looks nicer when the user types. Now the name variable up there is being assigned to input(), this means that it will have the value of what the user enters. Typing in ‘Billy’ and pressing ENTER will make the variable name a string “Billy”. That’s what we get when printing name. Cool, now let’s try greeting the user: ____________________________________________________ CODE:

name = input(“Hi there, what’s your name? ”) print(“Nice to meet you ” + name + “!”)

OUTPUT:

Hi there, what's your name? Sarah Nice to meet you Sarah!

____________________________________________________ Figure 1.30

Great, we just got the program to introduce itself to the user! You might notice that weird print statement with the name variable separated from the strings with a +. In the next section, we’re going to address this, allowing you to print variables out to the user combined with a message. First, however, let’s bring up another situation that you’ll learn to handle. We want to take user input for a calculator, for example: ____________________________________________________


CODE:

print(“Let’s add sum numbers! (pun intended)”) num1 = input(“Enter the 1st number: ”) num2 = input(“Enter the 2nd number: ”) print(num1 + num2)

____________________________________________________ Figure 1.31

Running this code, and entering any two numbers, you’ll see that the output is just them smashed together. If I enter 2 and 5 here, the output would be 25 instead of 7. This arises from the fact that inputs are always strings, even if they are made up of numeral characters. It’s just like writing the words “3 little pigs” on a document, the 3 can be copy and pasted because it’s just another character (like letters). Here, it might seem frustrating that you can’t just make a calculator. Well, you can, and it’s actually really simple. It just takes a bit of type-casting.

PRINTING TOGETHER & TYPE-CASTING I know, I know. Why are we talking about printing again? Well, before we just talked about “basic” printing, where a single thing is displayed on the screen. Now we know about some cooler stuff like variables, math, and inputs. So let’s learn some skills to implement all of that into printing. In the previous section, we have figure 1.30 that used a variable in the middle of a print statement. It did something like: ____________________________________________________


CODE:

name = “David” print(“Hello, ” + name + “!”) OUTPUT: Hello David! ____________________________________________________ Figure 1.31

Here, we used a tactic called concatenation, which is just combining different strings. We concatenated name onto “Hello, ” and “!” onto name, making a final string of “Hello David!” that was printed. We can do this with different string variables as well: ____________________________________________________ CODE:

name1 = “David ” name2 = name1 + “Schwartz” print(name2) OUTPUT: David Schwartz ____________________________________________________ Figure 1.32

The second variable became the concatenation of the first and a string, and printing it out we got the full name. This is with strings, so how could you do it with other types of variables, say integers? Remember those different variable types from before? Well, they are coming back in a big way. We’re going to have to keep track of what variables are what types. You can’t do math with words and numbers, after all. Let’s get ourselves into the right ‘type of mood’ with a little example: ____________________________________________________


CODE:

num1 = input(“Enter a number to increase: ”) print(num1 + 2)

OUTPUT:

Enter a number to increase: 12

Traceback (most recent call last): File "learn.py", line 2, in <module> print(num1 + 2) TypeError: can only concatenate str (not "int") to str

____________________________________________________ Figure 1.33

There we go, another one of those annoying errors. All we wanted to do was increase the value of an inputted number, and yet we can’t, for some reason. Let’s learn why. Looking at that error, it says we “can only concatenate str (not “int”) to str. Here, ‘str’ means string and ‘int’ means integer. If you’ll remember, input() always gives you a string value This error is telling us that you can’t concatenate a string and an integer. That makes sense, doesn’t it? They are two different variable types that shouldn’t be combined together. Instead, we can use a process called type-casting to use our inputted string as a number: ____________________________________________________ CODE:

num1 = input(“Enter a number to increase: ”) print(int(num1) + 2)

OUTPUT:

Enter a number to increase: 12 14

____________________________________________________ Figure 1.34

Eureka! We’ve done it! We were able to take in a number and add 2.


The difference between this example and the previous can be seen on line 2, where we surround the num1 variable with int() before adding 2. int() is a command in Python that converts the basic variable inside of it into an integer. If it’s a float, then we round down to the nearest integer (say 2.7 → 2). str() will convert basic variables into a string. float() will convert basic variables into a floating-point number. bool() will convert basic variables into a boolean. Cool, so that means if we wanted to, say, build a calculator, we could: ____________________________________________________ CODE:

num1 = int(input(“#: ”)) num2 = int(input(“#: ”)) print(num1 + num2)

OUTPUT:

#: 23 #: 7 30

____________________________________________________ Figure 1.35

Here, we surround the input()’s with int() so that upon user input, we instantly convert it to a number. num1 and num2 reference the numbers the user entered, which we can then print. Or we can improve that introduction from before: ____________________________________________________ CODE:

name = input(“What’s your name? ”) age = input(“How old are you? ”)


months = int(age)*12 print(“Hello ”+name+“, you are ”+str(months)+” months old!”)

OUTPUT:

What’s your name? Derek How old are you? 16 Hello Derek, you are 192 months old!

____________________________________________________ Figure 1.36

Now that’s a much more interesting greeting to our user! First, inputs allowed us to capture the user’s name and age. Converting that height into an integer, we used it to calculate their age in months. We then displayed a greeting which contained that newly calculated age with a conversion back to string. For printing in particular, we have a helpful shortcut so that type-casting isn’t always necessary: ____________________________________________________ print(“String”, 23, 0.75, False) CODE: String 23 0.75 False OUTPUT: ____________________________________________________ Figure 1.37

Here, in a single print statement, we were able to print all these different variable types with no hassle. This is because we used the comma (,) which lets us print any number of things, one after another, with a space in between them. I use this a lot, and it makes printing so much faster when you don’t have to focus on ensuring everything is a string. Speaking of strings, there is one last way to implement variables of different types within a string, and it is a lot more straight-forward. Let’s now take a look at:


STRING INDEXING, FORMATTING, & EXTRA TRICKS Strings, as you may have noticed, are pretty important in Python (and coding in general). I mean, you’re gonna want to be able to actually talk the user through what’s going on. Be it a loading bar, a message, a prompt, a form, strings of characters… are pretty useful. And don’t even get me started on String Theory, that’s a story for another day. In Python, we have plenty of ways to play with strings, here are some examples: Concatenation: ____________________________________________________ CODE:

firstHalf = “This is first” full = firstHalf + “ and this is second” print(full)

This is first and this is second OUTPUT: ____________________________________________________ Figure 1.38

Multiplication: ____________________________________________________ CODE:

str = “hi ” print(str*5)

hi hi hi hi hi OUTPUT: ____________________________________________________ Figure 1.39

Or, a favorite, Indexing: ____________________________________________________


CODE:

word = “cow” print(word[2])

w OUTPUT: ____________________________________________________ Figure 1.40

That last example is deserving of an explanation. Here, we made a string variable word that contained “cow”. The square brackets next to the word are us indexing it: taking a portion of the string or object, and using that portion independently. Here, using the 2, we are telling Python to capture the character at index 2, or the third character “w”. How Computers Count While you or me might start counting at 1, a computer starts at zero, going 0, 1, 2, 3, and so on. This number, in reference to a place in a list or counted group, is called an index. For example, in a group of people Karen, Soham, and Kat, the first person “Karen” is in index 0, while “Soham” is in index 1, and the last person in the 3-person-list is in index 2,”Kat”. If I have a word, “PIZZA”, indexing it would be looking at the list of characters it contains. Index 2 of the word is the third character, “Z”, and indexes 0 to 2, or [0:2] is the portion “PIZ”.

While figure 1.40 shows us taking a single character out of a string, we can also index them in other ways: ____________________________________________________ CODE:

sent = “please don’t panic” print(sent[0], sent[:3]) print(sent[4:8], sent[13:]) print(sent[3:-3])

OUTPUT:

p ple se d panic


ase don’t pa

____________________________________________________ Figure 1.41

Now, while this output might seem nonsensical at first, let’s look at it line-by-line: First, we set the sent variable to “please don’t panic”. Remember: spaces (“ ”) count as characters. Then, print(sent[0], sent[:3]) resulted in “p ple”. We indexed sent and obtained the first character, pretty straight forward. Then we used a colon (:), which here means take a range of indexes. We took the range from the beginning of the string to index 2. The colon (:) in indexing means start at the index to the left, and then stop one before the index to the right. When no index is provided, then use the ends of the string or object. So, now, the print(sent[4:8], sent[13:]) that resulted in “se d panic” first took the range from indexes 4 to 7 or characters 5 to 8 of the original string. Then, we took the “panic” by starting at the 14th character (13th index) and going until the end of the string. Lastly, the print(sent[3:-3]) used negative indexes, which start at -1 for the last character. This portion went from the 4th character in the string to the 4th last character, or “ase don’t pa”.


I mentioned earlier that there is a much easier way to inject different variable types into a string, and we refer to it as string formatting. Let’s take a peek at an example: ____________________________________________________ CODE:

num1, num2 = 3, 2 print(“I have {} cars and {} dogs!”.format(num1, num2))

I have 3 cars and 2 dogs! OUTPUT: ____________________________________________________ Figure 1.42

Here, we’ve made two variables that hold integers. We then print out a string, and using our new .format() command insert two variables into the string in place of the brackets({}). We can do this with as many variables as we want, separating them each with commas. Here’s even a handy trick we can use for, say, dollar amounts: ____________________________________________________ CODE:

amount = 3.423 print(“${:.2f}”.format(amount))

$3.42 OUTPUT: ____________________________________________________ Figure 1.42

Here, we’re using the same formatting style as in figure 1.41. Except, inside of the brackets we have this “:.2f” notation. This is just us saying hey, Python, I want you to round this number to 2 decimal places when you add it to the string. If we wanted to use


all 3, we could say “{:.3f}”, or if we needed an extra zero at the end we could use “{:.4f}”. Anyway, here we are: at the end of chapter 1. You now have all the basic information needed to build a large assortment of different Python programs. These objects, these variables, are the basic foundations of programming, and now you know how to utilize them to display some cool stuff. Next, we’ll talk about some more complex data structures past basic variables, and then jump into using all of these concepts to implement some logic into our programs. Now let’s continue onward with your journey, and “may the {}’s be with you.”.format(4).


Turn static files into dynamic content formats.

Create a flipbook
Python for Beginners by mechele7 - Issuu