Lecture 0 - CS50's Introduction To Programming With Python
Lecture 0 - CS50's Introduction To Programming With Python
OpenCourseWare
Donate (https://cs50.harvard.edu/donate)
Lecture 0
Creating Code with Python
Functions
Bugs
Improving Your First Python Program
Variables
Comments
Pseudocode
Further Improving Your First Python Program
Strings and Paremeters
A small problem with quotation marks
Formatting Strings
More on Strings
Integers or int
Readability Wins
:
Float Basics
More on Floats
Def
Returning Values
Summing Up
Functions
■ Functions are verbs or actions that the computer or computer language will
already know how to perform.
■ In your hello.py program, the print function knows how to print to the
terminal window.
■ The print function takes arguments. In this case, "hello, world" are the
arguments that the print function takes.
:
Bugs
■ Bugs are a natural part of coding. These are mistakes, problems for you to solve!
Don’t get discouraged! This is part of the process of becoming a great
programmer.
■ Imagine in our hello.py program that accidentally typed print("hello,
world" notice that we missed the final ) required by the compiler. If I
purposefully make this mistake, you’ll the compiler will output an error in the
terminal window!
■ Often, the error messages will inform you of your mistakes and provide you
clues on how to fix them. However, there will be many times when the compiler
is not this kind.
■ This edit alone, however, will not allow your program to output what your user
inputs. For that, we will need to introduce you to variables
Variables
■ A variable is just a container for a value within your own program.
■ In your program, you can introduce your own variable in your program by editing
it to read
Notice that this equal = sign in the middle of name = input("What's your
name? ") has a special role in programming. This equal sign literally assigns
what is on the right to what is on the left. Therefore, the value returned by
:
input("What's your name? ") is assigned to name .
■ The program will return hello, name in the terminal window regardless of
what the user types.
■ Further editing our code, you could type
Comments
■ Comments are a way for programmers to track what they are doing in their
programs and even inform others about their intentions for a block of code. In
short, they are notes for yourself and others who will see your code!
■ You can add comments to your program to be able to see what it is that your
program is doing. You might edit your code as follows:
Pseudocode
■ Pseudocode is an important type of comment that becomes a special type of to-
:
do list, especially when you don’t understand how to accomplish a coding task.
For example, in your code, you might edit your code to say:
# Print hello
print("hello,")
By providing end="" we are overwriting the default value of end such that it
never creates a new line after this first print statement. Providing the name as
“David”, the output in the terminal window will be hello, David .
■ Parameters, therefore, are arguments that can be taken by a function.
■ You can learn more in Python’s documentation on print
(https://docs.python.org/3/library/functions.html#print).
More on Strings
■ You should never expect your user to cooperate as intended. Therefore, you will
need to ensure that the input of your user is corrected or checked.
■ It turns out that built into strings is the ability to remove whitespace from a
string.
■ By utilizing the method strip on name as name = name.strip() , will strip
all the whitespaces on the left and right of the users input. You can modify your
code to be:
Rerunning this program, regardless of how many spaces you type before or after
the name, it will strip off all the whitespace.
■ Using the title method, it would title case the user’s name:
■ By this point, you might be very tired of typing python repeatedly in the
terminal window. You cause use the up arrow of your keyboard to recall the
most recent terminal commands you have made.
■ Notice that you can modify your code to be more efficient:
# Remove whitespace from the str and capitalize the first letter of each
name = name.strip().title()
# Ask the user for their name, remove whitespace from the str and capital
name = input("What's your name? ").strip().title()
Integers or int
■ In Python, an integer is referred to as an int .
■ In the world of mathematics, we are familiar with +, -, *, /, and % operators. That
last operator % or modulo operator may not be very familiar to you.
■ You don’t have to use the text editor window in your compiler to run Python
code. Down in your terminal, you can run python alone. You will be presented
with >>> in the terminal window. You can then run live, interactive code. You
could type 1+1 , and it will run that calculation. This mode will not commonly
be used during this course.
:
■ Opening up VS Code again, we can type code calculator.py in the terminal.
This will create a new file in which we will create our own calculator.
■ First, we can declare a few variables.
x = 1
y = 2
z = x + y
print(z)
x = input("What's x? ")
y = input("What's y? ")
z = x + y
print(z)
x = input("What's x? ")
y = input("What's y? ")
z = int(x) + int(y)
print(z)
The result is now correct. The use of int(x) is called “casting,” where a value is
temporarily changed from one type of variable (in this case, a string) to another
(here, an integer).
■ We can further improve our program as follows:
x = int(input("What's x? "))
y = int(input("What's y? "))
print(x + y)
:
This illustrates that you can run functions on functions. The inner function is run
first, and then the outer one is run. First, the input function is run. Then, the
int function.
■ You can learn more in Python’s documtenation of int
(https://docs.python.org/3/library/functions.html?highlight=float#int).
Readability Wins
■ When deciding on your approach to a coding task, remember that one could
make a reasonable argument for many approaches to the same problem.
■ Regardless of what approach you take to a programming task, remember that
your code must be readable. You should use comments to give yourself and
others clues about what your code is doing. Further, you should create code in a
way that is readable.
Float Basics
■ A floating point value is a real number that has a decimal point in it, such as
0.52 .
x = float(input("What's x? "))
y = float(input("What's y? "))
print(x + y)
This change allows your user to enter 1.2 and 3.4 to present a total of 4.6 .
■ Let’s imagine, however, that you want to round the total to the nearest integer.
Looking at the Python documentation for round , you’ll see that the available
arguments are round(number[n, ndigits]) . Those square brackets indicate
that something optional can be specified by the programmer. Therefore, you
could do round(n) to round a digit to its nearest integer. Alternatively, you
could code as follows:
More on Floats
■ How can we round floating point values? First, modify your code as follows:
As we might expect, this will round the result to the nearest two decimal points.
■ We could also use fstring to format the output as follows:
This cryptic fstring code displays the same as our prior rounding strategy.
■ You can learn more in Python’s documentation of float
(https://docs.python.org/3/library/functions.html?highlight=float#float).
Def
■ Wouldn’t it be nice to create our own functions?
■ Let’s bring back our final code of hello.py by typing code hello.py into the
terminal window. Your starting code should look as follows:
# Ask the user for their name, remove whitespace from the str and capital
name = input("What's your name? ").strip().title()
We can better our code to create our own special function that says “hello” for
us!
■ Erasing all our code in our text editor, let’s start from scratch:
Attempting to run this code, your compiler will throw an error. After all, there is
no defined function for hello .
■ We can create our own function called hello as follows:
def hello():
print("hello")
Here, in the first lines, you are creating your hello function. This time, however,
you are telling the compiler that this function takes a single parameter: a
variable called to . Therefore, when you call hello(name) the computer
passes name into the hello function as to . This is how we pass values into
functions. Very useful! Running python hello.py in the terminal window,
you’ll see that the output is much closer to our ideal presented earlier in this
lecture.
■ We can change our code to add a default value to hello :
Test out your code yourself. Notice how the first hello will behave as you
might expect, and the second hello, which is not passed a value, will, by default,
output hello, world .
■ We don’t have to have our function at the start of our program. We can move it
down, but we need to tell the compiler that we have a main function and a
separate hello function.
def main():
This alone, however, will create an error of sorts. If we run python hello.py ,
nothing happens! The reason for this is that nothing in this code is actually
calling the main function and bringing our program to life.
■ The following very small modification will call the main function and restore
our program to working order:
def main():
main()
Returning Values
■ You can imagine many scenarios where you don’t just want a function to
perform an action but also to return a value back to the main function. For
example, rather than simply printing the calculation of x + y , you may want a
function to return the value of this calculation back to another part of your
program. This “passing back” of a value we call a return value.
■ Returning to our calculator.py code by typing code calculator.py . Erase
all code there. Rework the code as follows:
def main():
x = int(input("What's x? "))
print("x squared is", square(x))
def square(n):
return n * n
main()
Summing Up
Through the work of this single lecture, you have learned abilities that you will use
countless times in your own programs. You have learned about…