CS50x 2026 - Lecture 6 - Python

CS50 www.youtube.com

Resumen Breve

Este video de CS50 introduce Python como un lenguaje de programación de alto nivel, contrastándolo con C y Scratch. Se destacan la simplicidad y la rapidez con la que se pueden resolver problemas en Python, ejemplificado con la reimplementación de un corrector ortográfico. También se exploran las funciones, tipos de datos, condicionales y bucles en Python, comparándolos con sus contrapartes en C. Además, se introduce el concepto de programación orientada a objetos y el uso de bibliotecas externas mediante pip.

  • Introducción a Python como lenguaje de alto nivel.
  • Comparación con C y Scratch.
  • Ejemplos de implementación rápida de soluciones.
  • Exploración de funciones, tipos de datos, condicionales y bucles.
  • Introducción a la programación orientada a objetos y uso de bibliotecas externas.

Introducción

El curso de CS50 se traslada de C a Python, un lenguaje de programación de nivel superior. Aprender C proporciona una comprensión profunda de cómo funcionan las computadoras y los lenguajes de programación, lo que facilita la apreciación de Python, Java y C++. Python permite escribir programas complejos con menos código, enfocándose en la resolución de problemas y la creación de productos. El objetivo es que los estudiantes se sientan cómodos aprendiendo nuevos lenguajes por sí mismos, utilizando la documentación y recursos disponibles.

Python

En C, se usaba make hello para compilar y ejecutar programas, mientras que en Python se ejecuta directamente el programa con python hello.py. Un programa simple en Python, como print("Hola mundo"), elimina la necesidad de #include, int main void, llaves y punto y coma. La función print es más amigable que printf y automáticamente añade una nueva línea. Python es un lenguaje de nivel superior que permite resolver problemas rápidamente.

Corrector Ortográfico

Se implementa un corrector ortográfico en Python, similar al problema del conjunto de problemas 5 de CS50. Se declara una variable global llamada words como un conjunto (set) para almacenar palabras sin duplicados. La función check verifica si una palabra está en el conjunto, y la función load abre un diccionario, lee su contenido y actualiza el conjunto de palabras. Las funciones size y unload retornan el tamaño del diccionario y liberan la memoria, respectivamente. La implementación en Python es más corta y sencilla que en C, pero puede ser más lenta debido a la interpretación del código.

Filtro

Se implementan filtros de imagen en Python utilizando la biblioteca PIL (Python Image Library). Se muestra cómo aplicar un filtro de desenfoque a una imagen con solo cuatro líneas de código. También se implementa la detección de bordes en una imagen utilizando la misma biblioteca. Estos ejemplos demuestran cómo Python simplifica tareas complejas en comparación con C.

Funciones

Se comparan las funciones en Scratch, C y Python. En Python, la función print reemplaza a printf y no requiere punto y coma ni nueva línea explícita. Python utiliza módulos y paquetes en lugar de archivos de encabezado. Se muestra cómo obtener entrada del usuario con get_string de la biblioteca CS50 y con la función input de Python. Se explica el uso de parámetros nombrados para modificar el comportamiento de las funciones, como el parámetro end en la función print.

Tipos de Datos

Se comparan los tipos de datos en C y Python. Python tiene bool, float, int y str, pero no tiene char ni punteros. Se muestra cómo convertir un programa de calculadora de C a Python, utilizando la función input para obtener números del usuario y la función int para convertirlos a enteros. Se explica que la función input retorna una cadena, por lo que es necesario convertirla a entero para realizar operaciones aritméticas.

Calculadora

Se crea un programa de calculadora en Python que solicita dos números al usuario y muestra su suma. Se explica que la función input retorna una cadena, por lo que es necesario convertirla a entero para realizar operaciones aritméticas. Se muestra cómo realizar la conversión directamente en la función input para simplificar el código.

Condicionales

Se comparan las estructuras condicionales (if, else if, else) en Scratch, C y Python. En Python, no se utilizan paréntesis ni llaves, pero se requiere indentación. La abreviatura para else if es elif. Se muestra un ejemplo de un programa que compara dos números y muestra si son iguales, menores o mayores.

Comparar

Se compara un programa que compara dos cadenas en C y Python. En C, se necesita la función strcmp para comparar cadenas, mientras que en Python se puede usar el operador ==. Se muestra un ejemplo de un programa que solicita dos cadenas al usuario y muestra si son iguales o diferentes. Python simplifica la comparación de cadenas al comparar los valores en lugar de las direcciones de memoria.

Programación Orientada a Objetos

Se explica el concepto de programación orientada a objetos (OOP) en Python. Se muestra cómo utilizar métodos de cadena, como lower, para convertir una cadena a minúsculas. Se explica que los métodos son funciones que están dentro de los objetos y que se acceden mediante la notación de punto. Se muestra un ejemplo de un programa que solicita al usuario si está de acuerdo y utiliza el método lower para convertir la entrada a minúsculas antes de compararla con "y" o "yes".

copy.py

Se compara la copia de cadenas en C y Python. En C, se necesita asignar memoria dinámicamente y copiar los caracteres uno por uno, mientras que en Python se puede usar el operador de asignación. Se muestra un ejemplo de un programa que solicita una cadena al usuario y crea una copia capitalizada de la misma utilizando el método capitalize. Python simplifica la copia de cadenas al manejar la gestión de memoria automáticamente.

Bucles

Se comparan los bucles en Scratch, C y Python. En Python, se pueden usar bucles while y for. Se muestra un ejemplo de un programa que imprime "meow" tres veces utilizando un bucle while. También se muestra cómo utilizar un bucle for con la función range para iterar sobre una secuencia de números.

Meow

Se explora la implementación de bucles en Python, comparándolos con C. Se muestra cómo usar un bucle while para imprimir "meow" tres veces. Se introduce el bucle for en Python, que itera sobre una lista de valores. Se explica el uso de la función range para generar una secuencia de números. Se introduce la convención de usar un guion bajo (_) como nombre de variable en un bucle for cuando la variable no se utiliza. Se muestra cómo implementar un bucle infinito con while True y cómo definir funciones en Python con la palabra clave def.

Truncamiento

Se discute el problema del truncamiento en C al dividir enteros y cómo Python lo resuelve automáticamente al retornar un valor de punto flotante cuando es necesario. Se muestra cómo Python mantiene la precisión en operaciones de división, a diferencia de C, donde se requiere una conversión explícita a float.

Excepciones

Se introduce el concepto de excepciones en Python como una forma de manejar errores sin depender únicamente de los valores de retorno. Se muestra cómo utilizar bloques try y except para capturar errores, como ValueError, que ocurre al intentar convertir una cadena no numérica a un entero. Se explica cómo las excepciones permiten escribir código más limpio y robusto al separar la lógica principal del manejo de errores.

Mario

Se reimplementa el problema de Mario de CS50 en Python. Se muestra cómo imprimir una pirámide de altura especificada por el usuario utilizando bucles for y la función print. Se explica cómo utilizar un bucle while para solicitar al usuario una altura válida y cómo romper el bucle una vez que se obtiene una entrada válida. Se muestra cómo imprimir caracteres en la misma línea utilizando el parámetro end de la función print.

Listas

Se introduce el concepto de listas en Python como una alternativa a los arrays en C. Se muestra cómo crear una lista, agregar elementos a la lista con el método append y calcular el promedio de los elementos en la lista utilizando las funciones sum y len. Se explica cómo las listas en Python son dinámicas y pueden crecer o disminuir según sea necesario.

Diccionarios

Se introduce el concepto de diccionarios en Python como una forma de almacenar pares clave-valor. Se muestra cómo crear un diccionario, agregar elementos al diccionario y buscar valores por clave. Se explica cómo los diccionarios son similares a las tablas hash y cómo se pueden utilizar para implementar estructuras de datos complejas. Se muestra cómo combinar listas y diccionarios para representar datos tabulares, como una hoja de cálculo.

sys

Se introduce el módulo sys en Python, que proporciona acceso a variables y funciones específicas del sistema. Se muestra cómo utilizar sys.argv para acceder a los argumentos de la línea de comandos. Se explica cómo utilizar sys.exit para salir del programa con un código de estado específico.

csv

Se introduce el módulo csv en Python, que permite leer y escribir archivos CSV (Comma Separated Values). Se muestra cómo utilizar csv.writer para escribir datos en un archivo CSV y cómo utilizar csv.DictWriter para escribir datos en un archivo CSV con encabezados. Se explica cómo utilizar la declaración with para abrir archivos y asegurarse de que se cierren correctamente.

pip

Se introduce el programa pip para instalar paquetes de Python. Se muestra cómo utilizar pip install para instalar bibliotecas de terceros, como cowsay y pyttsx3. Se explica cómo utilizar estas bibliotecas para agregar funcionalidad adicional a los programas de Python.

Resume cualquier video de YouTube en segundos

Obtén resúmenes como este de cualquier video, en tu idioma, con la app gratuita Summ.

Descargar en el App Store
Disponible en Google Play

Transcripción

Transcripción completa de “CS50x 2026 - Lecture 6 - Python”. Haz clic en una marca de tiempo para abrir el video en ese momento. ¿Necesitas otro video? Usa el generador de transcripciones de YouTube.

0:43 All right, this is CS 50, and this is already week 6, wherein we transition away from C to a programming language called Python. And that's not to say that the past several weeks haven't been among the goals of the course. Indeed, in learning C, I very much think that you'll have at the end of this class so much more of a bottom up understanding of how computers work, of how programming languages work, and in particular you'll appreciate and understand better how Python and Java and C++ and Swift and so many other languages. are actually doing their thing nowadays. But recall that we started with Scratch some weeks ago, and in Scratch what was nice was that the first program we wrote, Hello World, was just all too accessible. All you had to do was interlock two puzzle pieces in order to make the cat in that case say Hello world. Well, thereafter,

1:28 of course, we transitioned to C and recall that in week one we asked you to take on faith that you can sort of ignore that first line in a lot of these parentheses and the curly braces and really just focus on the essence of the program, which Clearly is still about hello world and printing it, albeit using a different function and a bit new syntax. Today, very excitingly, all of that is truly going to go away and be distilled into a single line of code when you indeed want to have the computer say something like Hello world. And this is what we mean by Python being a higher level language. So humans over the decades learned from earlier designs, earlier programming languages, what worked well, what did not. Computers got faster. Computers had more memory, and so you were able to start. Spending more of those resources in order to have the computer do more for you. And so you don't need to be as pedantic syntactically anymore.

2:14 You don't need to write as much code anymore and frankly you can just start solving problems of interest to you, building products of interest to you, so much more readily by choosing the right tool for the job. And so in the real world, if you continue coding after CS 50, like sometimes C will be the right tool for the job, sometimes Python will be the right tool for the job, and sometimes it's going to be a different language. Together that you'll never have studied in school. And in fact what's compelling, I think, about this week 6, much like when I took the class back in the day, is that after CS 50 you'll have a taste of 12, maybe a few different programming languages, and that's going to be enough to bootstrap yourself and teach yourself new languages because you're going to start to recognize in the real world similarities with past languages that you've seen, programming paradigms that are still sort of with us, and the syntax,

3:00 yeah, that's invariably going to change, but that's the. that you are going to Google or ask Chat GPT or some other AI about down the line so long as you know enough of it to sort of get real work done, you'll focus mostly ultimately on the ideas and the problems you want to solve and less on the syntax. And so among the goals for this week and this week's problem set and really the rest of the course is to get you more comfortable feeling uncomfortable in front of your keyboard because we're not going to give you and tell you everything you need to know for a language like Python. You're going to turn to the documentation. You're going to turn to the duck, and you're going to learn to to. Yourself ultimately a new language. So let's actually write our first program and compare and contrast with how we might do that in C. So recall that in C. We were in the habit for the first couple of weeks of doing make hello and make this build utility just kind of magically new to look for a file

3:46 called hello.c and magically to create a program called hello, and then you could run it with hello. And then a week or so later we revealed that make is really just automating compilation of your. And with the actual compiler clang in this case and passing it command line arguments like 0 to get a specific output like the file name hello instead of the default, which recall was a out passing in the name of the file you want to compile and turning on any libraries that you might want to compile into your program, link into your program beyond the standard ones. But then you could still run it in exactly the same way. Starting today, when you write Python code and then want to run it, you're simply going to run. The Python program itself. So just as Klang is a C compiler, Python is itself not only a programming language but a program as well.

4:36 And with the Python program, which understands the Python programming language, can you run code that you'll have written in a file called hello.ie? And what this program is doing is a little bit different from what Clang is doing, but we'll see that difference before long. But first, let me go over to BS code and let's write our simplest, our first of Python programs by doing code hello.ie, and then in this file without any includes, any in main voids, I'm simply going to say print quote unquote, hello world, close quote. All right, now I'm not going to. Make. I'm instead just going to do Python of hello.ie, cross my fingers as always, and voila, my first program in Python. So it's sort of obvious that we got rid of the hash and clue. We got rid of the Imain void, no curly braces, only a couple of parentheses here,

5:21 but what else is different to your eyes? That's a little more subtle here versus C. Yeah, yeah, so there's no F, so the print function is a little more human friendly. It's print instead of print F where the F did mean formatted, but we'll see that we still have that functionality. So no need for the line breaks, specifically the backslash n, and yet here's my cursor on the next line. So I dare say humans over the years realized we are more commonly wanting a new line than we don't want it. And so they made the default to actually give it to you automatically. And there's one more detail, yeah. So there's no semicolon, so I finished my thought at the end of the line, but I didn't need to explicitly terminate it with a semicolon. This is just with one program, all of these salient differences, but I'd argue that we got rid of all of the annoying stuff thus far anyway,

6:09 so we can really focus on what this program itself is doing. But what's exciting with Python 2 is just how quickly you can solve certain problems, and this isn't true of just Python. It's really any higher level language than C. In fact, just for fun, let me go ahead and implement. Problem set 5, wherein you're challenged with implementing the fastest spell checker possible. So let me go back here to VS code. Let's close out hello.ie and clear my terminal window, and let me go ahead and do this. Let me first split my terminal by clicking this rectangular icon over here, and that's going to give me two terminal windows now, left and right, because in the first one at left, I'm going to CD into a directory I came with today, which is the staff's solution to. Problemset 5's spell checker in C. And on the right hand side here I'm going to CD

6:56 into another directory I brought with me today called Python, inside of which is a translation of Problemset 5 into Python. In particular, I've implemented in advance a speller.pi file, which is the analog in Python of speller.cnc, and I've also prepared a dictionary. Pi file. Unfortunately, if we open up dictionary.i. You'll see that it's not actually implemented yet. So in dictionary.ie, let's implement in Python problem set 5 and see how long it takes. Well, the first thing I'm gonna do is declare a global variable, we'll call it words, and set that equal to the return value of a Python function called set, which essentially gives me a set object wherein I can store a whole bunch of words without duplicates. Python's gonna manage all of that for me. In effect, it's going to implement what I needed to implement myself in Problems at 5 a hash table.

7:43 Now down here I'm going to go ahead and define a function called check, pass in as input a parameter called Word because of course that's how it was implemented in C. But notice the difference already in Python we use a new keyword called deaf to define a function, and we don't have to specify the. Type of the variable being passed in word in this case, and we also don't have to specify a return type for the function. Now inside of this checks function, it suffices to do this I'm going to return word. lower in words, which is effectively a boolean expression asking is the lower case version of this word in the set? If so, returned true, otherwise returned false. Done with the check function. Now let's go ahead and define another function called load, which recall took an argument of the dictionary that you want to load into memory.

8:28 And let's go ahead now and do this with open dictionary as file, which effectively opens the dictionary, as in C we used FO in Python we use open. And it gives it a variable name of file. Then once that file is open, I'm gonna go ahead and update that entire set of words which starts out empty by taking the file, reading the entire contents top to bottom, left to right, and splitting all of the lines therein on the. New lines that terminate each of the strings, effectively updating the set with every word in that their dictionary. Then I'm gonna assume that it all just worked because there's a lot less effort for me to uh to perform myself in Python, and I'm just gonna go ahead and return true T in Python. Done. Next,

9:14 let's go ahead and define that other function from Palm set 5 size, whose purpose in life was to tell me the size of the dictionary I had loaded. Well, in Python, that's pretty easy. I can just return the length, or LEN for short, of the set in which I've stored all those words. Done. And then lastly I'm gonna go ahead and define an unload function which recall was responsible for freeing any memory I myself had allocated. I don't seem to have done any of that in Python. In fact, that's managed for me now, so I'm gonna go ahead and simply say return true because there's no work to be done. And that's it in like 19 lines of code in Python, most of which are blank lines. I claim I have reimplemented Problem set 5 in Python. Well, let's take a look now at the difference. I'm going to go ahead and reopen my terminal window, and I'm gonna go ahead and maximize it so we can see more output.

10:00 And now I'm gonna go. And run Python, which is going to be not only the name of the language but the name of the program we use today to start running our Python code, and I'm going to run it on speller.ie, which I brought with me today, specifically on the largest of problems that finds files, homes.text. Enter. And as with Problem set 5 itself, we'll see a whole bunch of misspelled words being printed to the screen, some of which might very well be misspelled, some of which are just not in the dictionary, some of which are simply possessives of words that are in the dictionary, but at the very end of this output I should see not only how many words were found, but the total time involved, which appears to be 1.87 seconds. Not bad, seeing as it only took me like what, a minute or two to write the actual code. But there is going to be a trade-off, we'll see, even though it took me much less human time

10:46 and arguably was a lot easier to implement this this spell checker in Python than I dare say it was for most everyone in C, let's see what that tradeoff might be. Over in my left hand terminal window in which I'm in the C directory which I brought with me as the staff solution in C to problem set 5, let's go ahead and make that spell checker. Then let's go ahead and do slash speller and run it on the same file, uh, Holmes.text, and see how long the C implementation takes. Enter. And we see some of the same output might be slower sometimes just because of the cloud and there total time spent in the CPU, not necessarily printing everything to the screen, which might take longer, is only 1.32 seconds versus the 1.87 seconds in Python.

11:33 Now, while only half a second, that's a decent percentage of the total amount of time spent running this spell checker in each of the windows, and so that it alone seems to be one of the trade-offs, even though it seems to be much faster. They're easier to implement a problem in Python, there's going to be trade-offs insofar as the code might very well run slower. And as we'll see today, that's in large part because whereas C is of course compiled. That's why Iran make and in turn clang, and then the zeros and ones, the so-called machine code is what you're running in Python generally, the the computer is interpreting your code, essentially reading it top to bottom, left to right, much like a human in between two. Other humans might slowly translate one spoken language to the other if those two people don't in fact speak the same language themselves.

12:19 So there's a bit of overhead when using Python, but I will say that the Python community has been working on this problem for some time and so in general it's not necessarily going to be as significant a trade off because there's certain tricks we can do. And in fact underneath the hood, what the Python language can do for you and the specific interpreter you're using is technically. Semi-secretly compile your code for you into something called bytecode and then run that bytecode, which is more efficient than actually reinterpreting it again and again, but we'll see more of this over time. For now, let's take a look at maybe two other problems that we might solve, dare say more easily, more quickly than we could have in C for problem at 4. Let me go ahead and shrink down my terminal window here, close out dictionary.ie, close one of my terminal windows and CD back to my main directory,

13:04 and let's go. Go ahead and open up that bridge bitmap photograph that we used in Problem set 4 and how to apply a number of Instagram-like filters there too. Well, now let's go ahead and implement maybe one of those filters, the blur filter, whose purpose in life is just to blur this image. Well, let's see how long this takes. Let me go ahead and open up, say, uh, blur.ie, which is now going to be a Python program for blurring images. It's empty initially, but I can pretty much write this. Quite quickly now let me go ahead and at the top of this file write the Python keyword from PIL for Python image library, import an object called Image and another one called Image filter in particular two features of the Python image library that's gonna make this so much easier to actually solve.

13:50 And then let's go ahead and define a variable we'll call it before, representing the before version of this image and set that equal to image. open. bridge.bmp where that is of course is the name of the file we want to blur. Then let's go ahead and create a variable called after representing the after version of this same filter and set that equal to before. filter parenthesis, image filter.bo blur, and then just to be a little dramatic, I'm going to blur it more so than you needed to in problem set 4, but we'll see it more visibly now on the screen. Let's do an argument of 10. And then at the very end of this process, let's do after.save and save it in a file called say out.bmp. Done. So in just 4 lines of code, I claim I've implemented the blur function now in

14:37 Python of what we did previously in C. Let me open my terminal window. Let me run the Python command this time on blur.ie. Cross my fingers as always. And indeed I've made a mistake. Perhaps even if you've never written Python before, you can see it and in fact we'll see a number of these errors, some intentional, some unintentional, but on line 4 what I intended to do was set equal to before. filter, that variable I created called after. All right, that's all right. Let's go back down to my terminal window, clear it to get rid of all that, and rerun Python of Blur.ie.ross my fingers even harder this time. Nothing bad seems to be happening. Indeed, now let's go ahead and open up out. BMP and before we reveal that, let's go back to the original, which is bridge. BMP and now dramatically, let's see the blurred version thereof.

15:24 Voila, hopefully to your eyes too. It looks quite a bit blurry. Well, how about one more flourish? Those of you who are feeling more comfortable last week and implemented perhaps, uh, edge edge detection in see. Well, let's see if we can whip that up quite quickly too. Let's go ahead and write a file called edges.ie using that same bridge. BMP file, and in this file, let's go ahead and do the following. As before from the Python image library, let's import, uh, the image feature and the image filter feature. Then as before, let's create a variable called before. Set it equal to image. open passing in bridge.bmp. So so far the same as before. Now let's create a variable called after. Set it equal to before. filter passing in this time image filter.fi edges,

16:11 which is different from box blur, and by definition it's going to find the image the edges of this here image, and then after, as before, let's do after.save of out.bmp and just clobber the version of the blurred file that we just created. All right, that's it. Let's go ahead and open up my terminal window now. Let's go ahead and again run Python, but this time on Edges.ie, cross my fingers real hard. So far so good, and that was quite fast. Recall that the bridge. BMP image looked like this, but now when we open up this new and improved version of Out. BMP thanks to Python and just 4 lines of code, we now have all of our edges detected. So what can we then learn from C itself? Well, C had of course functions, and functions were those actions or verbs that simply got worked on.

16:56 And let's go ahead and compare side by side, much like we did with scratch and C. The idea is that today onward are still going to be the same. And how they could translate to Python. So on the left here we'll now have our friend scratch. This of course was one of the first puzzle pieces we saw. It's a purple puzzle piece saying say, and it was a function insofar as it said the value of its argument, which in this case is hello world. What we've already seen in Python what this looks like. It looks similar to the version in C, but it's no longer print F. There's no longer a semicolon, and there's no longer an Explicit new line. So in Python it's quite simply this. Meanwhile in Python there are a whole bunch of libraries as well. Now in C we had simply header files, and those header files gave you access to the prototypes of that is the signatures of the functions that you want to use from those libraries.

17:43 Python uses somewhat different vernacular whereby Python has what are called modules and packages, and a package is just a collection of modules. But a lot, a module is just a library using Python Speak, so to speak. So anytime you hear someone discussing a module or a package in Python, they're just talking about using a library, and that library might come with the language itself just built in as standard, or it might be a third party library that you might download and install yourself much like I did a few weeks back when we installed the cow sayy program so that I could actually have a cow or other animals on the screen. Display text. So in C recall we had something like this include CS50.h, which was the header file preinstalled for you somewhere, but we will have for at least this week an analog of the CS50 library in C also in Python just to make this transition from C to Python a bit easier.

18:31 These two though are meant to be training wheels that you can take off and should take off, you know, even within a week or so. It's just meant to smooth that transition. Clear what's the same and what's different. So in the CS 50 library for Python, we also have a function called get string whose purpose in life is to get a string. To access it though, you don't use hash include CS50.h. That's a C thing. In Python you would say from CS50 import get string. It's a little more verbose, but it's also a little more precise as to what you want from the library, especially if you don't want the whole thing loaded into memory. So here for instance is now a scratch program that was a little more interesting than just printing out HelloWorld. This was the first program we wrote that actually got some user input. So in fact, let me go back to VS Code and let's see if we can't resurrect this C program real quickly in the form of a new hello.c.

19:20 So I'm going to run code of hello.c. And then in my, in my code tab, I'm going to do include CS50. H, include standardio.h, and then below that, I'm going to go ahead and whip up our familiar version of this, I made void, and then inside of the curly braces we'll bring back string. Even though we now know it's Chart star, we'll call our variable answer, set it equal to get string, ask the user, quote unquote, what's your name with a space just to move the cursor over. Still need my semicolon and C. And then after that, recall back in week one we did hello slashn. And then plugged in the variable answer so as to see Hello David, hello Kelly, or something else. Just to be safe, let me do make hello. All is well so far.

20:06 hello, type my name, and this version in C seems to be working OK. So in C, these lines of code here translate pretty literally to what we just saw, although we got the answer variable in. for free. That blue puzzle piece just existed without our having to create it, but it's a decent number of hoops to jump through in order to just get user input and print it out. Well, in Python, this is going to get a little more succinct in that the Python version of this code is now going to look like this. PrintF is now print. The semicolons are gone, and what else seems a little bit different. Yeah. I don't need any placeholders. Yeah, so we don't need the percents anymore. In fact, I'm curiously using a plus,

20:51 which if some of you studied Java or some other language, you might have actually seen this before. Even if you've never seen Python before, you've only seen C in CS 50, you can probably guess what the plus is doing, even if you don't know the technical vocab. What is the plus probably doing here? Yeah, so it's concatenating or joining together the thing on the left with the thing on the right, and we actually had that vernacular in the world of Scratch. We had the joint puzzle piece that joins hello, comma space and the value inside of answer. A plus in Python can do exactly the same thing. So it's a little more user friendly. Having to anticipate, let's put the placeholder here and then come back later and plug in the variable. Humans over time just realize that it's a lot easier to sort of do this in this way than bother with placeholders, though you can still use placeholders for other purposes. Another subtle difference between the C and Python version of these two lines.

21:41 More subtle Than that What's missing? Yeah, I'm back. Uh, so the backslash N is again gone for Python, so that sort of happens for free, indeed, and one more difference. Yeah, we don't need to declare the type of answer. Recall that if you rewind in the C version, you needed to tell the compiler that this is a string, and last week we could have changed string to charge star, but we still had to tell the compiler what data type we're putting into that variable. In Python we can now get rid of that data type, and Python will just figure it out from context. If get string returns a string, well then obviously the variable should store a string. If a function returns an in, well then obviously the variable should store an in, and the length.

22:27 It's just doing more of that decision making for you just to save you time and save you thought. There's a subtlety here though where we can make this program a little bit different. In fact, let's whip it up first in Python. Let me go back to VS code here, clear my terminal, and let's go ahead and create a program that again called Hello.ie. That'll open up my previous version thereof. And just so we can see these things side by side, I'm going to drag that tab over to the right of VS code and let go. And now you can see the C version still on the left and the Python. Version at the right. What I'm going to do here now in my Python version is change it to be quite like the version in C now at left. So as promised, I'm going to do from CS 50 import get string. Then below that I'm going to say simply answer equals get string, quote unquote, what's your name?

23:13 question mark space no semicolon, but then on the next line, what I'm oops, but uh parenthesis, then on the next line I'm going to do print, quote unquote. space close quote plus answer. Down here I'm going to go ahead and run Python if hello.ie again, no compilation step. I'm just going to interpret it line by line. What's my name David? And it seems now to work exactly the same. Now it turns out in Python there's even more ways to solve problems like this, even trivial problems like this. So here we're using the plus sign, not as addition per se, but as the concatenation operator, the joint operation. If you want though, you can take it. Advantage of the fact that print in Python can take more than one argument. It can take 2 or 3 or 4 or even 0

23:58 by simply changing the plus to a comma, getting rid of that seemingly superfluous space, and just give print two things to print because it turns out per the documentation of print, which we'll eventually see, it knows that if it takes +12 arguments by default, separate them for you by a single space, and that's something we can override as well. Which one is better? Like, uh, like I don't know, like they're sort of equivalent. It's such a trivial difference, but it speaks to the flexibility that you'll start to have whereby the language is a little less rigid than C was certainly when it comes to printing strings. So in fact, if I go back to VS code here and I go ahead and change that plus to a comma and get rid of the space inside of the quotes, I can rerun Pythonof hello.ie, type in my name, and we see exactly the same results there.

24:46 But we can take this one step further, even though it's going to look a little cryptic. This is sort of the more pythonic way to do things, and that too is actually a term of art. To do something pythonically is to do it the way that most Python programmers would do it. It's not the only way. It's not necessarily the right way, but it's sort of the recommended way in the community. So here we have that latest version where I'm passing two arguments to print. The first is quote unquote hello, comma, and then the second of which is the value of answer. I could similarly write this same program. With this crazy syntax, it takes a little getting used to, but it turns out it's actually kind of nice overall. What's obviously different? Well, one, there's these weird curly braces are back. They're not part of the logic of the program. They're literally inside of the double quotes,

25:31 but you can probably guess how this, what this does for me because there's one other crucial difference. What else has changed between before and after? Yeah, there's this weird F which is not part of print F. It's actually inside of the parenthesis and next to the double quotes. And even this one this came out was a little weird looking to people, but this is how you get this thing to be a formatted string, AKA an F string, as opposed to it being just a literal string of text. Now you can probably guess what it means to put the variable's name inside of the curly braces. It means the value of that variable is going to be substituted right there, similar in spirit to the percentage. S in C, but a little more explicit with the percents, you had to remember that that percents corresponds to this variable's value or something like that,

26:18 which was just annoying if anything else, if anything, but this time you have a placeholder in curly braces that just says what you want there, that particular value, and what this means more technically is that the answer variable will be interpolated by the interpreter, which means its value will be plugged in right there. So let's try this. Let me go back over to VS code. And quite simply, on my last line of code here, let's change the input to print to be quote unquote, hello, comma, and then Curly brace, answer. Then close curly brace, close quote, and I've done this, this is intentional, but let's see. Let me go ahead and rerun Python of hello.ie DAVID. What are we about to see? Hello comma.

27:05 Answer, so this is a bug, but just to demonstrate like what is going on and what's therefore missing, what, what did I forget? Yeah. Yeah, I didn't declare that this is a so-called F string or format string. The fix for this weirdly is just to put an F right there. And now if I rerun Pythono hello.ie, type in my name again, cross my fingers, now I see that the variable has indeed been interpolated and its value plugged in where I wanted it. All right, turns out we can take off one of these training wheels already. I propose that Get string just exists in the library just to smooth the transition, but honestly it's not really doing anything all that interesting. So let's take this first training wheel off. It turns out that Python comes with a function appropriately named input

27:51 such that if you want to get input from the human via their keyboard, you can just use the input function. So we can already for this program get rid of the CS 50. Library because input essentially behaves just like the get string function. So if I go back to my Python version here, I can change get get string to input, and I can even go and delete this training wheel up there, rerun Pythono hello.ie in my terminal, DAVID enter, and we're still in business as well. So input is generally going to be the way you go about getting input now from the user. All right, let me pause here and see if there's any questions as we try to bridge these two worlds from C to Python. Yeah. uh, so in Python, we don't need a name.

28:38 Good question. In Python, why don't we need the main function anymore because clearly that's been omnipresent in like every program we've written thus far, and here we have it in all of our Python programs thus far absent. It turns out that humans realize it's just so common that you want the file you're editing to be the main part of your program. Like, why bother adding the additional syntax of saying in main void or something analogous? It's just easier if you want to write two lines of code to get some work done. Why do you have to waste my time adding all of these this boilerplate code which we've been doing. Up until now, now that said, we're going to bring back Maine in a little bit because it will solve a problem, but generally speaking, what I'm doing here is indeed a program, but people in the real world would also call these scripts where a script is like a lightweight program that pretty much just reads top to bottom, left to right. It might be fairly lightweight.

29:24 It's really synonymous with writing a program, but this is again one of the appeals of a language like Python. You can just get right in and get out and get the job done. Even Java has moved to this in recent years where you don't have to put everything in a class, uh, public static void main for those familiar, you can just write, uh, system.out.print line and get some work done. Yeah. Good question. Is input only for a string? Yes, right now, it will get input from the user via their keyboard and you'll get back a string just like get string, and we'll come back to why that's maybe not a good thing. All right, so what's more what we want to do at this point? Well, let's tease apart some differences now with C. So up until now, every argument we've ever passed into a function in C,

30:11 and scratch for that matter is a so-called positional parameter, and a parameter is the same thing as an argument, but generally when you're looking at the function from the functions perspective, it's a parameter that it accepts, but when you're Calling the function and passing in an input, you call it typically an argument, but they refer to essentially the same thing, and all of the parameters we've been passing into functions thus far have been positional in the sense that the order matters. The first thing, then the second thing, then the third thing, and so forth. For instance, with print F, the first thing has to be the quoted string, maybe with the placeholder, and then if there's another argument after the comma, that can be the 2nd argument, the 3rd argument, and. So forth, but it turns out Python additionally supports what are called named parameters whereby you don't have to rely only on the order

30:57 in which you're enumerating the arguments to a function, and that's helpful because some functions, especially in the real world, when you start using other people's libraries that have lots of functionality, they might not take just one or two arguments. They might take 4 arguments, 10 arguments, maybe even more, and it can just be. Wieldy to have to remember the precise order of all those arguments, you're just asking for trouble if you're going to screw up or a colleague is going to get the order out of out of whack. So with name parameters you can actually be explicit with Python and tell it what argument you are trying to pass in by giving it an actual name. So let me go over to BS code here and propose that we use this for really the simplest of programs in order to Override that default

31:42 new line that we seem to be getting for free just by calling print. In other words, let me go ahead here and clear my terminal window. Let me close hello.c and focus only on hello.ie for just a moment and let's make it much simpler, like the very first version, and just print out using Python's print function, not print F, quote unquote hello. close quote. And now here I'm going to do Pythono hello.ie. Enter and we still see that the cursor moves to the next line, the dollar sign moves to the next line, because I'm automatically getting a new line. Well, what if you don't want that? How can you override that behavior? Well, you can actually use a named parameter in Python, and I can go up here and add a second argument. That if it were just something like this that would literally print out the word this because it's just another string,

32:31 but if I give it a name like end equals quote unquote, I can override the default behavior of the Python print function by changing the value of its end parameter to be the so-called empty string, quote unquote, which means literally there's nothing there. Watch what happens now if I run Python of hello.ie and hit enter, the dollar sign is weirdly and sort of in the ugly way on the same line just like it was when I made the mistake in C in week one of omitting the backslash N. That is to say, what the default value of this end parameter really is is quote unquote backslashn, and I can make it explicit by changing my code as such. I'm going to go ahead and rerun Pythono hello.ie, and now the cursors back on the next line.

33:17 And not that this is that useful other than overriding that default, but you could do fun things like, if you really want print to be excited to print some. Things for you. And if I now run Python of hello.ie a third time, now you see that it's ending with exclamation looks a little stupid with the dollar sign, so you could even toss in a new line there, run it yet again, and now we sort of get both of those there. But I would say the common case is to use that end named parameter simply to override it. So how do you learn more about these kinds of things? Well, if you go to The official documentation for Python, which is a thing more so than with C, like if you want to learn more about Python and the functions it offers and the arguments it takes, you go to the official documentation docs.python.org.

34:04 This is essentially analogous to the so-called manual pages or man pages that CS50 has a version of, but there is no one de facto source for those man pages. Several different versions of them exist in the wild, whereas Python itself. A community maintains its own official documentation. So for instance, if you go to a specific URL like this ending in functions.html, you'll see an exhaustive list of all of the functions that come with Python besides just the print function, and we'll see a bunch of more today. If specifically you scroll down to the print documentation, you'll see something that's a little arcane that looks like this, but this is represented. of a Python prototype, if you will, also called a signature that just tells you the name of a function and then how many and what type of arguments

34:50 it takes. So how to read this? Well, the print function takes some number of objects. So in Python specifically, this syntax of star objects just means zero or more objects, whatever that is, like a number or a string or something else. The stuff you want to. Print out after that, if you start using named parameters, you can specify what the default separator is the separator between arguments to print. So recall that when I did quote unquote hello, quote unquote or quote unquote hello, comma answer it was separated automatically for us by a single space even without my hitting the space bar inside of my quotes. That's because. As the default value here is in fact a single space. The default value for and as promised is indeed backslashn.

35:35 And then there's some other stuff related to file IO that print can also deal with, but more on that perhaps another time. There's one curiosity here in Python, it turns out that you can use double quotes or single quotes around strings, where in C it was much more regimented. Double quotes are for strings and single quotes are for. Chars characters only single characters. It doesn't matter in Python which one you use so long as you're consistent and stylistically you should really pick one and go with it. And the only time you should really alternate between the two is maybe if you want to put like an apostrophe for some human's name inside of double quote inside of single quotes or something like that, but generally you have a little more flexibility. in Python and you'll see in different languages Python community tends to use single quotes at least in the documentation. The JavaScript world tends to use single quotes.

36:22 Um, we in CS 50 often use double quotes just for consistency with what we do and see, but any, uh, community or company would typically have its own style guide that dictates which one you should use if only for consistency. Questions then on this here print function. As just representative of all of the docks that you'll see. All right, well, let's take a quick look at variables. We've used these a few times already, but let's focus in a little more detail on what's actually different in Scratch, if you wanted to create a variable called counter and set it equal to 0, you would use this orange puzzle piece here. In C, you would do something like this the type of the variable, the name of the variable, and then set it equal to the initial value semicolon. In Python, it's going to be a little similar,

37:07 but you can probably guess where we're going with this. How is this line of code probably about to change? Yeah, Good, we're not going to bother with in or the data type more generally, we're just gonna say counter because obviously like a smart interpreter can just figure it out from context that you're putting a 0 in there. It's obviously an integer, and what else is about to go away? The semicolon. So this is the C version and voila, this now is the Python version and this is as silly as this example is, it's kind of representative of how languages like Python just tend to be a little more programmer friendly because you just type less and get the same work done. All right, so if we wanted to do something now and scratch like. Increment the counter by 1. You would use this puzzle piece here. In C we could do something like this in Python it's going to be almost exactly the same, except of course no semicolon.

37:53 In C we could alternatively do this, and you can also do this in Python. In C though, You could also do what other technique? Plus plus, I'm sorry, but Python has taken that away from us. So if you got into the habit of using plus plus or minus minus, that's great. Use them and see all you want in Python, they just don't exist, so you'll see this more commonly instead as the heuristic. All right, what about the various types that exist in Python? Because even though you don't have to specify the types when declaring your variables, they do in fact actually exist underneath the hood, and it's worth knowing a little something about them because Not knowing will lead to some form of bug. So in C we had types like this bull, char, double, float in long, and string, the last of which was thanks to the CS 50 library.

38:39 But last week we would have started calling a string chartar instead, which it still is a data type, the address of some char. In Python, we're going to whittle this list down to a subset of those essentially whereby we still have bulls, we still have floats, we still have ints, and we do have strings, but they're literally. Called ss STR so it's not a CS 50 thing. The Python community calls strings STRs, but absent from this list is any mention of star, not to mention chartar, there are no pointers in Python, and indeed as powerful as I'd hope you found weeks 4 and 5 to be, I dare say you also found them incredibly frustrating and challenging and want to yield bugs in your code because with that. Power of memory management comes a whole slew of potential mistakes that you can make,

39:26 and that's true not just for CS 50 students but for programmers, adult programmers, full time programmers around the world. And so among the other features of languages like Python is they try to take away certain features of languages like C that were just too dangerous in the first place. It might be wonderfully powerful. It might help you solve problems more quickly, more precisely, but if they tend to do more damage than they're worth, some. it's worth just abstracting those details away. Similarly, Java has references, as some of you might know, but does not have pointers per se. You can't go poking around arbitrary locations in memory in the same way that you can with C. So let's take some of these data types out for a spin and see what's the same and what's different. Let me go back to VS code here and let me propose that we bring back one of our old calculators from a while back. So let me clear my terminal,

40:12 close hello.ie. And let me go ahead and open up a version of this program that I brought in advance, which was our calculator version 0 from back then. So just to remind you, one of the first versions of our calculator had the CS 50 library as well as the standard IO library, and then we simply got an IT using GetIT in week 1. We got another in in week one using GetIT, and then we simply performed some additions. It was a very Trivial calculator that we did very early on just to demonstrate some of the operators and syntax of C. Well, let's go ahead and try converting this to Python by creating our own program, calculator.i. So in my terminal window I'm going to write code of calculator.i. It's going to open another tab which I'm just going to drag over

40:58 to the right just so we can see both side by side. I won't bother with, say, well, Let's do it for parity here. Let me copy the C code into the Python file, even though this will not work in the same way. But let's keep what we need and get rid of what we don't. So instead of the slash slash for comments in Python, it turns out the convention is to use a single hash symbol like this. So it's a minor difference. It's half as many keystrokes, so that's nice, but we're not going to include anything like this. But we are going to do from CS 50. Let's import a function that I promised would exist called get in, but we'll soon get rid of that training wheel as well. We don't need main or this curly brace. We don't need this curly brace, and we don't need all of this indentation as a result. So I'm going to move all of that over to the left. I'm going to fix all of the comments to be Python comments by changing the slash slash

41:48 to hash symbols. And now I'm going to change each of these three lines of code, as you might expect to the Python version. So you probably can guess already. We can get rid of the in there and the in there. We can get rid of the semicolon here and the semicolon here. We can get rid of the F in print F here and we can get rid of the semicolon here. And there's a few different ways we could do this, but I dare say the simplest is going to be to get rid of the format code altogether in that first argument and just tell Python to print X plus Y. So there's a few different ways we can do this, but that's probably the most literal translation of the program at left. To the program at right. Let's reopen the terminal window and run Python of calculator.ie and hit enter. Let's do something like X is 1, Y is 2, and hopefully, we do in fact get 3.

42:35 All right, so that's all fine and good, but let's take off one of our training wheels now. So let me get rid of our C version here and focus just for the moment on Python. Let's take away this C code and what was the function we can use to get user input. Yeah, it was called a little louder. It's just called input. So let's get rid of CS 50's get in already and use input instead. All right, so this program is much simpler already. So let's go ahead and reopen the terminal window, run Python of calculator.pi, do one again for X, 2 again for Y, and of course, 1 + 2 equals 12. So what's going on here? Cause clearly this is a step backwards,

43:21 yeah. Yeah, so in the context of strings, plus represents concatenation, the joining of two arguments on the left and the right. Here that seems to be what's happening because it's not 12 per se, it's more literally +12 concatenated together, but why is that? Well, apparently the input function indeed. Returns a string that is those are the key strokes that came back from the user might look like numbers in Arabic numerals to us 1 and 2, but it's being treated as a string. More technically like underneath the hood, there is some char star stuff going on there, even though we're not using that same terminology. So intuitively, what's going to be the solution without just reverting to using the training wheel that is the get in function from CS 50? Put another way,

44:06 how did CS 50 probably implement get in, might you think? Yeah. Yeah, so we'recall that in C. We could cast some data types to other data types, typically ends to chars or charges to ends. It's not quite as simple as casting in this case, because underneath the hood, thanks to our knowledge of C, there's a bunch of stuff going on. There's probably a 1 and there's a null character. There's a 2, and there's a null character, so Not quite as literal as a char to an end or an end to a char, so we're going to more properly convert the H string or the stirr to an end. We're not casting, but converting, and converting just implies that there's a little more work that has to be done. But thankfully Python can do this for us. In fact, let me go up to line 4 here and say,

44:53 A pass the, well, actually let's do it in this a couple ways. Let's first convert the X value to an integer. Let's convert the Y value to an integer as well. So funny enough, it's very similar syntactically to casting, but in C, when you cast something, you actually wrote the data type in parentheses. Now the data type itself is a function that takes an argument which is the stir or string that you want to convert. So let me go back to my terminal, do Python of calculator.ie, enter, type in 1, type in 2, and now I get back my 3 answer. Now as you might imagine, just like in C, we can kind of play around with where we're performing some of these operations, and this looks, you know, arguably a little less obvious now as to what is being added. So I really like the simplicity of X + Y.

45:39 It just does what it says. So I could convert these in other ways. I could say after line 4, you know what, rechange. X to be the in version of X, but generally speaking, that's kind of wasting a line of code by just doing something you could do on a single line. So let me delete that and instead just say that well if I know the return value of the input function is a stir, let's just pass that output as the input to the end function and it'd be a little more pythonic. So to speak, to just pass the input functions output as the input to in, which is really hard to say, but we've done this in C, just nesting function calls like this. All right, so if I run this one more time, Pythonocalculator.pi type in 1, type in 2, we're back now in business.

46:26 Now what I won't trip over just yet is a subtlety that Whereby I'm deliberately typing in actual numbers like 1 and 2, but if you are following along at home or on your laptop, if you were to type in cat and dog, like bad things will happen, but we'll come back to that before long. Our questions though on any of this conversion of our strings to our. Integers in this case. All right, well, what more does Python offer to us? Well, in addition to these data types, there's actually going to be a bunch of others, a few of which we'll actually use today. In fact, we'll see ranges of numbers that's like that's a thing built into Python. We'll see lists of numbers which is going to be like a new and improved version of an array that solves like all of last week's problems when we talked about the downsides of using arrays.

47:13 There's going to be tups for things like X Y. Coordinates or GPS coordinates or anything where you have collections of values. There's going to bed or dictionaries whereby you can have key value pairs provided to you without having to write a whole hash table yourself and you can have sets which you can use to just contain unique sets of values that you just want to check for membership and there's bunches of other data types as well. And this is where languages like Python start to get really powerful because all of the Data structures we talked about in C we really only got from the language itself in array. Everything else we had to build, or at least talk about building in class, these now and more come with the language. Meanwhile, in the CS 50 library for Python, just so you know, there are a whole bunch of functions. These were the C versions in Python it stands to.

48:00 And that we don't need as many because there's fewer data types in Python, but get flow, get in and get string do all exist in the CS 50 library for Python. You're welcome and encouraged to use it because indeed among the goals for problems set 6 are going to be to redo some of your C problem set problems in Python where you can look at your own C code and hopefully. Uh, you like that solution and figure out how to convert it line by line essentially to the corresponding Python version, but clearly we've seen ways of taking these training wheels off quite quickly as well. And in fact, if you wanted to import all three of those functions for a larger program, you could do this just following the approach that I took so already, but you can also just separate them by com. like this or it turns out you can also import the whole CS 50 library as you'll

48:45 see in some code and then just access the functions within with slightly different syntax as well. All right, how about another construct from scratch and from C now in fact in Python. So in Scratch, if we wanted to do a comparison like is X less than Y where each of those are variables, then say. Much here in C it looked like this and nicely enough you can probably guess already which what's going to change here. Like the F is about to go away, the backslash n is about to go away, the semicolon is about to go away, but some other stuff's about to go away as well. Focus your attention on the syntax like parentheses and curly braces because in Python it's just that. So we got rid of the parentheses because they didn't really add all that much logically. We got rid of the curly braces, which technically we could do in C anytime there's a single line of code inside of a conditional,

49:33 but for consistency stylistically we always use them as well. Python though does not have you use any of those curly braces at all, but Python requires that you indent your code. Properly. So if you've ever been among those who are writing out your program and like everything is just crazily like left aligned and just a big mess until Style 50 swoops in and cleans it up for you, you're not going to be able to write Python code like that anymore. That's been such a societal problem among programmers, newbies and professionals alike, that the language itself requires logically that if you want this line of code to execute if this boolean. Expression is true, you've got to indent this line by convention 4 spaces. You can't be lazy and leave it all left aligned and sort of fix it up later. This has made Python code arguably more

50:18 readable because of these language-based requirements. Meanwhile, let's look at a ifE construct in Scratch, which looked a little something like this and see, it looked like this, which is kind of a lot of lines just to express a simple idea. All of those same things. Going to go away whereby in Python it looks like this instead and the only other difference worth calling out is that because you don't have the curly braces, you do have a colon which precedes the subsequent indentation as well. Meanwhile, if we've got an if if els in scratch in C, of course it looked like this. A lot of this is going to go away in the flash of a screen, but there's going to be a curiosity, which is not in fact a typo. Notice what happens with the LSIF. It's abbreviated L if, and honestly to this day, all these years later, I can never remember if it's L if or LSI

51:03 because different languages use different shorthand spellings of this phrase. It's LF in Python, because that's maybe the most succinct you can make the two words themselves, but everything else is effectively the same, including the additional colon this time. OK, questions on. Any of those conditionals and syntax, yeah. What a good question. What language did they code Python in? The interpreter we are using within VS Code is itself written in C, AKA C Python. However, you can implement a Python interpreter really in any language, including machine code like raw zeros and ones if you have that much free time in assembly. Language which we saw briefly weeks ago. You could write an interpreter for Python in Python if you really

51:49 want to be meta about it or in C++ or in Java. This is the thing about programming languages you can use any language to create a compiler for or interpreter for another language. What's going to vary is just how easy or difficult it is and how much time it therefore takes you. Good question. Other questions on any of these here features. All right, well, let's do something a little bit different in Python visa VC by opening up maybe a comparison program that we looked at some time ago. So let me go back to VS code here. I'm going to close my calculator and I'm going to open up now from my distribution code today a version of our comparison program from a while back which was essentially the

52:34 Uh, version 30 index thereof. So this one has comments, which the very first one in week 1 did not, but notice as a refresher what this comparison program was doing. It was including CS 50.H and standard.O.H. It was prompting the user for two integers via get in X and Y. It was then doing a very simple comparison comparing X against Y to determine if it's less than, greater than, or the same as. X and uh the same or equal to the same. So, just so that we can go through the motions of converting one of these to the other, let's do that side by side. Let me code a program called Compare.i. Let me close my terminal, drag the Python version over to the right here. And without comments this time, let's just do from CS 50 import get in.

53:20 Then below that let's do x equals get in and ask the user for what's X question mark. Then let's ask the user for Y using get in quote unquote what's why mark. Then below that let's do if x less than Y call in. Go ahead and print quote unquote X is less than Y L if X greater than Y, go ahead and print quote unquote X is greater than Y else coin, let's go ahead and print out quote unquote X is equal toy. So I dare say these are now equivalents. It's clearly fewer lines because a lot of the lines that left were admittedly comments, but also some curly braces and there's more syntax like parentheses that we got rid of too.

54:05 Let me open my terminal window. Let me run Python of compare.i. We'll type in 1 and 21 is less than uh X is less than Y. Let's do it again using 2 and 1. X is greater than Y. Let's do it one last time, 1 and 1, and of course those two now are equal to. Each other. all right, but why go down this road again because that was kind of a simple exercise but recall that we introduced this comparison of ants because it was so sort of stupidly simple, even if the syntax of that week was completely new but we ran into an issue pretty fast when we started comparing. Strings and that was a problem we really only fixed in week 4 when we finally revealed what a string actually is. If we focus a bit more on Python strings, it turns out that we can solve that problem much more easily in the world of Python.

54:53 In fact, let me go back to VS code here. Let me close these two versions of in comparison. Let me open up at left a version of my program. That I brought with me here that contains a version from week 2 wherein we finally revealed that a string is just a char star but recalled that the solution in week 4 as well as in week 1 when we first encountered this problem was to use stom, a function that whose purpose in life is to compare two strings character by character by character using a 4 loop or something like that. But they have knowledge, therefore, of how to navigate pointers, how to look for the null character, the backslash zero at the end, and all of that came from our friend string.h. Well, how can we go about implementing the same idea in Python? Well, let's open up VS codes,

55:39 Terminal window, open up a new program called Compare.ie, but this time, let's get rid of the integer version there. Of let's get 2 ins from the user, and I won't even use any CS 50 training wheels. Let's just use the input function to get S and ask the user for a value of S. So S colon close quote with a space, T equals input ask the user for a variable T. And then let's just ask the question if S equals equals t, then print out quote unquote same. Else, go ahead and print out quote unquote different. Let me move these side by side, just so you can see the difference. Notice how much code we have to write and how much we needed to understand in order to compare something as trivial as two strings and see.

56:24 But in Python we're literally just using equals equals and let's see if it actually works. So Python of compare.pi enter. Let's type in maybe cat for S and dog for T, and those are in fact different, but we would have gotten the same answer in C. Let's rerun Pythonfcompaed.pi and type in cat, type in cat again. And now it's detecting them the same. So wonderfully, Python has solved that seemingly annoying problem of not taking us literally like don't compare the pointer against the pointer. Compare what a reasonable programmer probably really cares about the values of those strings. So the equal equals is doing all of the 4 loop or the Y loop, iterating over those things character by character and actually giving us the answer we want. So what else gets easier in Python? Well let's focus a bit more on these strings.

57:11 Let me go back into VS code here. Let me close out our two comparison programs and clear my terminal, and let me go ahead and open up a prior program that we wrote, that one called Agree.c, and namely in the staff version of the code online, this was agree2.c, which is where we left it. Now recall in this C program that we did the following. We first, using CS50's GetHA function, prompted the user for a char, hopefully Y or N for yes or no, respectively. And then we used a Boolean expression and actually the combination of two using the two vertical bars to ask whether the inputted character is capital Y or the inputted character is lowercase y. And if so, we went ahead and printed out that the user agreed. Otherwise if they type in anything else for that character, we simply print it out, not agreed. Well, how can we go about implementing that same program in Python,

57:58 for instance, in a file called agree.ie? Well, let me go ahead. And open up my terminal window again. Let's create a file called agree.i. As before, let me go ahead and drag it over to the right so we can see these two things side by side, and let me go ahead and do this. I'm going to set a variable, say, called S equal to the return value of input, quote unquote. Do you agree there by asking the user the same question as before.

…

Share

Más resúmenes de videos