Lesson A.1: hello world, variables
Lesson A.2: how old are you?
Lesson A.3: True or False is True
Lesson A.4: random, game - guess my number 1
Lesson A.5: range, list, for loop
Lesson A.6: list, algorithm
Lesson A.7: function
Lesson A.8: game - hangman game
This will be a rough and loose tutorial of the programming language Python 3.
Let's start with an explanation of what Python is.
Now, go ahead and install Python 3.x from somewhere (or you can use the online Python -- Please use Online Python 3).
...
Alright, now that that's over, let's skip over about a million steps and move on to some actual code.
The print operator can be used to make your program output some text.
>>> print('Hello World!')
Hello World!
>>> print('World, Hello!')
World, Hello!
>>> print('Hello' + ' ' + 'World' + '!')
Hello World!
>>> print('The author\'s example for using apostrophes.')
The author's example for using apostrophes.
>>> print('Hello World!') #This is an example of a comment. Only humans can read comments.
Hello World!
Pretty simple, right?
You can assign variables with an equal sign.
>>> x = 2 #assigning an integer value
>>> print(x)
2
>>> x = 2.5 #assigning a float value
>>> print(x)
2.5
>>> x = 2.0 #still assigning a float value
>>> print(x)
2.0
>>> x = 'Hello World!' #assigning a string
>>> print(x)
Hello World!
>>> x = 'Hello'
>>> y = ' World!'
>>> print(x + y)
Hello World!
>>> x = 1
>>> y = 1
>>> print(x + y)
2
Pretty straightforward.
Variable names can be anything, as long as it doesn't bother the computer.
For example, you can't name a variable print, but you can name it urcomputer.
>>> urcomputer = 'orange'
>>> print('Your computer is ' + urcomputer + '.')
Your computer is orange.
We will make simple text games with "print", "variables", "if", and "raw_input."
The input command can be used to take an input from you.
Let's make a Python program file (ex: mycode.py) including the following code:
a = input("What's your name? ")
print("hi, " + a)
You can run the program by typing "python mycode.py".
What's your name? Choco
hi, Choco
Play this Python code:
adj0 = input('Adjective: ')
nat0 = input('Nationality: ')
name0 = input('Name: ')
noun0 = input('Noun: ')
adj1 = input('Adjective: ')
noun1 = input('Noun: ')
print('')
print('Pizza was invented by a ' + adj0 + ' ' + nat0)
print('chef named ' + name0 + '.')
print('')
print('To make a pizza, you need to')
print('take a lump of ' + noun0 + ', and')
print('make a thin, round, ' + adj1 + ' ' + noun1)
This is an example that you can see from your random input. It's fun!
Adjective: pretty
Nationality: Martian
Name: Conan
Noun: salt
Adjective: sweet
Noun: flowers
Pizza was invented by a pretty Martian
chef named Conan.
To make a pizza, you need to
take a lump of salt, and
make a thin, round, sweet flowers
Try this:
a = input("How old are you? ")
if (int(a) > 5):
print("Oh! You are not a baby!")
print("Are you?")
Note: There should be indentation (you can press "space" key 4 times) after the "if" command.
You may see this output:
How old are you? 12
Oh! You are not a baby!
Are you?
Your code can repeat your commands as many times as you want. We will learn Boolean logic and "while" loop.
You can compare two numbers. You can also compare between math expressions. The result will be either "true" or "false".
>>> 1 == 2
False
>>> 2 == (1 + 1)
True
>>> (60 * 24) == 1440
True
>>> 5 < 3
False
>>>
A variable can contain a number and you can compare two variables. The result will be either "true" or "false".
>>> a = (60 * 24)
>>> b = 1440
>>> a == b
True
>>>
Note: The double equals ("==") means that you want to compare two variable to check if they are the same or not. However, the single equal (ex: b = 1440) means that you want to assign the value (1440) to the variable (b).
You can combine "true"-"false" results using "and". The combined result will be true as long as everything is true. You are a good person as long as you do only right things.
>>> True and True
True
>>> True and False
False
>>> False and True
False
>>> False and False
False
>>>
>>>
>>> True and True and True and True
True
>>>
>>>
>>> True and True and True and True and False
False
>>>
You can combine "true"-"false" results using "or". The combined result will be true if one of them is true. You are a good person or a bad person.
>>> True or True
True
>>> True or False
True
>>> False or True
True
>>> False or False
False
>>>
>>>
>>> True or True or True or True
True
>>> False or False or False or False
False
>>> False or False or False or False or True
True
>>>
There is "not" command that reverse the result.
>>> a = True
>>> a
True
>>> not(a)
False
>>>
Play this Python code. It counts up to 10.
1: counter = 0
2:
3: while (counter <= 10):
4: print(counter)
5: counter = counter + 1
Note: I put line numbers in the code. The line 4 and 5 have a empty space before the command. Which means that these two lines (4 and 5) are under the line 3. It is a block structure. You cannot ignore this space in Python language. It helps both the computer and users.
You can see this result.
0
1
2
3
4
5
6
7
8
9
10
>>>
n = 0
counter = 0
while (counter <= 10):
n = n + counter
print(counter, n)
counter = counter + 1
You can see this result.
0 0
1 1
2 3
3 6
4 10
5 15
6 21
7 28
8 36
9 45
10 55
>>>
What is the sum from 1, 2, 3, and up to 5000?
n = 0
counter = 0
while (counter <= 5000):
n = n + counter
print(counter, n)
counter = counter + 1
Try this.
import random
a = random.randint(1,100)
print 'guess a number'
b = input()
print('Is it ', b, '?')
if (a == b):
print('Yes! Correct!')
else:
print('Sorry')
Can you make the code to keep asking forever until your answer is right? (see 'while' command in Lesson 3)
Computer programs are known for their extreme consistency, but sometimes, introducing intentional unpredictability can be useful. Let's say we wanted to pick out a random name from a list of students in a classroom. How would we go about it?
import random
students = [
'David',
'Daniel',
'Jennifer'
]
n = random.randint(0, (len(students)-1))
print(students[n])
A variable can contain a list of numbers:
a = [10, 20, 30]
Or, a list of strings:
fruit = ['apple', 'orange', 'banana']
Try this.
print(range(10))
It shows a list of numbers.
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Try this:
fruit = ['apple', 'orange', 'banana']
for each in fruit:
print(each)
Try this:
for j in range(10):
print(j)
It prints each number in the list.
0
1
2
3
4
5
6
7
8
9
Can you print out numbers if the numbers is greater than 5?
for j in range(10):
if j > 5:
print j
Can you print out numbers smaller than 7 (by changing only the second line)?
for j in range(10):
if (j < 7):
print(j)
Can you print out 1, 2, 3, ..., up to 100?
for j in range(100):
print(j, j + 1)
Can you print out only even numbers (ex: 2, 4, 6, ...)?
a = 0
for j in range(10):
if (j == a + 2):
print(j)
a = j
Another way...
for j in range(10):
if j % 2 == 0:
print j
Another way...
for j in range(10):
print(j*2)
You can make a multiplication table:
for j in range(10):
for k in range(10):
print(j, 'x', k, '=', j*k)
You will see this.
0 x 0 = 0
0 x 1 = 0
0 x 2 = 0
0 x 3 = 0
0 x 4 = 0
0 x 5 = 0
0 x 6 = 0
0 x 7 = 0
0 x 8 = 0
0 x 9 = 0
1 x 0 = 0
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
1 x 4 = 4
(...)
You can select any item in a list:
fruit = ['apple', 'orange', 'banana']
print(fruit)
print(fruit[0])
Or, you can select multiple items in a list:
fruit = ['apple', 'orange', 'banana']
print(fruit[0:2])
a = [23, 44, 1, 233, 44, 55, 66]
# Q1: print out the third item in the list
print(a[2])
# Q2: print out the first item in the list
print(a[0])
# Q3: print out the last item in the list
print(a[-1])
Can you challenge this? LINK
You may use Google to search the answers: ex: "how to sort a list in python"
We don't have to repeat the same code block if we use a function:
def getGrade():
while (1):
in = input('Which grade?')
if ((int(in) >= 1) and (int(in) <= 12)):
return int(in)
print('Hello?')
print('When did you start to learn coding?)
start = getGrade()
print('Which grade are you in now?)
now = getGrade()
print('You have been studied ' + str(now - start + 1) + ' year(s)!')
A function can take multiple inputs:
def smaller(x, y):
if x < y:
return x
else:
return y
a = 54
b = 23
print(smaller(a, b))
Of course, a function can take a list as the input:
def doubleList(x):
y = []
for each in x:
y.append(x * 2)
return y
a = [1, 3, 5, 7]
print(doubleList(a))
Pattern generators:
def triple(x):
return x * x * x
print(triple(3))
Try this:
def f(x):
sum = 0
for i in range(x):
sum += i
return sum
for i in range(10):
print(str(i) + ' --> ' + str(f(i)))
You will see the following result:0 -> 0
1 -> 0
2 -> 1
3 -> 3
4 -> 6
5 -> 10
6 -> 15
7 -> 21
8 -> 28
9 -> 36
Can you make functions that return the following sequences?
1 -> 1
2 -> 1
3 -> 2
4 -> 6
5 -> 24
6 -> 120
7 -> 720
8 -> 5040
9 -> 40320
It's just code steps to solve a problem.
Email to help@c2j.org for questions!