Types, Operators, Strings, Comments
-
Attribution
-
Allen Downey / Green Tea Press
-
Introduction to Python
-
What Is It?
“Python is a programming language that lets you work quickly and integrate systems more effectively.”
-
Why Python
Benefit | Resource |
---|---|
Friendly & Easy to Learn | Think Python Ebook |
Thoroughly documented | Python Docs |
Open source | Wiki Entry |
Broad range of applications | Applications |
Fully featured standard library | Python Standard Library Docs |
Thousands of third-party modules | Python Package Index (PyPI) |
-
The Zen Of Python
>>> import this
The Zen of Python, by Tim Peters
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.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
-
Hello, World!
-
Java Hello World
class HelloJava {
public static void main(String[] args) {
System.out.println("Hello Java");
}
}
-
Python Hello World
print("Hello Python")
-
Getting Started
-
How To Run Python Code
- Interactive Mode
- Script Mode
-
Interactive Mode
Manually type and execute code directly in the Python Interpreter.
-
Interactive Mode Demo
-
Script Mode
Execute a script file which contains python code (by convention python files have a .py extention).
-
Script Mode Demo
-
Arithmetic
-
Operations
Operation | Symbol |
---|---|
Addition | + |
Subtraction | - |
Multiplication | * |
Division | / |
Floor Division | // |
Modulo (Remainder) | % |
Exponentiation | ** |
-
Addition
1 + 1
# 2
40 + 2
# 42
-
Subtraction
1 - 1
# 0
43 - 1
# 42
-
Multiplication
7 * 7
# 49
21 * 2
# 42
-
Division
1 / 1
# 1.0
84 / 2
# 42.0
-
Floor Division
The floor division operator, //, divides two numbers and rounds down to an integer.
minutes = 105
hours = minutes // 60
hours
# 1
-
Special Note About Python 2
The division operator, /, performs floor division if both operands are integers, and floating-point division if either operand is a float.
-
Modulo (Remainder)
The modulus operator divides two numbers and returns the remainder.
2 % 2
# 0
3 % 2
# 1
-
Exponentiation
2 ** 2
# 4
3 ** 3
# 27
-
ARITHMETIC OPERATORS DEMO
-
Values & Types
-
Important Terms
- value: One of the basic units of data, like a number or string, that a program manipulates.
- type: A category of values.
-
Types Examples
Type | Value | Description |
---|---|---|
bool | True or False | Boolean |
int | 1 | Integer |
float | 42.0 | Floating-point number |
str | Hello Python | String |
None | Absence of a value |
-
The type Function
Boolean
Given an argument, the type function return the type of an object.
type(True)
# <class 'bool'>
-
The type Function
Integer
type(1)
# <class 'int'>
-
The type Function
Float
type(42.0)
# <class 'float'>
-
The type Function
String
type('Hello, Python!')
# <class 'str'>
type('42.0')
# <class 'str'>
type(str)
# <class 'type'>
-
The type Function
None
type(None)
# <class 'NoneType'>
-
More Information
-
Assignment Statements
-
Important Terms
A variable is a name that refers to a value.
An assignment is statement that assigns a value to a variable.
a = 35
greeting = 'Oi'
pi = 3.1415926535897932
current_player = None
-
type Function Revisited
a = 35
type(a)
# <class 'int'>
greeting = 'Oi'
type(greeting)
# <class 'str'>
pi = 3.1415926535897932
type(pi)
# <class 'float'>
total_sum = None
type(total_sum)
# <class 'NoneType'>
-
Variable Names
- Can be as long as you like.
- Can contain letters and numbers, but can’t begin with a number.
- Can contain uppercase letters but by convention only lowercase letters are used.
- The underscore character can apper in a name. It is often used in names with multiple words.
- Keywords cannot be used as variable names.
-
Keywords
-
ASSIGNMENT STATEMENTS DEMO
-
Expressions And Statements
-
Experssion
An expression is a combination of values, variables, and operators.
A value all by itself is considered an expression, and so is a variable.
42
# 42
a
# 35
a + 42
# 77
-
Statement
A statement is a unit of code that has an effect, like creating a variable or displaying a value.
a = 35
print(a)
-
Order Of Operations
-
- For mathematical operators, Python follows mathematical convention.
- The acronym PEMDAS is a useful way to remember the rules:
- Parentheses
- Exponentiation
- Multiplication and Division
- Addition and Subtraction Operators with the same precedence are evaluated from left to right.
-
String Operations
-
Operator | Operation |
---|---|
+ | String Concatenation |
* | Repetition |
-
Concatenation
'eggs '+ 'and ' + 'ham'
# 'eggs and ham'
'3' + '3'
# '33'
-
Concatenation Continued
When using the + operator where one of the operands is a string, both operands must be a string.
>>> 3 + '3'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
You can convert a numeric value to a string with the built-in function str().
str(3) + '3'
# '33'
-
Repetition
'Spam' * 3
# 'SpamSpamSpam'
-
Repetition Continued
When using the * operator where one of the operands is a string, the other operand must be an integer.
>>> 'Spam' * '3'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'str'
You can convert a string to an integer using the built-in function int().
'Spam' * int('3')
# 'SpamSpamSpam'
-
Comments
-
Options
- Block comments
- Inline comments
- Documentation Strings
-
Block comments
Block comments generally apply to some (or all) code that follows them, and are indented to the same level as that code. Each line of a block comment starts with a # and a single space.
# The airspeed velocity of an unladen swallow measured in meters per second.
# This is assuming average weather conditions.
velocity = 11
-
Inline Comments
An inline comment is a comment on the same line as a statement. Inline comments should be separated by at least two spaces from the statement. They should start with a # and a single space.
migratory = False # African swallows are non-migratory.
-
Documentation Strings
This will become relevant in future sections. Just know it exists.
"""
In order to maintain air-speed velocity,
a swallow needs to beat its wings
forty-three times every second
"""
beats_per_second = 43
-
Relevant Links
PEP 8 Style Guide
PEP 257 Docstring Conventions