Python Syntax Flashcards
Python is a
dynamic programming language
Python is a powerful, flexible programming language you can use in web/Internet development, to write desktop graphical user interfaces (GUIs), create games, and much more. Python is:
- High-level, meaning reading and writing Python is really easy—it looks a lot like regular English!
- Interpreted, meaning you don’t need a compiler to write and run Python! You can write it here at Codecademy or even on your own computer (many are shipped with the Python interpreter built in—we’ll get to the interpreter later in this lesson).
- Object-oriented, meaning it allows users to manipulate data structures called objects in order to build and execute programs. We’ll learn more about objects later.
- Fun to use. Python is named after Monty Python’s Flying Circus, and example code and tutorials often refer to the show and include jokes in order to make learning the language more interesting.
This course assumes no previous knowledge of Python in particular or programming/computer science in general.
One of the most basic concepts in computer programming is the variable
A variable is a word/identifier that hangs onto a single value. For example, let’s say you needed the number 5
for your program, but you’re not going to use it immediately. You can set a variable, say spam
, to grab the value 5
and hang onto it for later use, like this:
spam = 5
Declaring variables in Python is easy; you just write out a name/identifier, like spam
, and use =
to assign it a value, and you’re done
Data Types
In this case, the data type of my_variable
is an integer (a positive or negative whole number). There are three data types in Python that are of interest to us at the moment: integers (int in Python language), floats (fractional numbers written with a decimal point, like 1.970
), and booleans (which can be True
or False
).
Computer programs, in large part, are created to manipulate data. Therefore, it’s important to understand the different types of data (or “datatypes”) that we can incorporate into our programs.
Never use quotation marks ('
or "
) with booleans, and always capitalize the first letter! Python is case-sensitive (it cares about capitalization). We’ll use quotation marks when we get to strings, which we’ll cover in the next unit.
Python and set them to different values, and you’ve learned about three different types of values: integers, floats, and booleans.
You can reassign a variable at any point. If you first set my_int
to 7
but later want to change it to 3
, all you have to do is tell Python my_int = 3
, and it’ll change the value of my_int
for you.
What’s a Statement?
You can think of a Python statement as being similar to a sentence in English: it’s the smallest unit of the language that makes sense by itself
Just like “I,” “like,” and “Spam” aren’t sentences by themselves, but “I like Spam” is, variables and data types aren’t statements in Python, but they are the building blocks that form them.
To continue the sentence analogy, it’s clear that we also need a kind of punctuation to make it obvious where one statement ends and another begins. If you’re familiar with JavaScript, you know that statements end with a semicolon (;
). In Python, statements are separated by whitespace. Just like you can’t toss around semicolons wherever you want in JS, you can’t throw whitespace around in Python.
This may take some getting used to, especially if you’re coming from a programming language where whitespace doesn’t matter.
Whitespace Means Right Space
IndentationError: expected an indented block
You’ll get this error whenever your Python whitespace is out of whack. (If you’ve studied JavaScript, think of improper whitespace as improper use of ;
or {}
.) When your punctuation’s off, your meaning can change entirely:
> The peasant said, “The witch turned me into a newt!”“The peasant,” said the witch, “turned me into a newt!”
See what we mean?
A Matter of Interpretation
In the introduction to this unit, we mentioned that Python is an interpreted language (meaning it runs using an interpreter). In the context of Codecademy, the interpreter is the console/output window in the top right corner of the page.
For now, think of the interpreter as a program that takes the code you write, checks it for syntax errors, and executes the statements in that code, line by line. It works as a go-between for you and the computer and lets you know the result of your instructions to the machine.
Single Line Comments
You may have noticed the instructions in the editor that begin with a #
(pound or hash) symbol.
These lines of code are called comments, and they aren’t read by the interpreter—they don’t affect the code at all. They’re plain English comments written by the programmer to provide instructions or explain how a particular part of the program works.
Since this improves the readability of your code tremendously (and will help you debug programs more quickly, since you’ll be able to tell at a glance what each part of the program is supposed to do), we encourage you to comment on your code whenever its purpose isn’t immediately obvious.
Multi-Line Comments
Sometimes you have to write a really long comment. #
will only work across a single line, and while you could write a multi-line comment and start each line with #
, that can be a pain.””
f you want to write a comment across multiple lines, you can include the whole block in a set of triple quotation marks, like so:
"""I'm a lumberjack and I'm okay I sleep all night and I work all day!"""
Arithmetic Operators
Python’s statements aren’t limited to simple expressions of assignment like spam = 3
; they can also include mathematical expressions using arithmetic operators.
There are six arithmetic operators we’re going to focus on:
- Addition (
+
) - Subtraction (
-
) - Multiplication (
*
) - Division (
/
) - Exponentiation (
**
) - Modulo (
%
)
Syntax
class ClassName(SuperClass): //same as above //use 'super' keyword to get from above
Example
class RaceHorse(Horse): """A faster horse that inherits from Horse""" def movement(self): return "run" def movement_slow(self): super(Horse,self).movement() def \_\_repr\_\_(self): return "%s race horse weighing %f and wild status is %b" (self.color,self.weight,self.wild) >> horse3 = RaceHorse("white",200) >> print horse3.movement_slow() "walk" >> print horse3.movement() "run"
Syntax
class ClassName(object): """This is a class""" class_variable def \_\_init\_\_(self,*args): self.args = args def \_\_repr\_\_(self): return "Something to represent the object as a string" def other_method(self,*args): //do something else
Example
class Horse(object): """Horse represents a Horse""" species = "Equus ferus caballus" def \_\_init\_\_(self,color,weight,wild=False): self.color = color self.weight = weight self.wild = wild def \_\_repr\_\_(self): return "%s horse weighing %f and wild status is %b" (self.color,self.weight,self.wild) def make_sound(self): print("neighhhh") def movement(self): return "walk"
Dictionaries
Dictionaries are Python’s built-in associative data type. A dictionary is made of key-value pairs where each key corresponds to a value. Like sets, dictionaries are unordered. A few notes about keys and values: * The key must be immutable and hashable while the value can be of any type. Common examples of keys are tuples, strings and numbers. * A single dictionary can contain keys of varying types and values of varying types.
Syntax
dict() #creates new empty dictionary {} #creates new empty dictionary
Example
>> my_dict = {} >> content_of_value1 = "abcd" >> content_of_value2 = "wxyz" >> my_dict.update({"key_name1":content_of_value1}) >> my_dict.update({"key_name2":content_of_value2}) >> my_dict {'key_name1':"abcd", 'key_name2':"wxyz"} >> my_dict.get("key_name2") "wxyz"
Syntax
{key1:value1,key2:value2}
Example
>> my_dict = {"key1":[1,2,3],"key2":"I am a string",123:456} >> my_dict["key1"] #[1,2,3] >> my_dict[123] #456 >> my_dict["new key"] = "New value" >> print my_dict {"key2":"I am a string", "new key":"New value", "key1":[1,2,3],123:456}
Syntax
def function_name(parameters): # Some code here
Example
def add_two(a, b): c = a + b return c
# or without the interim assignment to c
def add_two(a, b):
return a + b
~~~
```
Syntax
def function_name(parameters, named_default_parameter=value): # Some code here
Example
def shout(exclamation="Hey!"): print exclamation shout() # Displays "Hey!" shout("Watch Out!") # Displays "Watch Out!"
Function Objects
Python functions are first-class objects, which means that they can be stored in variables and lists and can even be returned by other functions.
Python functions are first-class objects, which means that they can be stored in variables and lists and can even be returned by other functions.
Example
# Returning functions from functions
# A simple function
def say_hello(greeter, greeted):
return “Hello, “ + greeted + “, I’m “ + greeter + “.”
~~~
# We can use it like this: print say_hello("Alice", "Bob") # Displays "Hello, Bob, I'm Alice."
# We can also use it in a function: def produce_greeting_from_alice(greeted): return say_hello("Alice", greeted)
print produce_greeting_from_alice(“Bob”) # Displays “Hello, Bob, I’m Alice.”
# We can also return a function from a function by nesting them: def produce_greeting_from(greeter): def greet(greeted): return say_hello(greeter, greeted) return greet
# Here we create a greeting function for Eve: produce_greeting_from_eve = produce_greeting_from("Eve") # 'produce_greeting_from_eve' is now a function: print produce_greeting_from_eve("Alice") # Displays "Hello, Alice, I'm Eve."
# You can also invoke the function directly if you want: print produce_greeting_from("Bob")("Eve") # Displays "Hello, Eve, I'm Bob."
```
Example
# Storing function objects in variables:
def say_hello(name):
return “Hello, “ + name
~~~
foo = say_hello("Alice") # Now the value of 'foo' is "Hello, Alice"
fun = say_hello # Now the value of 'fun' is a function object we can use like the original function: bar = fun("Bob") # Now the value of 'bar' is "Hello, Bob"
```
Example
# Using functions in a dictionary instead of long if statements: # Let's say we have a variable called 'current_action' and we want stuff to happen based on its value: if current_action == 'PAUSE': pause() elif current_action == 'RESTART': restart() elif current_action == 'RESUME': resume()
# This can get long and complicated if there are many values.
# Instead, we can use a dictionary:
~~~
response_dict = {
‘PAUSE’: pause,
‘RESTART’: restart,
‘RESUME’: resume
}
response_dictcurrent_action # Gets the correct function from response_dict and calls it
~~~