In [1]:
message = "Hello Python world!"
print(message)
A variable holds a value. You can change the value of a variable at any point.
In [2]:
###highlight=[5,6]
message = "Hello Python world!"
print(message)
message = "Python is my favorite language!"
print(message)
In [12]:
message = "Thank you for sharing Python with the world, Guido!"
print(mesage)
Let's look through this error message. First, we see it is a NameError. Then we see the file that caused the error, and a green arrow shows us what line in that file caused the error. Then we get some more specific feedback, that "name 'mesage' is not defined".
You may have already spotted the source of the error. We spelled message two different ways. Python does not care whether we use the variable name "message" or "mesage". Python only cares that the spellings of our variable names match every time we use them.
This is pretty important, because it allows us to have a variable "name" with a single name in it, and then another variable "names" with a bunch of names in it.
We can fix NameErrors by making sure all of our variable names are spelled consistently.
In [13]:
###highlight=[3]
message = "Thank you for sharing Python with the world, Guido!"
print(message)
In case you didn't know Guido van Rossum created the Python language over 20 years ago, and he is considered Python's Benevolent Dictator for Life. Guido still signs off on all major changes to the core Python language.
In [ ]:
my_string = "This is a double-quoted string."
my_string = 'This is a single-quoted string.'
This lets us make strings that contain quotations.
In [ ]:
quote = "Linus Torvalds once said, 'Any program is only as good as it is useful.'"
In [4]:
first_name = 'eric'
print(first_name)
print(first_name.title())
It is often good to store data in lower case, and then change the case as you want to for presentation. This catches some TYpos. It also makes sure that 'eric', 'Eric', and 'ERIC' are not considered three different people.
Some of the most common cases are lower, title, and upper.
In [6]:
###highlight=[6,8,9]
first_name = 'eric'
print(first_name)
print(first_name.title())
print(first_name.upper())
first_name = 'Eric'
print(first_name.lower())
You will see this syntax quite often, where a variable name is followed by a dot and then the name of an action, followed by a set of parentheses. The parentheses may be empty, or they may contain some values.
variable_name.action()
In this example, the word "action" is the name of a method. A method is something that can be done to a variable. The methods 'lower', 'title', and 'upper' are all functions that have been written into the Python language, which do something to strings. Later on, you will learn to write your own methods.
In [8]:
first_name = 'ada'
last_name = 'lovelace'
full_name = first_name + ' ' + last_name
print(full_name.title())
The plus sign combines two strings into one, which is called "concatenation". You can use as many plus signs as you want in composing messages. In fact, many web pages are written as giant strings which are put together through a long series of string concatenations.
In [9]:
###highlight=[6,7,8]
first_name = 'ada'
last_name = 'lovelace'
full_name = first_name + ' ' + last_name
message = full_name.title() + ' ' + "was considered the world's first computer programmer."
print(message)
If you don't know who Ada Lovelace is, you might want to go read what Wikipedia or the Computer History Museum have to say about her. Her life and her work are also the inspiration for the Ada Initiative, which supports women who are involved in technical fields.
The term "whitespace" refers to characters that the computer is aware of, but are invisible to readers. The most common whitespace characters are spaces, tabs, and newlines.
Spaces are easy to create, because you have been using them as long as you have been using computers. Tabs and newlines are represented by special character combinations.
The two-character combination "\t" makes a tab appear in a string. Tabs can be used anywhere you like in a string.
In [17]:
print("Hello everyone!")
In [18]:
print("\tHello everyone!")
In [19]:
print("Hello \teveryone!")
The combination "\n" makes a newline appear in a string. You can use newlines anywhere you like in a string.
In [21]:
print("Hello everyone!")
In [22]:
print("\nHello everyone!")
In [23]:
print("Hello \neveryone!")
In [24]:
print("\n\n\nHello everyone!")
Many times you will allow users to enter text into a box, and then you will read that text and use it. It is really easy for people to include extra whitespace at the beginning or end of their text. Whitespace includes spaces, tabs, and newlines.
It is often a good idea to strip this whitespace from strings before you start working with them. For example, you might want to let people log in, and you probably want to treat 'eric ' as 'eric' when you are trying to see if I exist on your system.
You can strip whitespace from the left side, the right side, or both sides of a string.
In [10]:
name = ' eric '
print(name.lstrip())
print(name.rstrip())
print(name.strip())
It's hard to see exactly what is happening, so maybe the following will make it a little more clear:
In [11]:
name = ' eric '
print('-' + name.lstrip() + '-')
print('-' + name.rstrip() + '-')
print('-' + name.strip() + '-')
In [28]:
print(3+2)
In [30]:
print(3-2)
In [31]:
print(3*2)
In [1]:
print(3/2)
In [2]:
print(3**2)
You can use parenthesis to modify the standard order of operations.
In [4]:
standard_order = 2+3*4
print(standard_order)
In [5]:
my_order = (2+3)*4
print(my_order)
In [6]:
print(0.1+0.1)
However, sometimes you will get an answer with an unexpectly long decimal part:
In [7]:
print(0.1+0.2)
This happens because of the way computers represent numbers internally; this has nothing to do with Python itself. Basically, we are used to working in powers of ten, where one tenth plus two tenths is just three tenths. But computers work in powers of two. So your computer has to represent 0.1 in a power of two, and then 0.2 as a power of two, and express their sum as a power of two. There is no exact representation for 0.3 in powers of two, and we see that in the answer to 0.1+0.2.
Python tries to hide this kind of stuff when possible. Don't worry about it much for now; just don't be surprised by it, and know that we will learn to clean up our results a little later on.
You can also get the same kind of result with other operations.
In [8]:
print(3*0.1)
There are a couple differences in the way Python 2 and Python 3 handle numbers. In Python 2, dividing two integers always results in an integer, while Python 3 always returns a float. This is fine when the result of your integer division is an integer, but it leads to quite different results when the answer is a decimal.
In [2]:
# Python 2.7
print 4/2
In [1]:
# Python 2.7
print 3/2
In [11]:
# Python 3.3
print(4/2)
In [12]:
# Python 3.3
print(3/2)
If you are getting numerical results that you don't expect, or that don't make sense, check if the version of Python you are using is treating integers differently than you expect.
(HINT) Don't spend too much time on this, unless you like reading on forums about installing from packages and what not.
If you just want to play around with Python 2 and Python 3, you can easily do so on pythontutor.com. Click "Start using Online Python Tutor now", and then delete the sample code in the text box so you can enter your own code. On that page, there is a drop-down list just below the text box that lets you select different versions of Python. Click "Visualize Execution" to run your code. On the next page, you can either click "Forward" to step through your code one line at a time, or click "Last" to run your entire program.
As you begin to write more complicated code, you will have to spend more time thinking about how to code solutions to the problems you want to solve. Once you come up with an idea, you will spend a fair amount of time troubleshooting your code, and revising your overall approach.
Comments allow you to write in English, within your program. In Python, any line that starts with a pound (#) symbol is ignored by the Python interpreter.
In [1]:
# This line is a comment.
print("This line is not a comment, it is code.")
Writing good comments is one of the clear signs of a good programmer. If you have any real interest in taking programming seriously, start using comments now. You will see them throughout the examples in these notebooks.
The Python community is incredibly large and diverse. People are using Python in science, in medicine, in robotics, on the internet, and in any other field you can imagine. This diverse group of thinkers has developed a collective mindset about how programs should be written. If you want to understand Python and the community of Python programmers, it is a good idea to learn the ways Python programmers think.
You can easily see a set of guiding principles that is written right into the language:
In [2]:
import this
There is a lot here. Let's just take a few lines, and see what they mean for you as a new programmer.
Beautiful is better than ugly.
Python programmers recognize that good code can actually be beautiful. If you come up with a particularly elegant or efficient way to solve a problem, especially a difficult problem, other Python programmers will respect your work and may even call it beautiful. There is beauty in high-level technical work.
Explicit is better than implicit.
It is better to be clear about what you are doing, than come up with some shorter way to do something that is difficult to understand.
Simple is better than complex.
Complex is better than complicated.
Keep your code simple whenever possible, but recognize that we sometimes take on really difficult problems for which there are no easy solutions. In those cases, accept the complexity but avoid complication.
Readability counts.
There are very few interesting and useful programs these days that are written and maintained entirely by one person. Write your code in a way that others can read it as easily as possible, and in a way that you will be able to read and understand it 6 months from now. This includes writing good comments in your code.
There should be one-- and preferably only one --obvious way to do it.
There are many ways to solve most problems that come up in programming. However, most problems have a standard, well-established approach. Save complexity for when it is needed, and solve problems in the most straightforward way possible.
Now is better than never.
No one ever writes perfect code. If you have an idea you want to implement it, write some code that works. Release it, let it be used by others, and then steadily improve it.
We have learned quite a bit so far about programming, but we haven't learned enough yet for you to go create something. In the next notebook, things will get much more interesting, and there will be a longer list of overall challenges.
In [4]:
# I learned how to strip whitespace from strings.
name = '\t\teric'
print("I can strip tabs from my name: " + name.strip())
As I have said earlier, the Python community is incredibly rich and diverse. Here are a couple resources to look at, if you want to do some exploring.
The main Python website is probably not of too much interest to you at this point, but it is a great resource to know about as you start to learn more.
The Python Conference (PyCon) is an incredible event, and the community is entirely welcoming to new programmers. They happen all over the world, throughout the year. If you can make your way to one of these conferences, you will learn a great deal and meet some really interesting people.
Women and minorities are still under-represented in most technology fields, and the programming world is no different in this regard. That said, the Python community may well be the most welcoming and supportive programming community for women and minorities. There are a number of groups dedicated to bringing women and minorities together around programming in Python, and there are a number of explicit Codes of Conduct for Python-related events.
PyLadies is one of the most visible of these organizations. They are a great resource, so go see what they do and what they have to offer.
Wherever there are a number of Python programmers, they will find a way to get together. Python user groups are regular meetings of Python users from a local area. Go take a look at the list of user groups, and see if there is one near you.