PYTHON TUTORIAL! - CS50 Live, EP. 63
Skills:
Python for Data80%
Key Takeaways
Covers the basics of Python syntax for complete beginners
Full Transcript
all right hello world this is cs50 live my name is Colton Ogden today we're joined by the man himself David Malin hello everyone good to see everyone on stream and not just in the chat today we are doing something pretty cool today pretty fun we're doing a from scratch of Python tutorial and my understanding is that you've actually brought some questions and topics problem challenges that I haven't seen that we're gonna implement and I'm gonna sort of be a proxy to somebody who maybe is learning for the first time indeed so I'm gonna pretty much assume that Colton may or may not actually know Python and so along the way we'll try to solve some problems actively by a coding we'll pull things up by Google or Stack Overflow as we go and frankly try to approximate the experience that Colton and I arguably do every day when we're writing code to sort of figure out problems that we cannot get solved sure I guess maybe we should start off first off by maybe explaining what Python is and the honest folks we've advertised this as sort of an experience for people who may not have even programmed or read but at least have not programmed in Python before yeah so why don't we assume that no one here is really that familiar with Python but if you are that's fine hopefully we can fill in some gaps in your knowledge stop us at any point via the chat if you have a question there's no dumb questions here if we take them for granted that you know what some top concept is or some function is or some feature just chime and say hey everyone what what did they mean by that and so that we can answer here on stream so Python is a very popular programming language it's a little different from languages like C and C++ and a few others that you would traditionally compile recall that if you've ever programmed in one of those languages you have to actually run some program called a compiler to convert your source code the text that you write to machine code the zeros and ones that the computer actually understands nice thing about Python is that we don't have to do that what would is you want to characterize Python for folks to distinguish it from that process yeah no I mean Python is nice it's it's essentially it runs almost in this it's called a virtual machine but it's almost like having a computer inside a computer and it executes these you know with the traditional programming language you're writing text and I'll switch over to my computer here just that we can maybe frame this visually a little bit better but not Chrome in BS code by the way this is my text editor of choice it just vs code you need in order to any source code some sort of text editor application you can even use something like text edit for example if I pull it TextEdit on my Mac it's a I'm not sure what that email is there but I think that might have been from another stream but essentially what you do is you you have some program that you can write text into and usually you don't want to write it in what's called rich text or you have formatting you write it in plain text like this and you write your instructions to the computer a bunch of lines tell the computer icon no this isn't quite Python not unless you're unless you don't know how to write good variable names to say this might look and this might be some people's Python code but you essentially go through and you write a set of instructions for the computer like this top down and the computer will execute them but computers don't understand arbitrary textual information the computer can only speak in certain languages computer labs specifically its own machine code which is binary code which we talked about in cs50 one of the more underlying principles of that David has an awesome chance of lectures on our YouTube channel but long story short somewhere along the line you have to convert all your instructions into something that the computer can understand and with traditional language that you alluded to before you do this with the help of a compiler they take this text and end up translating it into you know they basically this which is the computer's native sort of tongue mm-hmm but how is Python different here python is different in that it doesn't actually perform this step explicitly along the line it still actually happens but it basically translates all the lines that you've written when you just load the script into the program that is itself called Python yeah and you can think of Python then is an interpreter this sort of middleman that translates between what you write and what the computer actually understands so you can think of Python the program which will run in just a couple minutes is a program that reads your own code top to bottom left to right and it just does what you say you don't have to actually use something like Visual Studio or GCC or clang or any number of other compilers explicitly all of that sort of happens before you automatically thanks to the interpretation process along the way in D you can even fire up let's see if if you have it installed on your machine for example here I have Python three there's two different versions of Python 3 long story short Python 3 is the new way the way that is going to be the official way very shortly as of 2020 but if I type Python 3 and my command line assuming you have it installed you can see that I actually have this sort of prompt here these three arrows which append I can actually type in instructions and it will immediately execute things for example if I wanted to say print David J Malan like like this assuming that I type it correctly it'll actually literally do it without needing to do that intermediary compilation stuff yeah absolutely this is an interactive interpreter so we'll just do what you say the downside of course is that we're not really saving any of our work along the way so it's better generally to write your programs in an actual text editor like vs code or sublime or atom or something else so that you can save your code and let the interpreter run it and rerun it again and again so why don't we go ahead and do that you want to go ahead and open up a blank editor window so for those of you following along at home if you want to go ahead and Google the S code or Visual Studio code you're welcome to download the same program for free atom sublime text and notepad plus plus and a bunch of others are very popular on Macs and PCs and Linux machines but odds are if you're tuning in you probably have some form of text editor but if not feel free to try one of those and then what you should also do if you don't have it already is make sure your computer if you do want to follow along has Python installed so again python is not only a language it's an interpreter a program that will understand your use of that language and if you go to python org slash downloads you'll find yourself at the official website where you can download the python version 3 installer to make sure that you have that on your machine depending on how your machine was configured you may have Python already as Colton said but it might be an older version Python 2 that's officially going to be end-of-life soon that is it's being phased out in favor finally of Python 3 so everything we do today is Python 3 specific but beware because when you're googling when you're looking on Stack Overflow there's a lot of good answers to old Python code out there so you don't want to be led astray Simo has a sweet comment says david because of you i stopped playing video games all day I learned it have a real job at an ecomcon wow that's amazing I see Andres taking exception to the fact that we haven't promoted Idol there's a few other IDE s and editors as well this is not an exhaustive list what's nice about things like vs code is that they are first and foremost a text editor and you can layer more features on top of them somebody asked out what the s code am I using I think I'm using Dracula right now it's just at the end of the last stream but I actually prefer the noctus theme so look real quick just the important stuff out of the way first this has nothing to do with Python but we're gonna switch that Noctis color that's the one that I recently have like but they all a lot of the defaults look very nice nice and you want it let's go ahead and get rid of the Explorer for now but let's just go ahead and save this program as hello dot pi so hello is gonna be the name of the program pi indicates that this is a Python program you don't need number three anywhere in there you still just use dot pi so our first program well let's keep it super simple and literally write the program that everyone in the world seems to start writing code in which is just hello world so instead of David J Malan how would you go ahead and Python and just write a program that prints out literally hello world I would I would use the print function which comes with Python and actually the nice thing about vs code is that it gives you a lot of this sort of built-in intelligence depending on how you like to develop or it will actually tell you when you write functions you know sort of what the function it what the function expects what it does so this is a nice thing about modern text editors and integrated development environments IDE using and you said hello world so I'm just gonna type in the string hello world and that's it yeah but some and you'll notice now that you get syntax highlighting with programs like this I see there's a shout-out to Pi charm as well which is a popular editor for Python as well yes we do know that IO might come with the default installation but we're just we're just focusing on Python today you can use any text editor out there that you would like it's amazing folks in the chat are actually typing typing some responses to what you said in is that actually this is kind of interesting because garage burrs wall actually says print hello world and if I'm if I'm reading that correctly he actually said or he or she actually said hello world now if we try to do you think we should try and run this and I don't like the squigglies things I suggest that there's a mistake of some sort so okay undefined variable hello and this says unexpected token world interesting so let's come let's come back to that though because I think we should run the program first because while we have arguably written a program now we haven't actually run it previously when Colton ran the program called Python 3 he was able to write a line of code hit enter and immediately was executed but typically the paradigm of course for writing code is to write one or more lines of code save it in a file and then somehow execute that file so I think to execute this file hello dot pi we're gonna need a terminal window sure how do we do this so I already have one so this is the Mac native terminal application windows has the same thing with CMD linux i actually know what's called on linux what's it called of linux terminal terminal or x term or any a bunch of other things and so I'm actually I'm still in the Python show I'm gonna clear my screen and then this is assuming that I'm actually in the directory where we're doing this code so right now we are at my I believe dev is that PWD that tells you where you're working yeah so this is per present working directory I'm here users J Harvard dev I want to actually go into where I just created that file which is streams slash Python tutorial and I believe that is where I created it and you'll see I hit LS for list and then if I type in Python 3 like we did before to open up the interactive show but instead I say hello dot PI after that we'll see that it actually outputs exactly what we wrote in the source code you know and while trivial go ahead if you could go back to the terminal window and just literally run Pi Python 3 hello dot PI again this should go without saying but because the code is saved in file you can of course repeat your steps you can improve on the program you can fix bugs again and again can't do that as easily in just the interactive Church really you lose all that state they've created as soon as you exit the interpreter in that context so the place we usually start when introducing Python to other students is to actually now make the program actually interactive like a program that just prints out hello world while sort of nice to be part of that history for posterity it's not particularly interactive at all beyond just running it so how would in Python you go about asking a user for his or her name and say hello so and so instead of just hello world all the time well it's common in a lot of languages that you get some sort of input function Java has one system dot was its you create a scanner at system dot in C use a scanf and in Python it's actually pretty easy all you have to do is just say let's just say I want to store the user's name in a variable called name and then I'll sign it whatever the return value of this function input is and notice that I'm still passing in this string hello world because when I ask them at the command line maybe I'd presumably want to prompt them for something or maybe say in this case not hello world but please enter your name colon space okay and then if I wrote let's try it out let's go ahead and run it so he notice Colton is using some keyboard shortcuts he's sitting up on his keyboard which on a lot of computers will actually rerun the previous command and you can keep hitting up up up up to go to previous commands further so I'm already realizing there is gonna be a slight issue with this so please enter your name let's say my name is Colton and the program is over nice which is expected yeah I mean you only wrote one line of code that is asking the user for input prompting them for their name and then storing that value over on the other hand side the other side in the name variable so what do you want to do next well now since I have name actually stored somewhere I've set name equals or against the value of input please into your name I can actually reuse that variable so I can say print hello space and then there's multiple ways to do this which you might have time to look at but all for now I'll just say hello and then I'll actually add a name to that string like that yeah so what's this plus I mean we're not doing addition here no so this is common in light in a lot of languages if this is a term called concatenation where you're not actually adding numbers you're actually adding strings you're basically taking one string and sticking another string right at the end of it now in the common operator for that use case and there are multiple operators across different languages but common is the plus just because it's kind of intuitive okay all right well let's let's go ahead and run this it's now two lines of code Colton has saved his file he's going back to the interpreter and running it on this file and we say hello comes to work now it's kind of a it's kind of a cold hello if I wanted I could probably add maybe a exclamation point at the end of it just to make it a little bit more you know I guess inviting or friendly or an unhappy face to see you oh sure I could say I could say hello Colton there we go now unfortunately that's gonna princess my unhappy face for everyone not just Colton but even me and for you so why don't we go ahead and change this I feel like in a lot of programming languages that we've seen that folks out there might have seen you can do things like conditions you can do something if something is true else you can do this other thing so could we modify this program in Python to maybe be happy to see anyone except you in which case you should see the unhappy face wow this feels like a depressing Hayward this is this is what the audience is requested how is this okay so we'll say okay so well we're gonna get the name and then I want to basically check to see what the value of the name is Craig because you said we want the frown to only appear whenever it's me and otherwise exclamation point I'm assume anything else really anything okay so we'll say we'll keep it simple so I'll say if name is equal to Colton : so this is a Python thing if you want to do an if statement you Cokely not : yeah Colton : then you say we'll say print hello and then we'll do plus name plus and I guess in this case we can even hard code the name since it's specific to this use case and then we'll we'll do the frown actually put a space in front of the smiley face because it was getting put right on me let's make sure we see how unhappy we artists yeah exactly and then we'll just do this other you know thing if that if statement doesn't turn out to be the case if the name is David or anybody else literally in the entire universe then we'll just say else would do what we did before which is just print the name and then in this case though we do want we do want the program to be happy to see who it is so we'll do an exercise so let's run this and then let's come back and we'll tease apart some of the syntax that we've just added sure so we'll say first of all we'll say David so hello David so if he was happy to see you very nice and polite how about can we do another one can we do how about Richard Richard Richard okay so please don't your name is Richard okay delightful to see you as well okay focus II Richard now let's let's test to see if our functionality is correct ar-ar-ar I guess one off use case and we'll use my name Oh perfect this is man this is a good program so far we have a smart smart program that knows the appropriate way to address sort of though can you run it one more time and it's like an angry person can you type your name in all caps this time oh sure absolutely so I'll say Colton oh it's happy to see ya no this is a bug this is objectively a bug so maybe we're gonna take a look at a couple of other syntactic features but especially if you're a little new to programming but you have the right intuition here if folks in the chat wouldn't mind proposing what techniques we could use to actually solve this problem we'll go back in and fix it in just a minute or two Congress that's a feature by the way that no that's a bug that's a bug but let's go ahead and back to the code for just a moment well folks propose some solutions here perhaps and there's a few questions I had for instance if I'm coming a Python new what's with the colons like I'm used to the indentation but the colons when we're the curly braces the so the nice thing about Python is there are no curly braces mm-hmm the the interesting thing about Python is that everything is based on white space so indentation that blocks no I mean this is something that folks may or may not be familiar with but denoting that something essentially is inside of something else is done with indentation so this if statements like body of code that executes when it's true we don't use curly break braces like we do in other languages we can't in wait we can't inline it but you would instead of doing something like this and then having and I actually I'm not 100% sure I think this I think technically is it technically possible to you know it's not I'm getting that conflated with I think something else but you don't have another stream entirely but moving on you you don't need these things you you can all you just need to do is make sure this is indented a certain level within this after this if statement here and now without opening a can of worms what's your preference you like tabs you like spaces I like tabs that get converted into spaces okay I'll take that as an acceptable answer indeed in the Python community unlike most languages there is an accepted norm or at least a recommended norm which is to use spaces so let's put an end to that debate today we're gonna use spaces for spaces generally would be pretty common but I like that you don't have to do the the curly braces as you know but I notice you're also using single quotes and I feel like in different languages and even in Python I sometimes see single quotes sometimes double quotes how do I think about that so there are for the for the large part interchangeable you can make strings with double quotes you can make strings with single quotes now if you're coming from a background like C or Java you can only use double quotes for strings but you have to use single quotes for single characters okay Python there's no difference there are no there is not really a by default single character versus string when you're using you know this apostrophe character or the double quote character so how would people go about deciding whether on a single quote kind of person or a double quote kind of person well I think that's a matter of taste but if you are use if your string for example contains let's say colton's favorite food pizza we can see that there's an issue in that different in that we see the green that we've seen before with strings after this apostrophe up until this apostrophe where we're actually using it for grammar we're actually using it as a part of the string itself and there's a couple ways of dealing with this one way is we can use the backslash like this and that'll fix it so now we've actually said ignore this apostrophe this is part of the actual string yep Jeanette Jeanette sax notes that as well nice but let's say I don't like the way that looks I don't like having a backslash to start my strings all over the place instead I can decide in any case where I do have a single quote inside the string itself I'll use double quotes on the outside and because this doesn't match up with this it doesn't cause an error in parsing the string nice yeah an augment I'm kind of going through an existential crisis I've been using double quotes for like 20 years and frankly I'm tired of holding the shift key down and I do think you're seeing in more modern Lee popular languages Python and JavaScript among them I'm starting to see frankly I think single quotes more often but you got to beware because of the stupid grammar issues alike so just be consistent I think is the point or resort to one or the other when you have two contextual e-commerce a big fan of single quotes itself as well don't like whole event sure yeah yeah I know too much shift at 20 years of hitting the shift key is enough somebody proposed an interesting way of getting around the the problem yeah let's come back to that I heard someone propose that we use lower so force the whole string to lowercase I see Richard proposed using an array or a list in Python where we could check for little Colton or big Colton or alternating caps Colton I think the downside there is that you're gonna have an annoying number of permutations of Colton's if you will with the C is capitalized or the O or the L or multiple ones and so forth so I like this lower ID and this is actually pretty conventional in a lot of programming languages especially Python when you want to compare something for equality you canonicalize it so to speak you force it to all lowercase or all lower all lowercase are all uppercase so that you know definitively what you're comparing against but you don't want to do it destructively you want to do it essentially temporarily on a copy of the variable right exactly so how could we do that here to make sure that we are unhappy to see you well we could say essentially here's here's what happens I guess we should demonstrate this in the terminal before week before we do anything else so I'm gonna pull up Python 3 and this is a nice thing actually at first what I'm gonna do it's gonna clear my CLI and then I'm gonna pull up Python 3 if you're ever curious about using a function in Python this is the downs this is the upside and being able to use it in an interpreter context you can actually just fire up your interpreter and just test variables test functions right away and I happen to know that there's a function called dot lower it works on strings but let's actually experiment with it so if I say let's let's do for example the string Colton and we'll say the lower parentheses and we'll hit enter and we'll see that indeed brings it all down now this is weird why do you have a period after a string don't you need to do with that on like a variable or something so this is then this gets into kind of the idea of what's called object-oriented programming which we won't dive into today but essentially every string in Python has a series of functions that it has its own reference to and the function when you when you call it using this dot which essentially means go inside of the thing to the left and then exit this thing that belongs to that thing on the left in this case the lower function sort of belongs to this string Colton it will run this function and sort of implicitly pass in this as a parameter to this function yeah so what you really have is that Colton is indeed a string in this case in a string is an actual object I can create a class in Python so it has all of these phone bill tin to it just one of which is this this lower function so I see hasanul e proposed I think what's actually a perfect solution and that's a little simpler and less code to write than something like a list based approach so we want to deploy Hasan's approach sure so first before we do that let's just test it again so we have the the version where it's my name type normally let's type let's test it with the version of my name and all uppercase which does also go to the name Colton and then just for just for kicks will do will do all my space style text and then we'll show an area there we go okay and then we'll see that no matter what permutation of capitalization we use we are unhappy to see you yes exactly come with a better town to the same base case so I'm gonna exit Python and then we'll adopt what was it Sean said which was if name lower is equal to not not to Colton with a capital C because that would that won't work there will never be any capital letters you're right alone I think well andrey caught it there but and I overstated we do have to make one tweak which is just replace that with a lowercase C indeed and if you run this let's go back here and we'll do Python 3 of hello dot pi again which I could have just hit up probably and we'll first we'll try it with my name like this okay hello Colton it's a it's a frown okay so that was the behavior that was happening before let's try it again but this time let's let's do just the first few couple letters capitalized oh oh but here's the interesting thing is actually okay nevermind it's still printing out Co a nice feature would be to have it print out the name with just a capital letter and not you should say cuz our next challenge is gonna be exactly that so your user does miss type his or her name in some stupid way like Colton video capital C capital o l3o in classic Colton we can at least with some probability fix this in code now I say some probability because at least in English there's a lot of names that have a mix of uppercase and lowercase characters O'Reilly for instance is a last name also the the name on a very popular series of computer science books you might know so we could get this wrong but let's assume that we have very simple names in this case like Colton Capital Co how in Python could you force the users input to be neatened not all lowercase but capital C and then lowercase Olten well my first instinct would be probably to use this named lower as our starting point well we'll bring everything we'll canonicalize all the names back to all lowercase like this and this actually let's actually start with that so we'll go name dot lower actually other way around well actually no will do in both cases we'll do in both cases so now you'll notice that I'm printing named lower in the actual output for both situations and what we've typed into name so that way even if we type in capital C capital o LTO n it's still gonna give us the canonicalized strings and not the best design but we'll get there well let's try this out so we'll say this plays into your name and we'll try Colton like that and it doesn't need say hello Colton with everything lowercase we're halfway there yeah I'm still have to now do the very first string okay and the first character and the first character in the string so I actually offhand don't know what function strings might have to capitalize the first letter but the chat though so the chat happens but don't know looking at looking at how would you do this if you were home alone with that a live twitch stream to answer your these questions for sure so I would probably say Python capitalized first letter string so have the name of the language is the first word cuz it's probably gonna be a major thing that Google optimizes for and then just literally kind of the main words that I care about in the query for what I'm looking at which capitalized not you know we explore the first letter in a string yeah and this is something you learn over time and odds are most everyone in the chatroom is learning this already you don't have to ask Google or Bing or whatever you use full sentences you can drop the words that really aren't adding anything to the query like how and and it and is and really just focus on the words like Colton has here that really have more information content for the research engine exactly somebody I'm gonna do that query and the Google is amazing the first result says in Python the capitalized method converts the first character of a string to capital letter uppercase letter if the string has its first character as a capital it returns the original string yeah and I don't use this particular site too often myself geeks for geeks or but it seems on point and just for kicks can you scroll down just so we can see what some of the other search results are sure so we're seeing stuck overflow is number two stuck overflow is number three a blog is number four programming program is calm is the next so you'll start to see patterns in search results if you're learning programming or teaching yourself Stack Overflow is a big one but sometimes Google thinks that it's pretty sure what it knows what the answer is so it'll just bubble it up special to the top oh all right so let's try this but shout out to those of you in the chat juban three and davis 216 all of whom got this and major if thats if i'm pronouncing that right also at a clever solution but arguably you're reinventing a wheel and i would propose that in python you really try to reuse some of the wheels that have been given but odds are underneath the hood capitalized is doing something quite like that but probably with some error checking just in case name is short indeed so we'll say name dot lower now this is an interesting thing so when we call this method dot lower it's actually returning a string and new stream and then that's essentially what we're doing here we're returning a new string and putting into the output we're returning a new string and comparing it to the string colton so the cool thing is that you can actually chain these methods onto themselves so I can say name dot lower which gives me the name Colton in all lower case or whatever name and all lower case letters but I can then do dot capitalize like so and what this will do is this will say okay give me the thing give me the dot lower method of the thing to the left okay and return it so this will give whatever the name is all lower case letters and then this becomes essentially that then when you call dot capital wise it's doing the same thing and saying give me the value to the left and then capitalize its first letter that thing to the left is now that lower case straight now when you hover over capitalise based on the definition of this function the BS code is feeding us here do we need to force things to lowercase first and how would you go about figuring that out I returned a capitalized version of the string more specifically make the first character have uppercase and the rest lowercase ah that's interesting I actually didn't realize that that was part of the signature well let's try it then in that case so let's say if name dot capitalize name capitalized and in this case I mean we could even we could even do it here and just and say Colton and then dot capitalized let's try it out so let's say the name of Colton first okay hello Colton let's try see Oh LTO n whoops nice man look we have a whole new problem and how do we fix that problem we get better at using the terminal oh it turns out that that actually worked a few steps ahead of us right and so besides trial and error like we just did too you can certainly read the official documentation in fact just so folks can see it if you've never seen pythons documentation it's so-so like all the and well most of the information is there but it's not always that easy to find what you're looking for dave is not a huge fan of the Python document so it could be much more user-friendly so can you go ahead and find us the documentation for the stiring classes capitalized function yeah so we'll go to STR which is the string class in Python a string object type and we went right here string capitalized and it looks like it's almost the important verbatim so yes codes probably getting its instructions right from here but this is good that we have the documentation up and notice how it's ordered you have on the Left indented all of left aligned you have all of the function names in that class boldface no less capitalized case fold Center someone in the chat just a moment ago proposed title the title function is there a title function inside the string class let's go ahead and look if there's is title its string title yeah so this is title case version of the string or word start with an uppercase character and the remaining characters are lowercase so this would be great for four full names yeah assuming no weirdness with like lowercase letters needing to be lowercase still sure but yeah absolutely so we can maybe even experiment with that so if I were to say let's go back to the s code let's say it most specifically maybe there's a Colton Jackson that we that we'd like to see but Colton Ogden is the one we don't want to see so why don't we go ahead and test that out so we'll say name title is equal to because remember title doesn't capitalized us but to multiple words in the string so in this case we don't have just one word we actually have two words separated by its space so let's go ahead and say named title and name title and there is a better way to do this which we should probably also take a look at in just a second as well so we'll go ahead and run this code and I'm gonna enter my name as Colton Ogden but all lowercase letters still don't like them oh it looks like you figured it out nice and actually smart programming this is this artificial intelligence and this is the very this is the seed for artificial intelligence your six-line state-of-the-art you know I would propose here too we are using on line three title to compare against Colton Ogden capital C capital o yep I admit I don't love that maybe you can convince me otherwise it just feels weird to not just choose something super simple like all lowercase or all uppercase right because this assumes that now I have the sophistication or my colleagues know what title does and therefore this just seems a little more fragile would you agree or disagree I think I would large they agree I think I would say I think I would say what I don't like the most is that we're using name title dot the dot title method specifically in three places that for sure but I don't like title for formatting but for for quality testing personally I would suggest you use something that's absolutely robust all lowercase all uppercase or another technique altogether but we'll get there in just a moment again and another something good up my sleeve for you yeah well dot lower lower probably be better sorry so change that's what lower which this - dot lower and then here's a nice little shortcut if using vs code and your highlight something let's say I want to edit this and this whoops this at the same time so I actually highlight this and if I hit command D or control D on a Windows computer I actually have multiple cursors so now I can actually go over here and type lower amazing in two different places it's typing twice as fast as I could have in my day there we go so let's let's take things up a notch if we can because you know you have a middle name right a lot of people have middle names and we want to make sure that we want to be unhappy about all Colton Ogden's not just you specifically so how could we go about adapting this program in such a way then it is unhappy to see Colton something Ogden or Colton something else Ogden so that there's a Colton at the beginning and OGG and at the end we don't care what's in the middle but there can be something in the middle how would you go about solving that problem a middle name middle name yeah but one name two names arbitrary number middle name I just don't want to see any Colton's over here or Coggins over here okay sure so in this case what we can probably do is figure out well first of all we're gonna get input in a string of some kind and it's gonna be this presumably space separated names no kind of sure so they're in Python a nice thing that you can do is you can actually do this thing called split and split a string okay so let's go into the end of the terminal here and actually pull up the interpreter and you know I like this because you just want to play yeah exactly let's just get a sense of what the function looks like and so I'm indeed answered the questions in the chat yes we're essentially at the moment just trying to get the first word in the last word yeah so we'll say let's say I have Colton Ogden here in a string and I want to split it into its constituents because so I'll just do thoughts split which is another method inside of the string class exactly and well we have some interesting syntax here but it looks like it did find my first name and it separated out my last name and what are these square brackets around you why am i seeing that so these square brackets are indicative of what you might have seen in java or c an array but in Python it's called a list and the nice thing about lists and python is that they can be of arbitrary size they can grow dynamically you don't have to allocate memory for them if you're coming from a more statically based background yeah and I'm smiling because the sandwich in the chat here is proposing that your sample middle name be Colton McLovin Ogden which is a great reference to a great movie question here about can we use the in operator from Richard because if the name is double bare bare double barrelled that wouldn't work so in just tests for the presence of a string anywhere and the string beginning middle end or anywhere else in between so it doesn't feel like the right fit we deliberately want to check the beginning and the end so I think the road we're going down is at least one approach that we can take yeah can someone who says stir it up fine as well but again I think that would also do lead us down the same track something stir it up find just literally finds whether and not a vision asks what if someone has to plus middle names that - we want to be sensitive - so how it let's let's go ahead and well I don't I don't just like the approach you're taking just splitting on the strings but how do I go about checking for colton at the beginning in Ogden to the end and can we try and like mclovin and maybe a two-word middle name just to see what the result looks like yeah I know what to code for so calling the glove and Hodgdon which is fantastic and actually you have three you have a David J Malan as your name we'll use that as well so let's split that so again it worked just like you did before even though we have three names instead of two it's split on spaces can I see four names that's this good we'll see David J McLovin Mela nice that's a mouthful and we'll split that and okay so every string from the original string ends up inside of the list it does so really we want to check the beginning of the list and the end of the list for Colton and Ogden and unhappiness we do and lists are nice in that you can just reference if you want a specific spot in the list you can say let's make a list here which has five numbers in it well actually for confusion let's not do that let's say I have apple orange and banana as a list and we can have just use our names as well but if I want to get a specific element from the list I can use what's called an index and this is a numerical index so lists start their ordering of their elements at zero so for example in this case L at index zero is Apple and wise one if it's the first element cuz computer scientist that zero is how they like to start numbering things in a program three things you know what Lua is one indexed scratch just wounded next to yeah okay presumably for user-friendliness maybe because Lua I know Lua was originally designed as a config language for less technical people and then scratch is a programming environment for people that are fresh to programming in computer science but ironically it just ends up confusing because then they eventually have to change yeah their transition to C or the Java or whatever now what's this is zero is that a number one on the left no that's an L and L is just a shorthand in this case for a variable for list L for lips and you can this is typically frowned upon you don't want to use a letter as a variable name for most circumstances outside of maybe some context we'll we'll get to a little bit later but in this case I just wanted a quick list so I'm gonna just use L again and what L looks like a one and a mono spaced font if I use these brackets just like we did for the actual to actually show the list itself but I say L at index zero this is how you can almost like almost like a box if we're thinking about it like there's little boxes little cubbies for each individual spot in our list mm-hm if we do this we'll see that L at index zero returns Apple okay L at index 1 gives us orange I am and L at index 2 gives us banana so everything is sequentially laid out and what fruit are we gonna see it L bracket 3 ooh that's a good question it looks like Python is smart enough to know at runtime whether or not we're actually indexing outside of the rainbow we've allocated for our list so in languages like C and C++ by default you're typically going to see no error but you're gonna be touching memory you shouldn't or the program could even crash if you do something like this this of course is an exception we'll talk about that perhaps in another stream but it's a way of handling errors and similarly what is l bracket negative 1 for instance can we go to the left oh yeah solutely so L bracket negative 1 now this this would cause chaos I think if you I'm really worried about this is gonna break the computer Oh interesting so Nana L negative one gave us it looks like banana the last element of our list interesting now why is that well it looks like it turns out that in Python you actually get this nice little syntactic sugar for indexing into your array from the and not the head so to speak the end of the list as opposed to the beginning and you know starting at negative one and going and backwards negative two negative three you go from the end of the list actually to the front of the list of the head of the list so what's l-bracket negative to going to bell bracket negative 2 gives us orange which is again one further from the back of the list an L Bergen negative 3 o and indeed all right so this is actually really handy when you want to do something relative to the end of the list but you don't want to have to do all of the math yourself necessarily you can just jump immediately to the end if you know the index but the catch here is that I think when we go back to your text editor we need to be robust against names with two words three words four words so how can we go about modifying this program now in hello dot pi to check that the first element in the list is Colton the last element is Alden but we don't really care how many other things are in between because I don't think we can hard code 0 + + 2 or 0 + 3 we need to figure out how many elements are in the list first right sure so our first step would be again to break the string up into its constituent parts inside the split method so we can do that here so we can say if well there's a few approaches we can do this we could do names and actually take name dot split nice and now we actually have another variable not with the whole string but with the individual names that make up the string that we passed in okay nice so now what we can do is we can say if names 0 because I remember again if we're doing if we're indexing into our list at index 0 that's the very first element in our list and we want to check to see if my first name if the first name in the list that we've entered is Colton that's what we care about so we'll just say if names 0 equals Colton and now here's the thing there are two conditions though because we could get a Colton Jackson a Colton Smith or what-have-you but we care specifically about Colton Ogden you know and so the others are delightful this is there are two actually two conditions here that we care about not just one condition and the nice thing that Python lets you do is actually say okay if I want to check for two different things I can just say if something and thing then do something if two things are true cut so you literally just say and you say and so I'll say if it's the case that names zero is equal to the string Colton and names if I can type names at negative one again the last element in the list no matter the size is equal to Ogden then we want to probably not say name dot lower probably actually just say name dot well in this case we do name not capitalized name stuff what was it title I guess we can do name that title and then name that title again for the actual printing out okay you know the other thing here though is that if it's if in this case we literally have the string Colton or literally this chain table then it'll work but if we have if we've missed types like we talked about before it's not gonna work yeah I don't like that so where should we do the lowercase trick for instance like we did last time so what we can do is I can say name dot again lower and force everything to lowercase initially split exactly so you'll get back a whole bunch of lowercase pieces now yeah this name even with the spaces all of the words all the letters that are alphanumeric are specifically alphabetical or going to be given a lower K they're lowercase version okay and so then after that I can change now we're not comparing for the capitalized C we're actually comparing for the lowercase because everything's been canonicalized names okay it's then once we've done that now when we render it when we actually display the name we don't want to display a lowercase because then look that look weird in despite what they've typed it'll look different we want to clean it up we want to give it the title aged version yeah okay so let's actually try and run this now assuming that I don't have any errors in here let me exit the interpreter clear my screen and then run my hello dot pi so let's test it out let's say David J Malan oh wow internationally and actually printed your name and it's happy to see you it is which is good let's go ahead and tie it let's try a Colton will use my actual full name Colton Taylor Ogden oh I'm happy to see you and happy to see me what about Colton McLovin yeah what about coffee done Colton McLovin Ogden looks like it knows it's you Missy still knows this mean I wouldn't Colton was try Colton McLovin Smith he's fine he's cool that's a different Colton what about just Colton okay let's try that hello this was suggested in the chat if we just have one name oh it looks like it's happy to see interesting cuz it really is the Ogden that we don't like correct interest any Colton and specifically if your string is one element long and you do negative 1 and 0 these are identical you get the same element because your your list is only one size so from the bottom and from the front it's making the same steps to get to the same value and I see Osley underscore t asks can you also do name 0 lower you can but then you're gonna end up calling lower in two places because you're gonna do it on names bracket 0 and names bracket negative 1 it's not wrong it's just you're literally calling the function twice as many places as you need to so I like what Colton did by elevating it to this other temporary variable the pieces that end up in the names variable as well this is where you get points for star for design specifically would you bucket eyes this as design this would be designed right yeah this is design I would say style would be more about the indentation whether your variables are named correctly but design is like the actual how you arrange your function calls and sort of mold your data to accomplish the task at hand so I think if folks are comfy I think there's a nice opportunity here even though the program is pretty small to kind of take things to the next level and introduce a more advanced topic known as regular expressions okay regular expressions allow you to check for patterns of user input which is nice because what Colton's something something Ogden really is it's a pattern and we're being very deliberate right now in splitting the string on space checking the first for C
Original Description
Join CS50's David J. Malan and Colton Ogden for a live Python tutorial, covering the basics of syntax for complete beginners. If interested in learning how to program or just in starting Python from the very beginning, this won't be a stream to miss!
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from CS50 · CS50 · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
Hello, World: Hadi Partovi
CS50
Content Distribution and Archival in a Digital Age
CS50
CS50 2014 - Week 1
CS50
CS50 2014 - Week 3
CS50
CS50 2014 - Week 0, continued
CS50
CS50 2014 - Week 4
CS50
Week 3, continued
CS50
Quiz 0 Review
CS50
CS50 2014 - Week 3, continued
CS50
CS50 2014 - Week 7
CS50
CS50 2014 - Week 7, continued
CS50
Breaking Through The (Google) Glass Ceiling by Christopher Bartholomew
CS50
Introduction to Amazon Web Services by Leo Zhadanovsky
CS50
CS50 2014 - Week 9
CS50
How to Build Innovative Technologies by Abby Fichtner
CS50
Light Your World (with Hue Bulbs) by Dan Bradley
CS50
Building Dynamic Web Apps with Laravel by Eric Ouyang
CS50
CS50 2014 - CS50 Lecture by Steve Ballmer
CS50
CS50 2014 - Week 10
CS50
This is CS50 with Steve Ballmer?
CS50
Meteor: a better way to build apps by Roger Zurawicki
CS50
Data Analysis in R by Dustin Tran
CS50
Data Visualization and D3 by David Chouinard
CS50
CS50 2014 - Week 6
CS50
Build Tomorrow's Library by Jeffrey Licht
CS50
CS50 2014 - Week 9, continued
CS50
Essential Scale-Out Computing by James Cuff
CS50
iOS App Development with Swift by Dan Armendariz
CS50
Sam Clark Leads Yale Students on Tour to CS50 at Harvard
CS50
3D Modeling and Manufacture by Ansel Duff
CS50
CS50 2014 - Week 5, continued
CS50
hello, world
CS50
CS50 2014 - Deep Thoughts - Hash Table
CS50
CS50 2014 - Deep Thoughts - Binary Tree
CS50
CS50 2014 - Deep Thoughts - Scratch
CS50
CS50 2014 - Deep Thoughts - MySQL
CS50
LaunchCode Visits CS50
CS50
CS50 Live, Episode 100
CS50
CS50 Field Trip to Google
CS50
This is CS50 AP
CS50
Week 4: Monday - CS50 2011 - Harvard University
CS50
Week 2: Wednesday - CS50 2011 - Harvard University
CS50
Week 1: Wednesday - CS50 2011 - Harvard University
CS50
Week 11: Monday - CS50 2011 - Harvard University
CS50
Week 3: Wednesday - CS50 2011 - Harvard University
CS50
Week 12: Monday - CS50 2011 - Harvard University
CS50
Week 1: Friday - CS50 2011 - Harvard University
CS50
Week 3: Monday - CS50 2011 - Harvard University
CS50
Week 10: Wednesday - CS50 2011 - Harvard University
CS50
Week 2: Monday - CS50 2011 - Harvard University
CS50
Week 9: Monday - CS50 2011 - Harvard University
CS50
Week 7: Monday - CS50 2011 - Harvard University
CS50
Week 5: Monday - CS50 2011 - Harvard University
CS50
Week 5: Wednesday - CS50 2011 - Harvard University
CS50
Week 7: Wednesday - CS50 2011 - Harvard University
CS50
Week 8: Monday - CS50 2011 - Harvard University
CS50
Week 9: Wednesday - CS50 2011 - Harvard University
CS50
Week 8: Wednesday - CS50 2011 - Harvard University
CS50
Week 10: Monday - CS50 2011 - Harvard University
CS50
Week 2: Wednesday - CS50 2010 - Harvard University
CS50
More on: Python for Data
View skill →
🎓
Tutor Explanation
DeepCamp AI