- BASICS
- Statements
- Operators
-
Functions
- Incremental
- Errors
- FUNCTIONS
- Function Definition
- Recursion
- Objects
- STRINGS
- Immutable
- Raw Strings
- Regex
- Validation
- Config
- Security
- Encrypt
- CLASS
- Definition
- Attributes
- Functional
- Methods
- COLLECTIONS
- Lists
- List Comprehension
- Dictionaries
- Dictionary Efficiency
- Tuples
- References
- Iterable
- STORAGE
- Files
- Databases
- Pipes
- With Open
- Shelve
- Zip
- Csv
- Json
PYTHON PAGES -
LEVEL 1
Definition
""" Specify the name and the sequence of statements.
Later, you can call the function by name.
Split a single instruction on multple lines with backslash.
"""
def f(a):
return a%2
def h(x):
return
print(f(3))
print(h("2"))
print("Hello " + \
"World")
"""
1
None
Hello World
"""
Import
""" To use a function from a module, you have to import it.
When you save your scripts don't use modules names like math, sys, csv.
"""
import math
print( math.pi )
print( math.sin(math.pi/2) )
"""
3.141592653589793
1.0
"""
Local variable
""" A local variable is destroyed after the function is called.
To modify a global variable from within a function, use global statement.
"""
def f(a, b):
c = a + b
return c
n = 0
def h():
global n
# Look Here
for i in range(10):
n = i
return n
print(f(3,4))
print(h())
try:
print(c)
except Exception as e:
print(e)
"""
7
9
name 'c' is not defined
"""
Lambda
""" Lambda (or anonymous) functions
The result of a lambda function is the return value
Less typing (and clearer) to pass a lamda function
"""
def short_function(x):
return x*2
equiv_function = lambda x: x*2
# Example, sort by the number of distinc letters
strings = ['foo', 'card', 'bar', 'aaaa']
strings.sort(key=lambda x: len(set(x)))
print(strings)
# ['aaaa', 'foo', 'bar', 'card']