In this section, you will learn to store information in variables.
You will learn about two types of data: strings, which are sets of characters, and numerical data types.
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]:
message = "Hello Python world!"
print(message)
message = "Python is my favorite language!"
print(message)
In [3]:
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 [4]:
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 [5]:
# Ex 2.1 : Hello World - Variable
# put your code here
In [6]:
# Ex 2.2 : One Variable, Two Messages
# put your code here
In [7]:
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 [8]:
quote = "Linus Torvalds once said, \
'Any program is only as good as it is useful.'"
In [12]:
multiline_string = '''This is a string where I
can confortably write on multiple lines
without worring about to use the escape character "\\" as in
the previsou example.
As you'll see, the original string formatting is preserved.
'''
print(multiline_string)
In [13]:
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 [16]:
first_name = 'eric'
print(first_name)
print(first_name.title())
print(first_name.upper())
first_name_titled = 'Eric'
print(first_name_titled.lower())
Note: Please notice that the original strings remain always unchanged
In [18]:
print(first_name)
print(first_name_titled)
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 [19]:
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 [20]:
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.
In [49]:
string_template = 'The result of the calculation of {calc} is {res}'
print("String Template: ", string_template)
print(string_template.format(calc='(3*4)+2', res=(3*4)+2))
For further information about String formatting, see the official online documentation about the string
module.
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 [21]:
print("Hello everyone!")
In [22]:
print("\tHello everyone!")
In [23]:
print("Hello \teveryone!")
The combination "\n" makes a newline appear in a string. You can use newlines anywhere you like in a string.
In [24]:
print("Hello everyone!")
In [25]:
print("\nHello everyone!")
In [26]:
print("Hello \neveryone!")
In [27]:
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 [28]:
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 [29]:
name = ' eric '
print('-' + name.lstrip() + '-')
print('-' + name.rstrip() + '-')
print('-' + name.strip() + '-')
In [30]:
# Ex 2.3 : Someone Said
# put your code here
In [31]:
# Ex 2.4 : First Name Cases
# put your code here
In [32]:
# Ex 2.5 : Full Name
# put your code here
In [33]:
# Ex 2.6 : About This Person
# put your code here
In [34]:
# Ex 2.7 : Name Strip
# put your code here
In [35]:
print(3+2)
In [36]:
print(3-2)
In [37]:
print(3*2)
In [38]:
print(3/2)
In [39]:
print(3**2)
You can use parenthesis to modify the standard order of operations.
In [40]:
standard_order = 2+3*4
print(standard_order)
In [41]:
my_order = (2+3)*4
print(my_order)
In [42]:
print(0.1+0.1)
However, sometimes you will get an answer with an unexpectly long decimal part:
In [43]:
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 [44]:
print(3*0.1)
In [50]:
# Test
3 * 0.1 == 0.3
Out[50]:
decimal
to the rescueThe decimal
module provides support for fast correctly-rounded decimal floating point arithmetic. It offers several advantages over the float datatype.
For Example:
In [3]:
from decimal import Decimal, getcontext
getcontext().prec = 17
result = 3 * Decimal(0.1)
print(type(result))
print(3 * Decimal(0.1))
print(3 * 0.1)
In [46]:
# Ex 2.8 : Arithmetic
a = 6
b = 5
print("a + b = ", end='')
o = a+b
print(o)
In [47]:
# Ex 2.9 : Order of Operations
result = (3*4)+2
print('The result of the calculation of (3*4)+2', result, sep=' = ')
In [ ]:
# Ex 2.10 : Long Decimals
print(3.125 / 0.2)
In [ ]:
In [ ]:
# Challenge: Neat Arithmetic
# Put your code here
In [ ]:
# Challenge: Neat Order of Operations
# Put your code here
In [ ]:
# Challenge: Long Decimals - Pattern
# Put your code here
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 [4]:
# This line is a comment.
#this
#is
#not
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.
In [55]:
# Ex 2.10 : First Comments
# put your code here
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 [57]:
# Overall Challenge
# Put your code here
In [58]:
# I learned how to strip whitespace from strings.
name = '\t\teric'
print("I can strip tabs from my name: " + name.strip())