Let’s start with a really simple program. Perhaps the simplest Python program is:
print("Hello, World!");This program just prints "Hello, World!". [1]
Printing goes to "standard output", a place Python uses to communicate with a user (in this case, us, the programmers.)
And if you haven’t done it yet, go to https://code.zipcode.rocks/python/ and make a browser bookmark for yourself. Once that’s done, you can use that Python REPL [2] as a place where you can type in the code from this book and run it to see what each code snippet does.
We run python3 in this book.
Don’t use python version 2. python3 is what the pros use.
We will use print to do a lot in the coming pages.
Here’s your second Python program:
milesPerHour = 55.0
print("Car's Speed: ", milesPerHour)If you typed into your REPL and clicked the "Run" button, you should have seen this as your output:
Car’s Speed: 55
as the program’s output.
Cool, huh? The ability to communicate with you is one of Python’s most fundamental capabilities. And you’ve run two Python programs. Congratulations, you’re a coder. (Well, at least for today you are.)
While you’re not thinking about the long term, or about large Python programs, there is a powerful thing in Python that helps with tracking comments and notes about the code.
In your program, you can write stuff that Python will ignore, it’s just there for you (or readers of your code). We use a 'hash character' to start a comment, and the comment goes to the end of the line. Python will ignore anything on a line after a hash character. "#"
# this is a comment. it might describe something in the code.
print('Hello')
print('World') # this is also a comment.Often, you’ll see something like this in this book.
flourAmount = 3.5;
print(flourAmount); # -> 3.5That comment at the end of the print line is showing what you can expect to see in the output. Here it would be "3.5" printed by itself. Try it in your bookmarked Repl.
We can also add useful stuff to the .log call.
flourAmount = 3.5;
print("We need", flourAmount, "cups of flour."); # -> We need 3.5 cups of flour.See how Python types it all out as a useful phrase? That proves to be very handy in a million-plus (or more) cases.
Comments can be used to explain tricky bits of code, or describe what you should see in output. Comments are your friend.
In Python, there are parts of a program and different parts have different names. Two of the most basic (and fundamental) are statements and expressions.
An expression is something that needs to be computed to find out the answer. Here are a few simple ones.
2 + 2 * 65536
speed > 55.0
regularPrice * (1.0 - salePercentOff)Each of these lines is something we’d like Python to compute for us. That computation is often referred to as "evaluation" or "evaluate the expression" to get to the answer. There are two kinds of expressions in Python, arithmetic expressions and boolean expressions.
Arithmetic expressions are, as their name implies, something that require arithmetic to get the answer. An expression like "5 + 8 - 3" gets evaluated to 10.
Boolean expressions result in either a True or a False value. Example: "maxSpeed > 500.0" - this is either true or false depending on the value of maxSpeed.
A statement is just a line of Python.
# at the Grocery
salesTaxRate = 0.06
totalGroceries = 38.99
salesTax = totalGroceries * salesTaxRate
chargeToCard = totalGroceries + salesTaxAnd this is what a Python program looks like. It’s just a list of statements, one after the other, that get computed from the top down.
Some of the statements have expressions in them (like totalGroceries * salesTaxRate), while some are just simple assignment statements (like totalGroceries = 38.99, where we assign the variable 'totalGroceries' the value 38.99). Don’t panic. These are just some simple examples of Python to give you a feel for it. We’ll go thru each of these kinds of things slowly in sections ahead.
In this book, you may see that the code used in examples is longer than can fit on one line in the code boxes. In Python, we have to add a line "continuation" character. So to be clear, a statement with long variable names is the same as one with a short name, but you may have to add "\" (backslashes) to make Python happy.
k = h * kph - (rest / 60)
kilometersCycled = numberOfHoursPedalled \
* kilometersPerHour \
- (totalMinutesOfRest / 60)When you come across code that goes onto multiple lines, do like Python does, look for the backslash, when you find it, think of the line being spread out.
Very often in Python, we will see a block of statements. It is a list of statements indented the same amount. (Yes, unlike many languages, in Python, white space is important.) It acts like a container to make clear what statements are included in the block.
It is so important that indentation, and making sure you have everything aligned properly, is one of the most important thing to learn about Python when you are a beginner. Many a beginner discovers that the braces { } that other languages use to manage the way code is grouped together are missing from Python. Java, JavaScript, and many other languages use braces to handle how code gets grouped together.
Not Python, that’s why is SO very important to get it right.
if (magePower > 120.0):
maxMagic = 500.0
lifeSpan = 800.0
maxWeapons = magePower / maxPowerPerWeapon
if (maxWeapons < 150):
print('You have too many weapons!')
else:
backpack.load()
# some more code
print(magePower, "is your Mage's Power rating.")See those SPACES (and confusingly, they might be TABs but you cannot tell that by looking at the line). All the indented lines below the IF statement are part of what gets run when the IF is True. Then you also see a nested IF below that, one that has an else statement. But the key thing is to look at the lines of code and notice how they are indented, because that tells what you need to know about how the program works, and what gets done depending on the states of the variables. (Don’t worry, we will be going into all this a lot more carefully later.)
Editing tools that let you work on Python do their best make the indentations are correct, but it is a common problem for beginner Python programmers to think the indentation isn’t important and spend far too much time tracking down silly indentation errors.
So, the wise Python beginner spends a fair amount of time making sure the details are exact on indentation. Making sure code is indented correctly is part of being a Pythonista.
Indentation is rejected as inconsistent if the code mixes tabs and spaces it gets flagged as an error in the code; a TabError is raised in that case.