intro to programming in python
View the Project on GitHub nlouie/nlouie-intro-to-python-atbs
print("Hello world!")
Hello world!
Other helpful resources:
while (parentNotFound) {
foreach (aisle in aisles) {
if (parentIsInAisle) {
walkTowardsParent();
}
}
}
http://python.org/
From your terminal…
$ /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
$ brew install python3
$ sudo apt-get install python3
Python is a programming language (with syntax rules for writing what is considered valid Python code) and the Python interpreter software that reads source code (written in the Python language) and performs its instructions. You can download the Python interpreter for free at https://python.org/, and there are versions for Linux, macOS, and Windows.
The name Python comes from the surreal British comedy group Monty Python, not from the snake. Python programmers are affectionately called Pythonistas, and both Monty Python and serpentine references usually pepper Python tutorials and documentation.
I encourage you to type into the interactive shell, also called the REPL (Read-Evaluate-Print Loop), which lets you run (or execute) Python instructions one at a time and instantly shows you the results.
Using the interactive shell is great for learning what basic Python instructions do, so give it a try as you follow along. You’ll remember the things you do much better than the things you only read.
Open IDLE (should be installed with Python). An interactive shell will come up. Create a new file, and name it test.py
You can use this python file to write python programs. Run it from the menu bar, or pressing F5
>>>
prompt.>>>
prompt.Powershell.exe
, for MacOS, this is Terminal.app
, for Linux, this is /bin/bash
Download a text editor, like Atom
$ python
Python 3.7.7 (default, Mar 10 2020, 15:43:33)
[Clang 11.0.0 (clang-1100.0.33.17)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
Or run a python file
$ python file.py
Try Python online without downloading
https://repl.it/
Comments are ignored by the program
print('I am a statement!') # I am a line comment
# print('I am also a statement!')
print('Player number:', 1)
'''
I am a block comment
'''
I am a statement!
Player number: 1
'\nI am a block comment \n'
In Python, 2 + 2 is called an expression, which is the most basic kind of programming instruction in the language. Expressions consist of values (such as 2) and operators (such as +
), and they can always evaluate (that is, reduce) down to a single value. That means you can use expressions anywhere in Python code that you could also use a value.
Operator | Operation | Example | Evaluates to |
---|---|---|---|
** | exponent | 2 ** 3 | 8 |
% | Modulus/remainder | 22 % 8 | 6 |
// | Integer division/floored quotient | 22 // 8 | 2 |
/ | Division | 22 / 8 | 2.75 |
* | Multiplication | 3 * 5 | 15 |
- | Subtraction | 5 - 2 | 3 |
+ | Addition | 2 + 2 | 4 |
1 + 1
2
2 * 6
12
5 - 10
-5
(5 - 1) * ((7 + 1) / (3 - 1)) # PEMDAS
16.0
23 / 7
3.2857142857142856
23 // 7
3
23 % 7
2
10 ** 2
100
Programs will crash if they contain code the computer can’t understand, which will cause Python to show an error message. An error message won’t break your computer, though, so don’t be afraid to make mistakes. A crash just means the program stopped running unexpectedly.
Some error messages are helpful than others. It helps to use a search engine.
You can always test to see whether an instruction works by entering it into the interactive shell. Don’t worry about breaking the computer: the worst that could happen is that Python responds with an error message. Professional software developers get error messages while writing code all the time.
8 / 0
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-29-340e47a3b5ce> in <module>
----> 1 8 / 0
ZeroDivisionError: division by zero
Remember that expressions are just values combined with operators, and they always evaluate down to a single value. A data type is a category for values, and every value belongs to exactly one data type.
Data type | Example |
---|---|
String | “hello”, ‘hi’, ‘a’, ‘64 cats’ |
Integer | -2, -1, 0, 1, 2, 3, 4, 5 |
Float | -1.25, -1.0, -0.5, 0.0, 0.5, 1.0, 1.25 |
# strings
print('hello world')
hello world
'
or "
''
or ""
is considered an “empty string”The meaning of an operator may change based on the data types of the values next to it.
For example, +
is the addition operator when it operates on two integers or floating-point values.
However, when +
is used on two string values, it joins the strings as the string concatenation operator.
'alice' + 'bob'
'alicebob'
# Mixing data types can crash your program or cause unexpected behavior
'alice' + 2
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-32-281b897eb5c9> in <module>
1 # Mixing data types can crash your program or cause unexpected behavior
----> 2 'alice' + 2
TypeError: can only concatenate str (not "int") to str
'Alice' * 5
'AliceAliceAliceAliceAlice'
'Alice' * 5.0
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-34-43325524c797> in <module>
----> 1 'Alice' * 5.0
TypeError: can't multiply sequence by non-int of type 'float'
spam = 42
spam
42
x = 0
y = 1
x + y
1
full_name
again printed "Ghostface Killa"
. This is called overwriting the variable.first_name = "Biggie"
last_name = "Smalls"
full_name = first_name + " " + last_name # string concatenation
print(full_name)
Biggie Smalls
print(full_name)
Biggie Smalls
full_name = "Ghostface Killa"
print(full_name)
Ghostface Killa
Though you can name your variables almost anything, Python does have some naming restrictions. You can name a variable anything as long as it obeys the following three rules:
Valid variable names | Invalid variable names |
---|---|
current_balance | current-balance (hyphens are not allowed) |
currentBalance | current balance (spaces are not allowed) |
account4 | 4account (can’t begin with a number) |
_42 | 42 (can’t begin with a number) |
TOTAL_SUM | TOTAL_\$UM (special characters like $ are not allowed) |
hello | ‘hello’ (special characters like ‘ are not allowed) |
first_name
, First_name
, first_nAme
are all different variables.demo0.py
.# 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.')
F5
, or clicking “Run” from the menu.python
command. You may need to run with python3
if you have multiple versions installed on your machine# find where you saved your python file..such as your Desktop
$ cd ~/Desktop
$ python demo0.py
print()
Functionprint()
function displays the string value inside its parentheses on the screen.print('Hello, world!')
Hello, world!
print('Hello, world!')
means “Print out the text in the string ‘Hello, world!’.”print()
function and the string value is being passed to the function. A value that is passed to a function call is an argument.input()
Functioninput()
function waits for the user to type some text on the keyboard and press ENTER.'Al'
, then the expression would evaluate to my_name = 'Al'
.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.my_name = input()
print('It is good to meet you ' + my_name)
Al
It is good to meet you Al
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.
len()
FunctionYou can pass the len() function a string value (or a variable containing a string), and the function evaluates to the integer value of the number of characters in that string.
len("hello")
5
len("The quick brown fox jumped over the lazy dog")
44
len('')
0
len("")
0
len(my_name)
evaluates to an integer. It is then passed to print()
to be displayed on the screen.print()
function allows you to pass it either integer values or string values, but notice the error that shows up when you type the following into the interactive shell:print('I am ' + 29 + ' years old.')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-46-40e8f0b932d8> in <module>
----> 1 print('I am ' + 29 + ' years old.')
TypeError: can only concatenate str (not "int") to str
The print() function isn’t causing that error, but rather it’s the expression you tried to pass to print(). You get the same error message if you type the expression into the interactive shell on its own.
'I am ' + 29 + ' years old.'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-47-b2e1590c4132> in <module>
----> 1 'I am ' + 29 + ' years old.'
TypeError: can only concatenate str (not "int") to str
+
operator can only be used to add two integers together or concatenate two strings.str()
, int()
, and float()
Functions29
with a string to pass to print()
, you’ll need to get the value '29'
, which is the string form of 29
. The str()
function can be passed an integer value and will evaluate to a string value version of the integer, as follows:str(29)
'29'
print('I am ' + str(29) + ' years old.')
I am 29 years old.
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 value that is passed to the print()
function.str()
, int()
, and float()
functions will evaluate to the string, integer, and floating-point forms of the value you pass, respectively.str(0)
'0'
str(-3.14)
'-3.14'
int('42')
42
int('-99')
-99
int(1.25)
1
float(3.14)
3.14
float(10)
10.0
str()
, int()
, and float()
functions and pass them values of the other data types to obtain a string, integer, or floating-point form of those values.str()
function is handy when you have an integer or float that you want to concatenate to a string.int()
function is also helpful if you have a number as a string value that you want to use in some mathematics.input()
function always returns a string, even if the user enters a number. Enter spam = input()
into the interactive shell and enter 101
when it waits for your text.spam = input()
spam
101
'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() function to get the integer form of spam and then store this as the new value in spam.
spam = int(spam)
spam
101
Now you should be able to treat the spam variable as an integer instead of a string.
spam
101
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')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-60-7e09e10be494> in <module>
----> 1 int('99.99')
ValueError: invalid literal for int() with base 10: '99.99'
int('twelve')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-61-bcdccb17a8a6> in <module>
----> 1 int('twelve')
ValueError: invalid literal for int() with base 10: 'twelve'
The int()
function is also useful if you need to round a floating-point number down.
int(7.7)
7
int(7.7) + 1
8
Although the string value of a number is considered a completely different value from the integer or floating-point version, an integer can be equal to a floating point.
==
to denote comparisonboolean
which can be either True
(1) or False
(0)42 == '42'
False
42 == 42.0
True
42.0 == 0042.000
True
You can compute expressions with a calculator or enter string concatenations with a word processor. You can even do string replication easily by copying and pasting text. But expressions, and their component values—operators, variables, and function calls—are the basic building blocks that make programs. Once you know how to handle these elements, you will be able to instruct Python to operate on large amounts of data for you.
It is good to remember the different types of operators (+
,-
, *
, /
, //
, %
, and **
for math operations, and +
and *
for string operations) and the three data types (integers, floating-point numbers, and strings) introduced in this chapter.
I introduced a few different functions as well. The print() and input() functions handle simple text output (to the screen) and input (from the keyboard). The len() function takes a string and evaluates to an int of the number of characters in the string. The str(), int(), and float() functions will evaluate to the string, integer, or floating-point number form of the value they are passed.
In the next chapter, you’ll learn how to tell Python to make intelligent decisions about what code to run, what code to skip, and what code to repeat based on the values it has. This is known as flow control, and it allows you to write programs that make intelligent decisions.
*
'hello'
-88.8
-
/
+
5
spam
'spam'
Name three data types.
What is an expression made up of? What do all expressions do?
This module introduced assignment statements, like spam = 10
. What is the difference between an expression and a statement?
What does the variable bacon
contain after the following code runs?
bacon = 20
bacon + 1
'spam' + 'spamspam'
'spam' * 3
Why is eggs
a valid variable name while 100
is invalid?
What three functions can be used to get the integer, floating-point number, or string version of a value?
Why does this expression cause an error? How can you fix it?
'I ate ' + 99 + ' burritos.'
Extra credit: Search online for the Python documentation for the len() function. It will be on a web page titled “Built-in Functions.” Skim the list of other functions Python has, look up what the round() function does, and experiment with it in the interactive shell.
https://automatetheboringstuff.com/