Python for Beginners
Jennifer Strejevitch - Feb 2017
Introduction to the command line interface
Command line
- Also called command-prompt; terminal; cmd; console; shell
- Like Windows explorer (Windows) or Finder (Mac) without graphic interface
Mac
Windows
Open the command line
Windows
- Start menu → in "Search in programs and files"→ type "cmd" OR
- Start menu → All Programs → Accessories → Command Prompt
Mac
+ space then type "terminal"
Linux
Look through the menu for your window manager for anything named "Shell" or "Terminal."
Let's practice some commands
With your terminal opened, please type:
➜ ~ whoami
command-line
Result
Please observe that in your command line interface there might be a "$" sign or ">". Most examples online will display those signs. You don't need to type them. My terminal displays an arrow for example.
Useful commands
Windows | Mac OS X or Linux | |
---|---|---|
Current directory | cd | pwd |
List files and directories | dir | ls |
Change directory | cd FolderName | cd FolderName |
Create directory | mkdir FolderName | mkdir FolderName |
Close terminal | exit | exit |
open explorer/finder | start . | open . (Mac) |
Learn more commands on:
Windows
http://simplyadvanced.net/blog/cheat-sheet-for-windows-command-prompt/
Mac OS X
https://github.com/0nn0/terminal-mac-cheatsheet
Linux
https://www.cheatography.com/davechild/cheat-sheets/linux-command-line/
Next step:
Code editor
Atom
Sublime Text 3... You can choose!
Code editors have lots of helpers such as highlighting, closing quotes for you. They help you read your code better, spot mistakes and most importantly, they produce plain text as opposed to Word, notepad, etc.
Python prompt
Once you have python installed you should be able to get to the python prompt by simply typing "python" on your console. You should then see some information on the version and a ">>>" sign preceding your cursor. Remember that when you are on the python prompt, everything you type will be interpreted as python code, so the directory commands we showed you early won't work. In order to go back to your normal console, type "exit()" then Enter.
You can practice some python commands directly on your console and see some results instantly.
Examples:
Python file
- If you write your code in the python prompt, it won't get saved
- When writing a lot of code, it's easier to save it in a file
- Python files have a ".py" extension
- Once you create a python file (e.g. hello.py) you can run it
- You run a python file by typing "python filename.py" + Enter (obs: you run it ouside the Python prompt.
You can practice by following
http://opentechschool.github.io/python-beginners/en/getting_started.html#running-python-files
Variables
Variables are
- A name for something
- A place where you store a value (e.g. a number, a function)
- A good practice is to make it clear to other people who will read the code
Examples:
course = "Python for beginners"
students = 40
print("There are " + students + " students in the " + course + " course")
Errors
Can you explain this error?
>>> print "There are ", students, " students in the ", course, " course"
There are
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'students' is not defined
>>>
Errors happen when you've written something wrong, made a logic mistake or something unexpected happened that made the code operate incorrectly. Generally programming languages have a record of expected errors and can display them to help us find where things went wrong (Like above. We forgot to declare the "students" variable).
Python language structure
def encode(input_string):
count = 1
prev = ''
lst = []
for character in input_string:
if character != prev:
entry = (prev, count)
lst.append(entry)
count = 1
prev = character
else:
entry = (character, count)
lst.append(entry)
return lst
Python is whitespace sensitive. Its blocks are defined by their indentation. It's a language requirement. I also makes it easier for other people to read your code.
Block 1
Block 2
Block 3
Block 2
Block 1
Loops
Loops (or iterations) are useful when you need to do something in repetition. One way to do this in Python is through the keyword "for".
for name in "John", "Sam", "Jill":
print("Hello " + name)
Hello John
Hello Sam
Hello Jill
Making it more interesting with lists
fruits = ["apple", "pear", "oranges", "kiwi"]
for fruit in fruits:
print(fruit)
Lists are a container of things that are organised in order from first to last.
- List is one of various Python variable types
- We have seen so far strings and integers
- string is any text we put within single or double quotes (e.g. "this is a string" or 'this is also a string')
- integers are numbers, positive or negative, without any decimal point (e.g. 1, 2, 0, -1)
Functions
They are a piece of code that does a determined thing. They help the code be more understandable and avoid repetition.
print() is a function. It does a single thing which is to output to the console.
You can create your own function by using the keyword def
def morning_greeting():
print("Good morning!")
>>> morning_greeting()
Good morning!
Obs: in order to call a function you need to add () at the end
Functions with parameters
def morning_greeting(name):
print("Good morning " + name + "!")
>>> morning_greeting("Jennifer")
Good morning Jennifer!
Obs: You might already have noticed that the + sign when used with strings, joins them together. It's commonly called "concatenation".
Conditional statements
They allow you to check if something is True or False and take some action based on that
This is possible thanks to the python boolean type. booleans can only hold True or False
>>> 5 > 2
True
>>> 10 < 2
False
Try:
Both operations above returned a boolean value
In order to check if a value is True or False you can use the keywords if and else
direction = -30
if direction > 0 :
turtle.forward(direction)
else:
turtle.left(180)
turtle.forward(-direction)
More examples on http://opentechschool.github.io/python-beginners/en/conditionals.html#examples
Suggested exercise: Write a function that takes the time of the day and prints the appropriate greeting. e.g. "Good morning!", "Good night!"...
Conditional loops
a = 0
while a < 10:
print("The value of the variable a meets the condition since a is " + str(a))
a = a + 1
print("a now is " + str(a))
print("End!")
Output:
The value of the variable a meets the condition since a is 0
a now is 1
The value of the variable a meets the condition since a is 1
a now is 2
The value of the variable a meets the condition since a is 2
a now is 3
The value of the variable a meets the condition since a is 3
a now is 4
The value of the variable a meets the condition since a is 4
a now is 5
The value of the variable a meets the condition since a is 5
a now is 6
The value of the variable a meets the condition since a is 6
a now is 7
The value of the variable a meets the condition since a is 7
a now is 8
The value of the variable a meets the condition since a is 8
a now is 9
The value of the variable a meets the condition since a is 9
a now is 10
End!