βββββBeautiful is better than ugly.
ββββExplicit is better than implicit.
ββββSimple is better than complex.
ββββComplex is better than complicated.
ββββFlat is better than nested.
ββββSparse is better than dense.
ββββReadability countsβ¦β
By tradition, we will create our very first Python program:
"Hello World"
In Python, it will look like this:
print("Hello World!")
There's two ways you can do this:
Glitch time!
In your terminal, type python
to enter interactive mode.
Enter the command:
print("Hello World!")
What do you think print
do?
To exit interactive mode, type exit()
Create a file using a text editor (atom, sublime, vim, β¦)
vim helloWorld.py
.py
indicates that the file is a Python file.
Type the code to print "Hello World"
in the file.
To execute the file, run:
python helloWorld.py
In other languages, indentation is for readability. In Python, indentation is necessary.
Python uses indentation to indicate a block of code.
To save us the hassle of switching back and forth from Glitch, we'll use Trinket for the rest of our tutorial to run our code. You can edit live code, try it!
# This is a comment
Take our Hello World
program: notice how only "Hello World!"
is printed, and none of the comments appeared.
Print out your name and a fun fact about yourself π
Include comments to explain your code.
Think of a variable as a container for storing a value.
Create a variable by assigning a value to it (no need to be declared or typed!)
variable = value
Use a single =
sign (not to be confused with the equality operator ==
)
Example:
parking_on_campus = 0
Here, I'm assigning the value 0 to the variable parking_on_campus
.
Common: myVariable or my_variable
NAME
and name
are different)Variables can store:
Easy. Just reassign it to another value!
my_var = 5
my_var = my_var + 3
print(my_variable)
What will this print?
Let's make a RPG game character!
There are various data types in python that variables can store. Unlike other languages (like C or Java) you don't have to declare the variable type. Just simplying assign a variable something (like we have shown before).
Numbers are self-explanatory. What isn't so obvious is that python distinguishes the different types of numbers (e.g. integer vs. decimal numbers).
Integer numbers are called int
Decimal numbers are called float
Let's use ints and floats to make some game variables.
Strings are a series of characters surrounded by either single quotation marks or double quotation marks:
'hello'
is the same as "hello"
.
Strings can output to the screen using print()
:
print("hello world!")
Strings also have some cool built-in features and functions. Let's take a look at some of them:
A list is a collection of elements which is ordered and changeable. It allows duplicate members.
Let's take a closer look at what lists are by using a list as our game inventory.
Dictionary is a collection of objects that store data in key, value pairs.
Let's explore this through our game's shop.
Boolean values are the two constant objects False
and True
. They are used to represent truth values.
Example:
is_learning_python = True
Boolean values are useful for conditional statements and loops (more on that later).
You can do math in Python using arithmetic operators.
Here are some examples of operators, try to guess what the values are. Then uncomment the print statements to check your answers.
Try it yourself! Use variables and operators to update your gold
count.
You can compare two things using comparison operators.
Comparison Operators will return Booleans (True/False).
Try to guess what the values are. Then uncomment the print statements to check your answers.
Logical Operators reads like English!
and
: both are True -> True. Otherwise False
or
: either are True -> True. None is True -> False
not
: opposite
Again, try to guess the values and uncomment the print statements to check.
Scenario:
Suppose I want to drink a health potion, but only if my health is low (<50). How do I do that? π
Decision making is required when we want to execute a code only if a certain condition is satisfied.
In Python, the if statement is used for decision making.
The syntax for a Python if statement is:
if test condition:
code
If test condition
is True, code
will execute.
Pay close attention to the :
and indentation!
Take our scenario from earlier,
Another scenario:
I have two potions, big and small. I will drink the big potion when my health is extrememly low (<10), and I will drink the small potion when my health is low (<50). If my health is not low, I will not drink any.
What happens if I use if statements?
Oh no! I drank both potions π±
This is where elif
and else
comes in.
if test condition 1:
code1
elif test condition 2:
code2
else:
code3
If the test condition 1 is not met, the program will skip code1 and check test condition 2.
If test condition 2 is not met, the program will skip code2 and execute code3 in else
.
You can add as many elif as you need!
Going back to our example, this is what the code will look like:
I encountered a monster. Do I use Range Attack, Melee Attack, or Flee? πΉπ‘πβ
Let's say our character's
weapon = "Sword"
π‘
Every time our character hit an enemy with the sword, we want it to inflict some damage to the enemy.
What would be a good way to represent the damage of the weapon and the health of the enemy? β
If we used variables
enemyHealth = 100
weaponDamage = 5
to represent health and damage respectively, we could represent a successful strike against an enemy as
enemyHealth = enemyHealth - weaponDamage
But if I had to do this again and again, that might get a little frustrating to type over and over, and for more complicated sets of instructions, it also increases the chances that I could make an error.
A great way around this is to use something called a function. Much like math, it take some inputs (parameters) and does things with them.
Similar to the math function
Let's see what a function like this would look like.
In python, we need to explicitly tell python that we are trying to declare a function, and the way to do it is by using the def
keyword.
So a function that subtracts weapon damage from an enemy's health would look something like:
def damageEnemy(weaponDamage, enemyHealth):
This is a function declaration (you declare that damageEnemy
is a function with parameters weaponDamage
and enemyHealth
).
A function can take any number of parameters (interchangably called inputs) with which it can do fun little things.
However, doing these things isn't very useful if we can't do anything with the result. For example,
Similarly, Python functions can also return values! To do this, put return whatIWantToReturn
at the end of the function. So if I were to model
def f(x):
power = x**(2)
return power
So now that you understand, can you make a function that damages an enemy? Try it out!
Now you have a working function⦠or do you? A great way to test if your function works is by⦠literally making it work. So how do we actually get something out of a function? Well, you can just plug in values and assign the return value to another variable. Let's try this.
See, it's that easy! Functions allow you to express more things in less code. A great saying I love is: efficiency is clever laziness, and this is exactly a mindset a good programer should have.
So we managed to be a little lazy, but I'm about to teach you guys how to escalate your laziness to a new level. Let's say your character encountered a boss with 50 health, but your damage is only 10. How would we be able to kill the boss?
One solution would be to call our function 5 times, but is there a lazier way to do it? There is! We can use something called a for-loop which basically executes an instruction many times.
Syntax:
for variable in range(numberOfTimesToLoop):
code
A for-loop can also loop through a list of items:
shop = {"shield": 20,
"sword" : 30,
"bow": 50,
"armor": 100,
"ax": 40 }
inventory = []
for item in shop:
if shop[item] < 50:
inventory.append(item)
print(inventory)
What do you think will be printed?
What if we want to keep attacking until the boss dies?
To keep repeating an operation when you don't know how many times you have to do it (in this case hit the boss) but do know when you would stop (when the boss dies), we use something called a while loop.
Like the name suggests, this kind of loop runs as long as a condition is satisfied.
So to kill this boss, we can write the following piece of code:
Let's maximize our laziness. Let's say you are out in the woods and find a mystery chest full of both awesome and lame items.
mystery_chest = ["shield","sword","bow","armor","ax","50 gold","a single pebble"]
Obviously if it's a mystery chest, we don't know what we're going to get. How can we make sure that we get a random item from the mystery chest? This is where using libraries comes in handy.
A 'library' is essentially a .py
file containing a set of already pre-defined funtions. It is a 'library' of code that you can borrow. The way we can borrow code from the libary is using the import
statement at the top of the file:
import library_name
In order to use a library's funcitons, we call the funtion using the following syntax:
library_name.function_name(parameters)
The random
library is useful for things that rely on creating random sequences (e.g. generating random numbers, shuffling a list). Let's use the random
library to randomize our mystery chest.
Check out the source code for the random
library (Source Code). Imagine if we had to write this code from scratch, our game would take even longer to create!
Before you begin coding any complex function/program, try googling to see if a library already exists for it. Chances are, someone already did the hard work and coded up a library for it with proper documentation.
Congratulations, you made it to the end of the tutorial!
Hope you learned something useful