Skip to content

Printing

Let’s start with one of the simplest and most-used functions in Python: the print statement.

print()

An empty print statement like this one, with nothing inside the parentheses, will produce only a blank line. In order to get your program to output text, try this:

print("Hello, world!")

or

print('Hi there.')

You can use single or double quotes, as long as you open and close with the same kind. You can also print multiple items by putting commas in between them:

print("Knock, knock!", "Who's there?")

Try your hand at printing:

The text you’ve just printed out is called a string. It is one of many different data types in Python. Strings are mostly used to hold text, but they can be used for other things as well, as you’ll see. If you want to create a long string, you might want to break up your text. You can do that by putting triple quotes around your string and hitting Enter to create line breaks:

print('''Four score and seven years ago our fathers
brought forth on this continent, a new nation,
conceived in Liberty, and dedicated to the
proposition that all men are created equal.''')

(You can use three single quotes or three double quotes.)

 

Comments

Comments are a way of leaving notes to yourself and anyone else who reads your code. Use a hashtag to create a comment:

# this is a comment
print(5*2)      # this is a comment too!

Anything after the hashtag on that line will be ignored when your code runs, but anything before it will function normally.

You can also create a multi-line comment using triple quotes:

"""This is a multi-line comment. I can 
use it to write a nice long note without 
affecting how my code runs."""

Comments can be used for a variety of purposes: describing what a section of code does, outlining a program, leaving a bookmark about a bit of code you want to look back at later, or setting aside a bit of code that you don’t want to delete but aren’t currently using.

Math

Python makes it very easy to do math:

Symbol Operation
+ addition
- subtraction
* multiplication
/ division

(The asterisk for multiplication is SHIFT-8.)

Check out these examples, and try some of your own:

For exponents, use a double asterisk **. For example, 32 is coded as 3**2. For more complex equations, use parentheses to control order of operations: (5+3)/(16-4). Python does division in a couple different ways. Decimal division is what happens when we use a calculator: you might get a whole number, or you might get a decimal. When you use a slash / in Python, you're doing decimal division. There's another kind of division, though: integer division, which always produces a whole number (rounded down), is accomplished with a double slash //. You can also use a percent sign % for remainder. The example above shows that 13÷5 can be thought of as "2.6" or as "2 remainder 3". Try changing the numbers around to see how it works.

 

String Operations

You can also use math operators to modify strings. A plus sign concatenates two strings, squishing them together into one string: 'egg' + 'plant' produces the string 'eggplant'. Multiplication repeats a string the number of times indicated, so 'Echo!' * 5 is 'Echo!Echo!Echo!Echo!Echo!'

Try it here:

Variables

Sometimes you want to save a value instead of just printing it. If you’re going to be using the same value or string more than once, you can save it by assigning it to a variable.

It’s easy to declare a new variable in Python:

name = "Toothless"
age = 7
species = "Night Fury"

name, species, and age are variable names. The first two variables are strings, and the third is an integer. We don’t have to tell Python what kind of variable we’re creating—it automatically determines the type of variable based on the format we give it. So anything in quotes is a string, a number without a decimal is an integer, and a number with a decimal is called a float. We’ll talk about several other data types over the next few days.

When you’re changing the value of a variable, varName += x or varName -= x are useful shortcuts to say “add x to the value of varName” or “subtract x from the value ofvarName“. This shortcut will come in handy in several of the programs we’ll create. (And, by the way, += also works on strings!)

points = 28
#points = points + 6    #the long way
points += 6             #the shortcut

Try creating and using some variables here:

There are a few rules about variable names. Variable names can only use letters, numbers, and underscores _, and they can’t start with numbers. They are also case sensitive, which means that name, Name, and NAME are all different variables.

Because spaces aren’t allowed in variable names, programmers often use a format called camel case to make long variable names more readable. For example:

firstName = "Pippi"
lastName = "Longstocking"
aReallyLongVariableName = 42

 

Python Libraries

One of the features that makes Python so powerful and versatile is its enormous collection of libraries. These are chunks of code written by other programmers to make certain kinds of tasks easier. You can import libraries into your program and use them as shortcuts for complicated tasks.

We’ll be using the random library a few times this week. The random library has functions that give random outputs: picking a number from a set of numbers, flipping a coin, etc.

The randint function used above returns a random number between the numbers given, including both of the end numbers. Try changing around the endpoints to see what happens. If you run the code repeatedly, it will select a new number each time!

Skip to toolbar