Your First Program
While the interac ve shell is good for running Python instruc ons one at a
me, to write en re Python programs you’ll enter the instruc ons into the file
editor. The file editor is similar to text editors such as Notepad and TextMate,
but it has some features specifically for entering source code. To open a new
file in Mu, click the New bu on on the top row.
The tab that appears should contain a cursor awai ng your input, but it’s different from the
interac ve shell, which runs Python instruc ons as soon as you press ENTER. The file editor lets
you enter many instruc ons, save the file, and run the program. Here’s how you can tell the
difference between the two:
The interac ve shell will always be the one with the >>> or In [1]: prompt.
The file editor won’t have the >>> or In [1]: prompt.
Now it’s me to create your first program! When the file editor window opens, enter the
following into it:
# This program says hello and asks for my name.
print('Hello, world!')
print('What is your name?') # Ask for their name.
my_name = input('>')
print('It is good to meet you, ' + my_name)
print('The length of your name is:')
print(len(my_name))
print('What is your age?') # Ask for their age.
my_age = input('>')
print('You will be ' + str(int(my_age) + 1) + ' in a year.')
Once you’ve entered your source code, save it so that you won’t have to retype it each me
you start Mu. Click Save, enter [Link] in the File Name field, and then click Save.
You should save your programs every once in a while as you type them. That way, if the
computer crashes or you accidentally exit Mu, you won’t lose the code. As a shortcut, you can
press CTRL-S on Windows and Linux or -S on macOS to save your file.
Once you’ve saved, let’s run our program. Press the F5 key or click the Run bu on. Enter your
name when your program asks for it. The program’s output in the interac ve shell should look
something like this:
Hello, world!
What is your name?
>Al
It is good to meet you, Al
The length of your name is:
What is your age?
>4
You will be 5 in a year.
>>>
When there are no more lines of code to execute, the Python program terminates; that is, it
stops running. (You can also say that the Python program exits.) The Mu editor displays the >>>
interac ve shell prompt a er the program terminated, in case you’d like to enter some further
Python code.
You can close the file editor by clicking the X on the file’s tab, just like closing a browser tab. To
reload a saved program, click Load from the menu. Do that now, and in the window that
appears, choose [Link] and click the Open bu on. Your previously saved [Link] program
should open in the file editor window.
h p://[Link]
You can view the step-by-step execu on of a program using the Python Tutor visualiza on tool
at
(h p://[Link]). Click the forward bu on to move through
each step of the program’s execu on. You’ll be able to see how the variables’ values and the
output change.
Dissec ng the Program
With your new program open in the file editor, let’s take a quick tour of the
Python instruc ons it uses by looking at what each line of code does.
Comments
The following line is called a comment:
# This program says hello and asks for my name.
Python ignores comments, and you can use them to write notes or remind yourself what the
code is trying to do. Any text for the rest of the line following a hash mark (#) is part of a
comment.
Some mes programmers will put a # in front of a line of code to temporarily remove it while
tes ng a program. This is called commen ng out code, and it can be useful when you’re trying
to figure out why a program isn’t working. You can remove the # later when you are ready to
put the line back in.
Python also ignores the blank line a er the comment. You can add as many blank lines to your
program as you want. This spacing can make your code easier to read, like paragraphs in a
book.
The print() Func on
The
print()
(h ps://[Link]/3/library/func [Link]#print) func on
displays the string value inside its parentheses on the screen:
print('Hello, world!')
print('What is your name?') # Ask for their name.
The line print('Hello, world!') means “Print out the text in the string 'Hello, world!'.”
When Python executes this line, you say that Python is calling the print() func on and the
string value is being passed to the func on. A value that is passed to a func on call is an
argument. No ce that the quotes are not printed to the screen. They just mark where the string
begins and ends; they are not part of the string value’s text.
NOTE
You can also use this func on to display a blank line on the screen; call print() with nothing
in between the parentheses.
When you write a func on name, the opening and closing parentheses at the end iden fy it as
the name of a func on. This is why in this book, you’ll see print() rather than print. It’s a
standard conven on to have no spaces in between the func on name and the opening
parentheses, even though Python doesn’t require this. Chapter 3 describes func ons in more
detail.
The input() Func on
The
input()
(h ps://[Link]/3/library/func [Link]#input) func on
waits for the user to type some text on the keyboard and press ENTER:
my_name = input('>')
This func on call evaluates to a string iden cal to the user’s text, and the rest of the code
assigns the my_name variable to this string value. The '>' string passed to the func on causes
the > prompt to appear, which serves as an indicator to the user that they are expected to
enter something. Your programs don’t have to pass a string to the input() func on; if you call
input(), the program will wait for the user’s text without displaying any prompt.
THE > AND >>> PROMPTS
You can pass any string to input() to change the prompt that appears when your
program runs. Calling input('>') puts an angle bracket > on the screen as the prompt.
This is different from the >>> prompt that appears in the Python interac ve shell. In this
book, the >>> prompt indicates a response to the Python interac ve shell and the >
prompt indicates a response to a program running the input('>') call. My choice of '>'
was arbitrary; you can use any prompt you want or no prompt at all.
You can think of the input() func on call as an expression that evaluates to whatever string
the user typed. If the user entered 'Al', the assignment statement would effec vely be
my_name = 'Al'.
If you call input() and see an error message, like NameError: name 'Al' is not defined,
the problem is that you’re running the code with Python 2 instead of Python 3.
The Gree ng Message
The following call to print() contains the expression 'It is good to meet you, ' +
my_name between the parentheses:
print('It is good to meet you, ' + my_name)
Remember that expressions can always evaluate to a single value. If 'Al' is the value stored in
my_name, then this expression evaluates to 'It is good to meet you, Al'. This single
string value is then passed to print(), which prints it on the screen.
The len() Func on
You can pass the
len()
(h ps://[Link]/3/library/func [Link]#len)
func on a string value (or a variable containing a string), and the func on evaluates to the
integer value of the number of characters in that string:
print('The length of your name is:')
print(len(my_name))
Enter the following into the interac ve shell to try this:
>>> len('hello')
>>> len('My very energe c monster just scarfed nachos.')
46
>>> len('')
Just like in those examples, len(my_name) evaluates to an integer. We say that the len()
func on call returns or outputs this integer value, and the value is the func on call’s return
value. It is then passed to print() to be displayed on the screen. The print() func on allows
you to pass it either integer values or string values, but no ce the error that shows up when
you enter the following into the interac ve shell:
>>> print('I am ' + 29 + ' years old.')
Traceback (most recent call last):
File "<python-input-0>", line 1, in <module>
print('I am ' + 29 + ' years old.')
TypeError: can only concatenate str (not "int") to str
The print() func on isn’t causing that error; rather, it’s the expression you tried to pass to
print(). You’ll get the same error message if you type the expression into the interac ve shell
on its own:
>>> 'I am ' + 29 + ' years old.'
Traceback (most recent call last):
File "<python-input-0>", line 1, in <module>
'I am ' + 29 + ' years old.'
TypeError: can only concatenate str (not "int") to str
Python gives an error because the + operator can be used only to add two numbers together
or to concatenate two strings. You can’t add an integer to a string because this is not allowed
in Python. You can fix this by using a string version of the integer instead, as explained in the
next sec on.
The str(), int(), and float() Func ons
If you want to concatenate an integer such as 29 with a string to pass to print(), you’ll need
to get the value '29', which is the string form of 29. The str() func on can be passed an
integer value and will return a string value version of the integer, as follows:
>>> str(29)
'29'
>>> print('I am ' + str(29) + ' years old.')
I am 29 years old.
Because str(29) evaluates to '29', the expression 'I am ' + str(29) + ' years old.'
evaluates to 'I am ' + '29' + ' years old.', which in turn evaluates to 'I am 29 years
old.' This is the string value that is passed to the print() func on.
The str(), int(), and float() func ons will evaluate to the string, integer, and floa ng
point forms of the value you pass, respec vely. Try conver ng some values in the interac ve
shell with these func ons, and watch what happens:
>>> str(0)
'0'
>>> str(-3.14)
'-3.14'
>>> int('42')
42
>>> int('-99')-99
>>> int(1.25)
>>> int(1.99)
>>> float('3.14')
3.14
>>> float(10)
10.0
The previous examples call the str(), int(), and float() func ons and pass them values of
the other data types to obtain a string, integer, or floa ng-point form of those values.
The str() func on is handy when you have an integer or float that you want to concatenate
to a string. The int() func on is also helpful if you have a number as a string value that you
want to use in some mathema cs. For example, the input() func on always returns a string,
even if the user enters a number. Enter spam = input() into the interac ve shell, then enter 101
when it waits for your text:
>>> spam = input()
101
>>> spam
'101'
The value stored inside spam isn’t the integer 101 but the string '101'. If you want to do math
using the value in spam, use the int() func on to get its integer form and then store this as
the variable’s new value. If spam is the string '101', then the expression int(spam) will
evaluate to the integer value 101, and the assignment statement spam = int(spam) will be
equivalent to spam = 101:
>>> spam = int(spam)
>>> spam
101
Now you should be able to treat the spam variable as an integer instead of a string:
>>> spam * 10 / 5
202.0
Note that if you pass a value to int() that it cannot evaluate as an integer, Python will display
an error message:
>>> int('99.99')
Traceback (most recent call last):
File "<python-input-0>", line 1, in <module>
int('99.99')
ValueError: invalid literal for int() with base 10: '99.99'
>>> int('twelve')
Traceback (most recent call last):
File "<python-input-0>", line 1, in <module>
int('twelve')
ValueError: invalid literal for int() with base 10: 'twelve'
>>> int(7.7)
>>> int(7.7) + 1
The int() func on is also useful if you need to round a floa ng-point number down:
You used the int() and str() func ons in the last three lines of your program to get a value
of the appropriate data type for the code:
print('What is your age?') # Ask for their age.
my_age = input('>')
print('You will be ' + str(int(my_age) + 1) + ' in a year.')
The my_age variable contains the value returned from input(). Because the input() func on
always returns a string (even if the user entered a number), you can use the int(my_age) code
to return an integer value of the string in my_age. This integer value is then added to 1 in the
expression int(my_age) + 1.
TEXT AND NUMBER EQUIVALENCE
Although the string value of a number is considered a completely different value from the
integer or floa ng-point version, an integer can be equal to a floa ng point:
>>> 42 == '42'
False
>>> 42 == 42.0
True
>>> 42.0 == 0042.000
True
Python makes this dis nc on because strings are text, while integers and floats are
numbers.
The result of this addi on is passed to the str() func on: str(int(my _age) + 1). The string
value returned is then concatenated with the strings 'You will be ' and ' in a year.' to
evaluate to one large string value. This large string is finally passed to print() to be displayed
on the screen.
Let’s say the user enters the string '4' for my_age. The evalua on steps would look something
like the following:
Descrip on
The string '4' is converted to an integer, so you can add 1 to it. The result is 5. The str()
func on converts the result back to a string, so you can concatenate it with the second string,
'in a year.', to create the final message.
The type() Func on
Integer, floa ng-point, and string aren’t the only data types in Python. As you con nue to learn
about programming, you may come across values of other data types. You can always pass
these to the
type()
(h ps://[Link]/3/library/func [Link]#type)
func on to determine what type they are. For example, enter the following into the interac ve
shell:
>>> type(42)
<class 'int'>
>>> type(42.0)
<class 'float'>
>>> type('forty two')
<class 'str'>
>>> name = 'Zophie'
>>> type(name) # The name variable has a value of the string type.
<class 'str'>
>>> type(len(name)) # The len() func on returns integer values.
<class 'int'>
Not only can you pass any value to type(), but (as with any func on call) you can also pass it
any variable or expression to determine the data type of the value that it evaluates to. The
type() func on itself returns values, but the angle brackets mean they are not syntac cally
valid Python code; you cannot run code like spam = <class 'str'>.
The round() and abs() Func ons
Let’s learn about two more Python func ons that, like the len() func on, take an argument
and return a value. The
round()
(h ps://[Link]/3/library/func [Link]#round) func on accepts a float
value and returns the nearest integer. Enter the following into the interac ve shell:
>>> round(3.14)
>>> round(7.7)
>>> round(-2.2)-2
The round() func on also accepts an op onal second argument specifying how many decimal
places it should round. Enter the following into the interac ve shell:
>>> round(3.14, 1)
3.1
>>> round(7.7777, 3)
7.778
The behavior for rounding half numbers is a bit odd. The func on call round(3.5) rounds up
to 4, while round(2.5) rounds down to 2. For halfway numbers that end with .5, the number is
rounded to the nearest even integer. This is called banker’s rounding.
The
abs()
(h ps://[Link]/3/library/func [Link]#abs) func on
returns the absolute value of the number argument. In mathema cs, this is defined as the
distance from 0, but I find it easier to think of it as the posi ve form of the number. Enter the
following into the interac ve shell:
>>> abs(25)
25
>>> abs(-25)
25
>>> abs(-3.14)
3.14
>>> abs(0)
Python comes with several different func ons that you’ll learn about in this book. This sec on
demonstrates how you can experiment with them in the interac ve shell to see how they
behave with different inputs. This is a common technique for prac cing the new code that you
learn.