fix(guide): move guide to english directory
This commit is contained in:
committed by
mrugesh mohapatra
parent
3a270cab98
commit
73a97354e1
25
client/src/pages/guide/english/python/abs-function/index.md
Normal file
25
client/src/pages/guide/english/python/abs-function/index.md
Normal file
@ -0,0 +1,25 @@
|
||||
---
|
||||
title: Python Abs Function
|
||||
---
|
||||
`abs()` is a built-in function in Python 3, to compute the absolute value of any number. The absolute value of a number "means only how far a number is from 0" <sup>1</sup> It takes one argument `x`. The argument can even be a <a href='https://docs.python.org/3.0/library/cmath.html' target='_blank' rel='nofollow'>complex number</a>, and in that case its <a href='http://www.mathcentre.ac.uk/resources/sigma%20complex%20number%20leaflets/sigma-complex9-2009-1.pdf' target='_blank' rel='nofollow'>modulus</a> is returned.
|
||||
|
||||
## Argument
|
||||
|
||||
It takes one argument `x` - an integer, or decimal, or a complex number.
|
||||
|
||||
## Return Value
|
||||
|
||||
The return value would be a positive number. Even if complex number is passed, it would return its magnitude, computed as per complex number algebra.
|
||||
|
||||
## Code Sample
|
||||
|
||||
print(abs(3.4)) # prints 3.4
|
||||
print(abs(-6)) # prints 6
|
||||
print(abs(3 + 4j)) # prints 5, because |3 + 4j| = 5
|
||||
|
||||
 <a href='https://repl.it/CL8k/0' target='_blank' rel='nofollow'>Run Code</a>
|
||||
|
||||
<a href='https://docs.python.org/3/library/functions.html#abs' target='_blank' rel='nofollow'>Official Docs</a>
|
||||
|
||||
### Sources
|
||||
1. <a href='https://www.mathsisfun.com/numbers/absolute-value.html' target='_blank'>Math Is Fun. Accessed: October 25, 2017</a>
|
40
client/src/pages/guide/english/python/all-iterable/index.md
Normal file
40
client/src/pages/guide/english/python/all-iterable/index.md
Normal file
@ -0,0 +1,40 @@
|
||||
---
|
||||
title: Python All Iterable
|
||||
---
|
||||
`all()` is a built-in function in Python 3 (and Python 2 since version 2.5), to check if all items of an <a href='https://docs.python.org/3/glossary.html#term-iterable' target='_blank' rel='nofollow'>_iterable_</a> are `True`. It takes one argument, `iterable`.
|
||||
|
||||
## Argument
|
||||
|
||||
### iterable
|
||||
|
||||
The `iterable` argument is the collection whose entries are to be checked. It can be a `list`, `str`, `dict`, `tuple`, etc.
|
||||
|
||||
## Return Value
|
||||
|
||||
The return value is a Boolean. If and only if **all** entries of `iterable` are [truthy](https://guide.freecodecamp.org/python/truth-value-testing), it returns `True`. This function essentially performs a Boolean `AND` operation over all elements.
|
||||
|
||||
If even one of them is not truthy, it returns `False`.
|
||||
|
||||
The `all()` operation is equivalent to (not internally implemented exactly like this)
|
||||
|
||||
def all(iterable):
|
||||
for element in iterable:
|
||||
if not element:
|
||||
return False
|
||||
return True
|
||||
|
||||
## Code Sample
|
||||
|
||||
print(all([])) #=> True # Because an empty iterable has no non-truthy elements
|
||||
print(all([6, 7])) #=> True
|
||||
print(all([6, 7, None])) #=> False # Because it has None
|
||||
print(all([0, 6, 7])) #=> False # Because it has zero
|
||||
print(all([9, 8, [1, 2]])) #=> True
|
||||
print(all([9, 8, []])) #=> False # Because it has []
|
||||
print(all([9, 8, [1, 2, []]])) #=> True
|
||||
print(all([9, 8, {}])) #=> False # Because it has {}
|
||||
print(all([9, 8, {'engine': 'Gcloud'}])) #=> True
|
||||
|
||||
 <a href='https://repl.it/CL9U/0' target='_blank' rel='nofollow'>Run Code</a>
|
||||
|
||||
<a href='https://docs.python.org/3/library/functions.html#all' target='_blank' rel='nofollow'>Official Docs</a>
|
39
client/src/pages/guide/english/python/any-iterable/index.md
Normal file
39
client/src/pages/guide/english/python/any-iterable/index.md
Normal file
@ -0,0 +1,39 @@
|
||||
---
|
||||
title: Python Any Iterable
|
||||
---
|
||||
`any()` is a built-in function in Python 3 (and Python 2 since version 2.5), to check if any of the items of an <a href='https://docs.python.org/3/glossary.html#term-iterable' target='_blank' rel='nofollow'>_iterable_</a> is `True`. It takes one argument, `iterable`.
|
||||
|
||||
## Argument
|
||||
|
||||
### iterable
|
||||
|
||||
The `iterable` argument is the collection whose entries are to be checked. It can typically be a `list`, `str`, `dict`, `tuple` etc., even a `file object`.
|
||||
|
||||
## Return Value
|
||||
|
||||
The return value is a Boolean. If and only if **all** entries of iterable are `False`, or the `iterable` is empty; it returns `False`. This function essentially performs a Boolean `OR` operation over all elements.
|
||||
|
||||
If even one of them is `True`, it returns `True`.
|
||||
|
||||
The `any()` operation is equivalent to (internally, may not be implemented exactly like this)
|
||||
|
||||
def any(iterable):
|
||||
for element in iterable:
|
||||
if element:
|
||||
return True
|
||||
return False
|
||||
|
||||
## Code Sample
|
||||
|
||||
print(any([])) #=> False
|
||||
print(any({})) #=> False
|
||||
print(any([None])) #=> False
|
||||
print(any(['', {}, 0])) #=> False
|
||||
print(any([6, 7])) #=> True
|
||||
print(any([6, 7, None])) #=> True
|
||||
print(any([0, 6, 7])) #=> True
|
||||
print(any([9, 8, [1, 2]])) #=> True
|
||||
|
||||
 <a href='https://repl.it/CL9c/0' target='_blank' rel='nofollow'>Run Code</a>
|
||||
|
||||
<a href='https://docs.python.org/3/library/functions.html#any' target='_blank' rel='nofollow'>Official Docs</a>
|
45
client/src/pages/guide/english/python/args-variable/index.md
Normal file
45
client/src/pages/guide/english/python/args-variable/index.md
Normal file
@ -0,0 +1,45 @@
|
||||
---
|
||||
title: Relationships between * and args
|
||||
---
|
||||
## Presence of * in function definition
|
||||
|
||||
```Python
|
||||
# How does *args work in a function definition
|
||||
|
||||
def hardFunc(arg1, arg2):
|
||||
# create a tuple and pollute it with arguments passed to hardFunc
|
||||
args=(arg1, arg2)
|
||||
# print out results
|
||||
print(args[0])
|
||||
print(args[1])
|
||||
|
||||
hardFunc('hard_one', 'hard_two')
|
||||
# output — Try it yourself now and in sequential snippets!
|
||||
|
||||
def softFunc(*args):
|
||||
# at this point after calling softFunc a tuple with a name of a word
|
||||
# followed by * is created automatically (in this case the name is args)
|
||||
# print out results
|
||||
print(args[0])
|
||||
print(args[1])
|
||||
|
||||
softFunc('soft_one', 'soft_two')
|
||||
|
||||
# Now try to do something illegal
|
||||
hardFunc('one', 'two', 'three')
|
||||
|
||||
# Now do things legally
|
||||
softFunc('one', 'two', 'three')
|
||||
|
||||
# or even
|
||||
softFunc('one', 'two', 'three', 'infinity')
|
||||
|
||||
# softFunc handles arbitrary amount of arguments easily by virtue of * syntax
|
||||
# So using a single variable name in conjuction with * we gained the ability
|
||||
# to invoke a function with arbitrary amount of arguments.
|
||||
|
||||
# Once again when softFunc is called the newly args
|
||||
# tuple filled with provided arguments is created
|
||||
|
||||
# Conclusion softFunc is a more flexible/dynamic verson of a hardFunc
|
||||
```
|
312
client/src/pages/guide/english/python/basic-operators/index.md
Normal file
312
client/src/pages/guide/english/python/basic-operators/index.md
Normal file
@ -0,0 +1,312 @@
|
||||
---
|
||||
title: Basic Operators
|
||||
---
|
||||
## Basic Operators
|
||||
|
||||
Operators are symbols which tells the interpreter to do a specific operation (viz arithmetic, comparison, logical, etc.)
|
||||
|
||||
The different types of operators in Python are listed below:
|
||||
|
||||
1. Arithmetic Operators
|
||||
2. Relational Operators
|
||||
3. Bitwise Operators
|
||||
4. Assignment Operators
|
||||
5. Logical Operators
|
||||
6. Membership Operators
|
||||
7. Identity Operators
|
||||
|
||||
#### Arithmetic Operators
|
||||
|
||||
An arithmetic operator takes two operands as input, performs a calculation and returns the result.
|
||||
|
||||
Consider the expression, <b>“a = 2 + 3”</b>. Here, `2` and `3` are the <i>operands</i> and `+` is the <i>arithmetic operator</i>. The result of the operation is stored in the variable a.
|
||||
|
||||
<table style="width:100%">
|
||||
<tr>
|
||||
<th>Operator</th>
|
||||
<th>Description</th>
|
||||
<th>Usage</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">+</td>
|
||||
<td>Performs Addition on the operands</td>
|
||||
<td>12 + 3 = 15</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">-</td>
|
||||
<td>Performs Subtraction on the operands. <br>Subtracts the right operand from the left operand</td>
|
||||
<td>12 - 3 = 9</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">*</td>
|
||||
<td>Performs Multiplication on the operands</td>
|
||||
<td>12 * 3 = 36</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">/</td>
|
||||
<td>Performs Division on the operands. <br>Divides the left operand by the right operand</td>
|
||||
<td>12 / 3 = 4</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">%</td>
|
||||
<td>Performs a Modulus on the operands. <br>Returns the remainder obtained while dividing the left operand by the right operand</td>
|
||||
<td>16 % 3 = 1</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">**</td>
|
||||
<td>Performs an Exponentiation operation. <br>The left operand is raised to the power of right operand</td>
|
||||
<td>12 ** 3 = 1728</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">//</td>
|
||||
<td>Performs a Floor Division operation. <br>Returns the integral part of the quotient obtained after diving the left operand by the right operand</td>
|
||||
<td>18 // 5 = 3</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
Note: To get the result in floating type, one of the operands must also be of float type.
|
||||
|
||||
#### Relational Operators
|
||||
|
||||
A relational operator is used to compare two operands to decide a relation between them. It returns a boolean value based on the condition.
|
||||
|
||||
<table style="width:100%">
|
||||
<tr>
|
||||
<th>Operator</th>
|
||||
<th>Description</th>
|
||||
<th>Usage</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">></td>
|
||||
<td>Returns True if the left operand is greater than the right operand<br>Returns False otherwise</td>
|
||||
<td>12 > 3 returns True</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center"><</td>
|
||||
<td>Returns True if the right operand is greater than the left operand<br>Returns False otherwise</td>
|
||||
<td>12 < 3 returns False</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">==</td>
|
||||
<td>Returns True if both the operands are equal<br>Returns False otherwise</td>
|
||||
<td>12 == 3 returns False</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">>=</td>
|
||||
<td>Returns True if the left operand is greater than or equal to the right operand<br>Returns False otherwise</td>
|
||||
<td>12 >= 3 returns True</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center"><=</td>
|
||||
<td>Returns True if the right operand is greater than or equal to the left operand<br>Returns False otherwise</td>
|
||||
<td>12 <= 3 returns False</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">!=</td>
|
||||
<td>Returns True if both the operands are not equal<br>Returns False otherwise</td>
|
||||
<td>12 != 3 returns True</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
#### Bitwise Operators
|
||||
|
||||
A bitwise operator performs operations on the operands bit by bit
|
||||
|
||||
Consider a = 2 (in binary notation, 10) and b = 3 (in binary notation, 11) for the below usages
|
||||
|
||||
<table style="width:100%">
|
||||
<tr>
|
||||
<th>Operator</th>
|
||||
<th>Description</th>
|
||||
<th>Usage</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">&</td>
|
||||
<td>Performs bitwise AND operation on the operands</td>
|
||||
<td>a & b = 2<br>Binary: 10 & 11 = 10</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">|</td>
|
||||
<td>Performs bitwise OR operation on the operands</td>
|
||||
<td>a | b = 3<br>Binary: 10 | 11 = 11</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">^</td>
|
||||
<td>Performs bitwise XOR operation on the operands</td>
|
||||
<td>a ^ b = 1<br>Binary: 10 ^ 11 = 01</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">~</td>
|
||||
<td>Performs bitwise NOT operation on the operand<br>Flips every bit in the operand</td>
|
||||
<td>~a = -3<br>Binary: ~(00000010) = (11111101)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">>></td>
|
||||
<td>Performs a bitwise right shift. Shifts the bits of left operand, right by the number of bits specified as the right operand </td>
|
||||
<td>a >> b = 0<br>Binary: 00000010 >> 00000011 = 0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center"><<</td>
|
||||
<td>Performs a bitwise left shift. Shifts the bits of left operand, left by the number of bits specified as the right operand </td>
|
||||
<td>a << b = 16<br>Binary: 00000010 << 00000011 = 00001000</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
|
||||
#### Assignment Operators
|
||||
An assignment operator is used to assign values to a variable. This is usually combined with other operators (like arithmetic, bitwise) where the operation is performed on the operands and the result is assigned to the left operand.
|
||||
|
||||
Consider the following examples,
|
||||
<br>
|
||||
<b>a = 18</b>. Here `=` is an assignment operator, and the result is stored in variable a.
|
||||
<br>
|
||||
<b>a += 10</b>. Here `+=` is an assignment operator, and the result is stored in variable a. This is same as a = a + 10.
|
||||
|
||||
<table style="width:100%">
|
||||
<tr>
|
||||
<th>Operator</th>
|
||||
<th>Usage</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">=</td>
|
||||
<td>a = 5. The value 5 is assigned to the variable a</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">+=</td>
|
||||
<td>a += 5 is equivalent to a = a + 5</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">-=</td>
|
||||
<td>a -= 5 is equivalent to a = a - 5</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">*=</td>
|
||||
<td>a *= 3 is equivalent to a = a * 3</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">/=</td>
|
||||
<td>a /= 3 is equivalent to a = a / 3</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">%=</td>
|
||||
<td>a %= 3 is equivalent to a = a % 3</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">**=</td>
|
||||
<td>a **= 3 is equivalent to a = a ** 3</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">//=</td>
|
||||
<td>a //= 3 is equivalent to a = a // 3</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">&=</td>
|
||||
<td>a &= 3 is equivalent to a = a & 3</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">|=</td>
|
||||
<td>a |= 3 is equivalent to a = a | 3</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">^=</td>
|
||||
<td>a ^= 3 is equivalent to a = a ^ 3</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">>>=</td>
|
||||
<td>a >>= 3 is equivalent to a = a >> 3</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center"><<=</td>
|
||||
<td>a <<= 3 is equivalent to a = a << 3</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
#### Logical Operators
|
||||
|
||||
A logical operator is used to make a decision based on multiple conditions. The logical operators used in Python are
|
||||
`and`, `or` and `not`
|
||||
|
||||
<table style="width:100%">
|
||||
<tr>
|
||||
<th>Operator</th>
|
||||
<th>Description</th>
|
||||
<th>Usage</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">and</td>
|
||||
<td>Returns True if both the operands are True<br>Returns False otherwise</td>
|
||||
<td>a and b</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">or</td>
|
||||
<td>Returns True if any one of the operands are True<br>Returns False otherwise</td>
|
||||
<td>a or b</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">not</td>
|
||||
<td>Returns True if the operand is False<br>Returns False otherwise</td>
|
||||
<td>not a</td>
|
||||
</tr>
|
||||
<tr>
|
||||
</table>
|
||||
|
||||
#### Membership Operators
|
||||
|
||||
A membership operator is used to identify membership in any sequence (lists, strings, tuples).
|
||||
<br>`in` and `not in` are membership operators
|
||||
|
||||
<br>`in` returns True if the specified value is found in the sequence. Returns False otherwise.
|
||||
<br>`not in` returns True if the specified value is not found in the sequence. Returns False otherwise.
|
||||
|
||||
###### Example Usage
|
||||
|
||||
```py
|
||||
a = [1,2,3,4,5]
|
||||
|
||||
#Is 3 in the list a?
|
||||
print 3 in a # prints True
|
||||
|
||||
#Is 12 not in list a?
|
||||
print 12 not in a # prints True
|
||||
|
||||
str = "Hello World"
|
||||
|
||||
#Does the string str contain World?
|
||||
print "World" in str # prints True
|
||||
|
||||
#Does the string str contain world? (note: case sensitive)
|
||||
print "world" in str # prints False
|
||||
|
||||
print "code" not in str # prints True
|
||||
```
|
||||
#### Identity Operators
|
||||
|
||||
An identity operator is used to check if two variables share the same memory location.
|
||||
<br>`is` and `is not` are identity operators
|
||||
|
||||
<br>`is` returns True if the operands refer to the same object. Returns False otherwise.
|
||||
<br>`is not` returns True if the operands do not refer to the same object. Returns False otherwise.
|
||||
|
||||
Please note that two values when equal, need not imply they are identical.
|
||||
|
||||
###### Example Usage
|
||||
|
||||
```py
|
||||
a = 3
|
||||
b = 3
|
||||
c = 4
|
||||
print a is b # prints True
|
||||
print a is not b # prints False
|
||||
print a is not c # prints True
|
||||
|
||||
str1 = "FreeCodeCamp"
|
||||
str2 = "FreeCodeCamp"
|
||||
|
||||
print str1 is str2 # prints True
|
||||
print "Code" is str2 # prints False
|
||||
|
||||
a = [10,20,30]
|
||||
b = [10,20,30]
|
||||
|
||||
print a is b # prints False (since lists are mutable in Python)
|
||||
```
|
30
client/src/pages/guide/english/python/bool-function/index.md
Normal file
30
client/src/pages/guide/english/python/bool-function/index.md
Normal file
@ -0,0 +1,30 @@
|
||||
---
|
||||
title: Python Bool Function
|
||||
---
|
||||
`bool()` is a built-in function in Python 3\. This function returns a Boolean value, i.e. True or False. It takes one argument, `x`.
|
||||
|
||||
## Arguments
|
||||
|
||||
It takes one argument, `x`. `x` is converted using the standard <a href='https://docs.python.org/3/library/stdtypes.html#truth' target='_blank' rel='nofollow'>Truth Testing Procedure</a>.
|
||||
|
||||
## Return Value
|
||||
|
||||
If `x` is false or omitted, this returns `False`; otherwise it returns `True`.
|
||||
|
||||
## Code Sample
|
||||
|
||||
print(bool(4 > 2)) # Returns True as 4 is greater than 2
|
||||
print(bool(4 < 2)) # Returns False as 4 is not less than 2
|
||||
print(bool(4 == 4)) # Returns True as 4 is equal to 4
|
||||
print(bool(4 != 4)) # Returns False as 4 is equal to 4 so inequality doesn't holds
|
||||
print(bool(4)) # Returns True as 4 is a non-zero value
|
||||
print(bool(-4)) # Returns True as -4 is a non-zero value
|
||||
print(bool(0)) # Returns False as it is a zero value
|
||||
print(bool('dskl')) # Returns True as the string is a non-zero value
|
||||
print(bool([1, 2, 3])) # Returns True as the list is a non-zero value
|
||||
print(bool((2,3,4))) # Returns True as tuple is a non-zero value
|
||||
print(bool([])) # Returns False as list is empty and equal to 0 according to truth value testing
|
||||
|
||||
 <a href='https://repl.it/CVCS/2' target='_blank' rel='nofollow'>Run Code</a>
|
||||
|
||||
<a href='https://docs.python.org/3/library/functions.html#bool' target='_blank' rel='nofollow'>Official Docs</a>
|
@ -0,0 +1,47 @@
|
||||
---
|
||||
title: Python Boolean Operations
|
||||
---
|
||||
<a href='https://docs.python.org/3/reference/expressions.html#and' target='_blank' rel='nofollow'>`and`</a>, <a href='https://docs.python.org/3/reference/expressions.html#or' target='_blank' rel='nofollow'>`or`</a>, <a href='https://docs.python.org/3/reference/expressions.html#not' target='_blank' rel='nofollow'>`not`</a>
|
||||
|
||||
<a href='https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not' target='_blank' rel='nofollow'>Python Docs - Boolean Operations</a>
|
||||
|
||||
These are the Boolean operations, ordered by ascending priority:
|
||||
|
||||
Operation | Result | Notes
|
||||
--------- | ------------------------------------ | -----
|
||||
x or y | if x is false, then y, else x | (1)
|
||||
x and y | if x is false, then x, else y | (2)
|
||||
not x | if x is false, then True, else False | (3)
|
||||
|
||||
**Notes:**
|
||||
|
||||
1. This is a short-circuit operator, so it only evaluates the second argument if the first one is False.
|
||||
2. This is a short-circuit operator, so it only evaluates the second argument if the first one is True.
|
||||
3. not has a lower priority than non-Boolean operators, so not a == b is interpreted as not (a == b), and a == not b is a syntax error.
|
||||
|
||||
## Examples:
|
||||
|
||||
### `not`:
|
||||
|
||||
>>> not True
|
||||
False
|
||||
>>> not False
|
||||
True
|
||||
|
||||
### `and`:
|
||||
|
||||
>>> True and False # Short-circuited at first argument.
|
||||
False
|
||||
>>> False and True # Second argument is evaluated.
|
||||
False
|
||||
>>> True and True # Second argument is evaluated.
|
||||
True
|
||||
|
||||
### `or`:
|
||||
|
||||
>>> True or False # Short-circuited at first argument.
|
||||
True
|
||||
>>> False or True # Second argument is evaluated.
|
||||
True
|
||||
>>> False or False # Second argument is evaluated.
|
||||
False
|
@ -0,0 +1,30 @@
|
||||
---
|
||||
title: Python Built in Constants
|
||||
---
|
||||
<a href='https://docs.python.org/3/library/constants.html' target='_blank' rel='nofollow'>Constants</a>
|
||||
|
||||
Three commonly used built-in constants:
|
||||
|
||||
* `True`: The true value of the _bool_ type. Assignments to `True` raise a _SyntaxError_.
|
||||
* `False`: The false value of the _bool_ type. Assignments to `False` raise a _SyntaxError_.
|
||||
* `None` : The sole value of the type _NoneType_. None is frequently used to represent the absence of a value, as when default arguments are not passed to a function. Assignments to `None` raise a _SyntaxError_.
|
||||
|
||||
Other built-in constants:
|
||||
|
||||
* `NotImplemented`: Special value which should be returned by the binary special methods, such as `__eg__()`, `__add__()`, `__rsub__()`, etc.) to indicate that the operation is not implemented with respect to the other type.
|
||||
* `Ellipsis`: Special value used mostly in conjunction with extended slicing syntax for user-defined container data types.
|
||||
* `__debug__`: True if Python was not started with an -o option.
|
||||
|
||||
Constants added by the site module
|
||||
The site module (which is imported automatically during startup, except if the -S command-line option is given) adds several constants to the built-in namespace. They are useful for the interactive interpreter shell and should not be used in programs.
|
||||
|
||||
Objects that when printed, print a message like “Use quit() or Ctrl-D (i.e. EOF) to exit”, and when called, raise SystemExit with the specified exit code:
|
||||
|
||||
* quit(code=None)
|
||||
* exit(code=None)
|
||||
|
||||
Objects that when printed, print a message like “Type license() to see the full license text”, and when called, display the corresponding text in a pager-like fashion (one screen at a time):
|
||||
|
||||
* copyright
|
||||
* license
|
||||
* credits
|
@ -0,0 +1,47 @@
|
||||
---
|
||||
title: Python Calling Functions
|
||||
---
|
||||
A function definition statement does not execute the function. Executing (calling) a function is done by using the name of the function followed by parenthesis enclosing required arguments (if any).
|
||||
|
||||
>>> def say_hello():
|
||||
... print('Hello')
|
||||
...
|
||||
>>> say_hello()
|
||||
Hello
|
||||
|
||||
The execution of a function introduces a new symbol table used for the local variables of the function. More precisely, all variable assignments in a function store the value in the local symbol table; whereas variable references first look in the local symbol table, then in the local symbol tables of enclosing functions, then in the global symbol table, and finally in the table of built-in names. Thus, global variables cannot be directly assigned a value within a function (unless named in a global statement), although they may be referenced.
|
||||
|
||||
>>> a = 1
|
||||
>>> b = 10
|
||||
>>> def fn():
|
||||
... print(a) # local a is not assigned, no enclosing function, global a referenced.
|
||||
... b = 20 # local b is assigned in the local symbol table for the function.
|
||||
... print(b) # local b is referenced.
|
||||
...
|
||||
>>> fn()
|
||||
1
|
||||
20
|
||||
>>> b # global b is not changed by the function call.
|
||||
10
|
||||
|
||||
The actual parameters (arguments) to a function call are introduced in the local symbol table of the called function when it is called; thus, arguments are passed using call by value (where the value is always an object reference, not the value of the object). When a function calls another function, a new local symbol table is created for that call.
|
||||
|
||||
>>> def greet(s):
|
||||
... s = "Hello " + s # s in local symbol table is reassigned.
|
||||
... print(s)
|
||||
...
|
||||
>>> person = "Bob"
|
||||
>>> greet(person)
|
||||
Hello Bob
|
||||
>>> person # person used to call remains bound to original object, 'Bob'.
|
||||
'Bob'
|
||||
|
||||
The arguments used to call a function cannot be reassigned by the function, but arguments that reference mutable objects can have their values changed:
|
||||
|
||||
>>> def fn(arg):
|
||||
... arg.append(1)
|
||||
...
|
||||
>>> a = [1, 2, 3]
|
||||
>>> fn(a)
|
||||
>>> a
|
||||
[1, 2, 3, 1]
|
79
client/src/pages/guide/english/python/class/index.md
Normal file
79
client/src/pages/guide/english/python/class/index.md
Normal file
@ -0,0 +1,79 @@
|
||||
---
|
||||
title: Class
|
||||
---
|
||||
## Class
|
||||
|
||||
Classes provide a means of bundling data and functionality together.
|
||||
Creating a new class creates a new type of object, allowing new instances of that type to be made.
|
||||
Each class instance can have attributes attached to it for maintaining its state.
|
||||
Class instances can also have methods (defined by its class) for modifying its state.
|
||||
|
||||
Compared with other programming languages, Python’s class mechanism adds classes with a minimum of
|
||||
new syntax and semantics. It is a mixture of the class mechanisms found in C++.
|
||||
Python classes provide all the standard features of Object Oriented Programming:
|
||||
the class inheritance mechanism allows multiple base classes,
|
||||
a derived class can override any methods of its base class or classes,
|
||||
and a method can call the method of a base class with the same name.
|
||||
Objects can contain arbitrary amounts and kinds of data.
|
||||
As is true for modules, classes partake of the dynamic nature of Python:
|
||||
they are created at runtime, and can be modified further after creation.
|
||||
|
||||
#### Class Definition Syntax :
|
||||
|
||||
The simplest form of class definition looks like this:
|
||||
|
||||
>>>class ClassName:
|
||||
... <statement-1>
|
||||
... .
|
||||
... .
|
||||
... .
|
||||
... <statement-N>
|
||||
#### Class Objects:
|
||||
|
||||
class objects support two kinds of operations: attribute references and instantiation.
|
||||
|
||||
Attribute references use the standard syntax used for all attribute references in Python: obj.name.
|
||||
Valid attribute names are all the names that were in the class’s namespace when the class object was created.
|
||||
So, if the class definition looked like this:
|
||||
|
||||
class MyClass:
|
||||
"""A simple example class"""
|
||||
i = 12345
|
||||
|
||||
def f(self):
|
||||
return 'hello world'
|
||||
|
||||
then MyClass.i and MyClass.f are valid attribute references, returning an integer and a function object, respectively.
|
||||
Class attributes can also be assigned to, so you can change the value of MyClass.i by assignment. __doc__ is also a valid attribute,
|
||||
returning the docstring belonging to the class: "A simple example class".
|
||||
Class instantiation uses function notation.
|
||||
Just pretend that the class object is a parameterless function that returns a new instance of the class.
|
||||
For example (assuming the above class):
|
||||
|
||||
x = MyClass()
|
||||
|
||||
creates a new instance of the class and assigns this object to the local variable x.
|
||||
|
||||
The instantiation operation (“calling” a class object) creates an empty object.
|
||||
Many classes like to create objects with instances customized to a specific initial state.
|
||||
Therefore a class may define a special method named __init__(), like this:
|
||||
|
||||
def __init__(self):
|
||||
self.data = []
|
||||
|
||||
When a class defines an __init__() method,
|
||||
class instantiation automatically invokes __init__() for the newly-created class instance.
|
||||
So in this example, a new, initialized instance can be obtained by:
|
||||
|
||||
x = MyClass()
|
||||
Of course, the __init__() method may have arguments for greater flexibility.
|
||||
In that case, arguments given to the class instantiation operator are passed on to __init__(). For example,
|
||||
|
||||
>>> class Complex:
|
||||
... def __init__(self, realpart, imagpart):
|
||||
... self.r = realpart
|
||||
... self.i = imagpart
|
||||
...
|
||||
>>> x = Complex(3.0, -4.5)
|
||||
>>> x.r, x.i
|
||||
(3.0, -4.5)
|
@ -0,0 +1,62 @@
|
||||
---
|
||||
title: Python Code Blocks and Indentation
|
||||
---
|
||||
It is generally good practice for you not to mix tabs and spaces when coding in Python. Doing this can possibly cause a ```TabError```, and your program will crash. Be consistent when you code - choose either to indent using tabs or spaces and follow your chosen convention throughout your program.
|
||||
|
||||
#### Code Blocks and Indentation
|
||||
One of the most distinctive features of Python is its use of indentation to mark blocks of code. Consider the if-statement from our simple password-checking program:
|
||||
|
||||
``` python
|
||||
if pwd == 'apple':
|
||||
print('Logging on ...')
|
||||
else:
|
||||
print('Incorrect password.')
|
||||
|
||||
print('All done!')
|
||||
```
|
||||
|
||||
The lines print('Logging on ...') and print('Incorrect password.') are two separate code blocks. These ones happen to be only a single line long, but Python lets you write code blocks consisting of any number of statements.
|
||||
|
||||
To indicate a block of code in Python, you must indent each line of the block by the same amount. The two blocks of code in our example if-statement are both indented four spaces, which is a typical amount of indentation for Python.
|
||||
|
||||
In most other programming languages, indentation is used only to help make the code look pretty. But in Python, it is required for indicating what block of code a statement belongs to. For instance, the final print('All done!') is not indented, and so is not part of the else-block.
|
||||
|
||||
Programmers familiar with other languages often bristle at the thought that indentation matters: Many programmers like the freedom to format their code how they please. However, Python indentation rules are quite simple, and most programmers already use indentation to make their code readable. Python simply takes this idea one step further and gives meaning to the indentation.
|
||||
|
||||
#### If/elif-statements
|
||||
An if/elif-statement is a generalized if-statement with more than one condition. It is used for making complex decisions. For example, suppose an airline has the following “child” ticket rates: Kids 2 years old or younger fly for free, kids older than 2 but younger than 13 pay a discounted child fare, and anyone 13 years or older pays a regular adult fare. The following program determines how much a passenger should pay:
|
||||
|
||||
```python
|
||||
# airfare.py
|
||||
age = int(input('How old are you? '))
|
||||
if age <= 2:
|
||||
print(' free')
|
||||
elif 2 < age < 13:
|
||||
print(' child fare)
|
||||
else:
|
||||
print('adult fare')
|
||||
```
|
||||
|
||||
After Python gets age from the user, it enters the if/elif-statement and checks each condition one after the other in the order they are given. So first it checks if age is less than 2, and if so, it indicates that the flying is free and jumps out of the elif-condition. If age is not less than 2, then it checks the next elif-condition to see if age is between 2 and 13. If so, it prints the appropriate message and jumps out of the if/elif-statement. If neither the if-condition nor the elif-condition is True, then it executes the code in the else-block.
|
||||
|
||||
#### Conditional expressions
|
||||
Python has one more logical operator that some programmers like (and some don’t!). It’s essentially a shorthand notation for if-statements that can be used directly within expressions. Consider this code:
|
||||
|
||||
```python
|
||||
food = input("What's your favorite food? ")
|
||||
reply = 'yuck' if food == 'lamb' else 'yum'
|
||||
```
|
||||
|
||||
The expression on the right-hand side of = in the second line is called a conditional expression, and it evaluates to either 'yuck' or 'yum'. It’s equivalent to the following:
|
||||
|
||||
```python
|
||||
food = input("What's your favorite food? ")
|
||||
if food == 'lamb':
|
||||
reply = 'yuck'
|
||||
else:
|
||||
reply = 'yum'
|
||||
```
|
||||
|
||||
Conditional expressions are usually shorter than the corresponding if/else-statements, although not quite as flexible or easy to read. In general, you should use them when they make your code simpler.
|
||||
|
||||
[Python Documentation - Indentation](https://docs.python.org/3/reference/lexical_analysis.html#indentation)
|
@ -0,0 +1,31 @@
|
||||
---
|
||||
title: Python Commenting Code
|
||||
---
|
||||
Comments are used to annotate, describe, or explain code that is complex or difficult to understand. Python will intentionally ignore comments when it compiles to bytecode by the interpreter. <a href='https://www.python.org/dev/peps/pep-0008/#comments' target='_blank' rel='nofollow'>`PEP 8`</a> has a section dealing with comments.They also increases the readablity of code by adding easy and descriptive language for better understanding.
|
||||
|
||||
**Block** and **inline** comments start with a `#`, followed by a space before the comment:
|
||||
|
||||
# This is a block comment.
|
||||
print('Hello world!') # This is an inline commment.
|
||||
|
||||
Python does not include a formal way to write multiline comments. Each line of a comment spanning multiple lines should start with `#` and a space:
|
||||
|
||||
# This is the first line of a multiline comment.
|
||||
# This is the second line.
|
||||
|
||||
Another type of comment is the **docstring**, documented in <a href='https://www.python.org/dev/peps/pep-0257/' target='_blank' rel='nofollow'>`PEP 257`</a>. Docstrings are a specific type of comment that becomes the `__doc__` attribute.
|
||||
|
||||
For a string literal to be a docstring, it must start and end with `\"\"\"` and be the first statement of the module, function, class, or method definition it is documenting:
|
||||
|
||||
class SomeClass():
|
||||
"""Summary line for SomeClass.
|
||||
|
||||
More elaborate descriptions may require using a
|
||||
a multiline docstring.
|
||||
"""
|
||||
|
||||
def method_a(self):
|
||||
"""Single line summary of method_a."""
|
||||
pass
|
||||
|
||||
String literals that start and end with `"""` that are not docstrings (not the first statement), can be used for multiline strings. They will not become `__doc__` attributes. If they are not assigned to a variable, they will not generate bytecode. There is some discussion about using them as multiline comments found <a href='http://stackoverflow.com/questions/7696924/multiline-comments-in-python' target='_blank' rel='nofollow'>here</a>.
|
88
client/src/pages/guide/english/python/comparisons/index.md
Normal file
88
client/src/pages/guide/english/python/comparisons/index.md
Normal file
@ -0,0 +1,88 @@
|
||||
---
|
||||
title: Python Comparisons
|
||||
---
|
||||
[Python Docs - Comparisons](https://docs.python.org/3/library/stdtypes.html#comparisons)
|
||||
|
||||
There are eight comparison operations in Python. They all have the same priority (which is higher than that of the Boolean operations). Comparisons can be chained arbitrarily; for example, `x < y <= z` is equivalent to `x < y and y <= z`, except that `y` is evaluated only once (but in both cases `z` is not evaluated at all when `x < y` is found to be false).
|
||||
|
||||
This table summarizes the comparison operations:
|
||||
|
||||
Operation | Meaning
|
||||
--------- | -----------------------
|
||||
`<` | strictly less than
|
||||
`<=` | less than or equal to
|
||||
`>` | strictly greater than
|
||||
`>=` | greater than or equal to
|
||||
`==` | equal to
|
||||
`!=` | not equal to
|
||||
`is` | object identity
|
||||
`is not` | negated object identity
|
||||
|
||||
Objects of different types, except different numeric types, never compare equal. Furthermore, some types (for example, function objects) support only a degenerate notion of comparison where any two objects of that type are unequal. The `<`, `<=`, `>` and `>=` operators will raise a `TypeError` exception when comparing a complex number with another built-in numeric type, when the objects are of different types that cannot be compared, or in other cases where there is no defined ordering.
|
||||
|
||||
Non-identical instances of a class normally compare as non-equal unless the class defines the `__eq__()` method.
|
||||
|
||||
Instances of a class cannot be ordered with respect to other instances of the same class, or other types of object, unless the class defines enough of the methods `__lt__()`, `__le__()`, `__gt__()`, and `__ge__()` (in general, `__lt__()` and `__eq__()` are sufficient, if you want the conventional meanings of the comparison operators).
|
||||
|
||||
The behavior of the `is` and `is not` operators cannot be customized; also they can be applied to any two objects and never raise an exception.
|
||||
|
||||
### Equality Comparisons - "is" vs "=="
|
||||
|
||||
In Python, there are two comparison operators which allow us to check to see if two objects are equal. The `is` operator and the `==` operator. However, there is a key difference between them!
|
||||
|
||||
The key difference between 'is' and '==' can be summed up as:
|
||||
* `is` is used to compare <b>identity</b>
|
||||
* `==` is used to compare <b>equality</b>
|
||||
|
||||
## Example
|
||||
First, create a list in Python.
|
||||
|
||||
```python
|
||||
myListA = [1,2,3]
|
||||
```
|
||||
|
||||
Next, create a copy of that list.
|
||||
|
||||
```python
|
||||
myListB = myListA
|
||||
```
|
||||
|
||||
If we use the '==' operator or the 'is' operator, both will result in a <b>True</b> output.
|
||||
|
||||
```python
|
||||
>>> myListA == myListB # both lists contains similar elements
|
||||
True
|
||||
>>> myListB is myListA # myListB contains the same elements
|
||||
True
|
||||
```
|
||||
This is because both myListA and myListB are pointing to the same list variable, which I defined at beginning of my Python program. Both lists are exactly the same, both in identity and in content.
|
||||
|
||||
However, what if I now create a new list?
|
||||
|
||||
```python
|
||||
myListC = [1,2,3]
|
||||
```
|
||||
|
||||
Performing the `==` operator still shows that both lists are the same, in terms of content.
|
||||
|
||||
```python
|
||||
>>> myListA == myListC
|
||||
True
|
||||
```
|
||||
|
||||
However, performing the `is` operator will now produce a `False` output. This is because myListA and myListC are two different variables, despite containing the same data. Even though they look the same, they are <b>different</b>.
|
||||
|
||||
```python
|
||||
>>> myListA is myListC
|
||||
False # both lists have different reference
|
||||
```
|
||||
|
||||
To sum up:
|
||||
* An `is` expression outputs `True` if both variables are pointing to the same reference
|
||||
* An `==` expression outputs `True` if both variables contain the same data
|
||||
|
||||
|
||||
**TODO**
|
||||
|
||||
* Chained comparisons `w < x < y > z`
|
||||
* Equality comparison `is` vs `==`
|
@ -0,0 +1,59 @@
|
||||
---
|
||||
title: Python Complex Numbers
|
||||
---
|
||||
Complex numbers have a real and an imaginary part, each represented by a floating point number.
|
||||
|
||||
The imaginary part of a complex number can be created using an imaginary literal, this results in a complex number with a real part of `0.0`:
|
||||
```python
|
||||
>>> a = 3.5j
|
||||
>>> type(a)
|
||||
<class 'complex'>
|
||||
>>> print(a)
|
||||
3.5j
|
||||
>>> a.real
|
||||
0.0
|
||||
>>> a.imag
|
||||
3.5
|
||||
```
|
||||
|
||||
No literal exists for creating a complex number with non-zero real and imaginary parts. To create a non-zero real part complex number, add an imaginary literal to a floating point number:
|
||||
|
||||
```python
|
||||
>>> a = 1.1 + 3.5j
|
||||
>>> type(a)
|
||||
<class 'complex'>
|
||||
>>> print(a)
|
||||
(1.1+3.5j)
|
||||
>>> a.real
|
||||
1.1
|
||||
>>> a.imag
|
||||
3.5
|
||||
```
|
||||
|
||||
Or use the <a href='https://docs.python.org/3/library/functions.html#complex' target='_blank' rel='nofollow'>complex constructor</a>.
|
||||
|
||||
```python
|
||||
class complex([real[, imag]])
|
||||
```
|
||||
|
||||
The arguments used to call the complex constructor can be of numeric (including `complex`) type for either parameter:
|
||||
|
||||
```python
|
||||
>>> complex(1, 1)
|
||||
(1+1j)
|
||||
>>> complex(1j, 1j)
|
||||
(-1+1j)
|
||||
>>> complex(1.1, 3.5)
|
||||
(1.1+3.5j)
|
||||
>>> complex(1.1)
|
||||
(1.1+0j)
|
||||
>>> complex(0, 3.5)
|
||||
3.5j
|
||||
```
|
||||
|
||||
A `string` can also be used as the argument. No second argument is allowed if a string is used as an argument
|
||||
|
||||
```python
|
||||
>>> complex("1.1+3.5j")
|
||||
(1.1+3.5j)
|
||||
```
|
@ -0,0 +1,6 @@
|
||||
---
|
||||
title: Python Containers
|
||||
---
|
||||
Some objects contain references to other objects; these are called containers. Examples of containers are tuples, lists and dictionaries. The references are part of a container's value. In most cases, when we talk about the value of a container, we imply the values, not the identities of the contained objects; however, when we talk about the mutability of a container, only the identities of the immediately contained objects are implied. So, if an immutable container (like a tuple) contains a reference to a mutable object, its value changes if that mutable object is changed.
|
||||
|
||||
<a href='https://docs.python.org/3/reference/datamodel.html#objects-values-and-types' target='_blank' rel='nofollow'>Python Docs - Object Values & Types</a>
|
@ -0,0 +1,73 @@
|
||||
---
|
||||
title: Converting Integer to String in Python
|
||||
---
|
||||
## Converting Integer to String in Python
|
||||
|
||||
Unlike many other languages out there, Python does not implicitly typecast integers (or floats) to strings when concatenating with strings. Fortunately, Python has a handy built-in function `str()` which will convert the argument passed in to a string format.
|
||||
|
||||
#### The Wrong Way
|
||||
|
||||
Programmers coming from other languages may attempt to do the following string concatenation which produces an error:
|
||||
|
||||
```py
|
||||
age = 18
|
||||
|
||||
string = "Hello, I am " + age + " years old"
|
||||
```
|
||||
<a href='https://repl.it/JyYH/0' target='_blank' rel='nofollow'>Run code on repl.it</a>
|
||||
|
||||
The error that shows up is
|
||||
```
|
||||
Traceback (most recent call last):
|
||||
File "python", line 3, in <module>
|
||||
TypeError: must be str, not int
|
||||
```
|
||||
|
||||
`TypeError: must be str, not int` indicates that the integer must first be converted to a string to be concatenated.
|
||||
|
||||
#### The Correct Way
|
||||
|
||||
Simple concatenation example:
|
||||
|
||||
```py
|
||||
age = 18
|
||||
|
||||
print("Hello, I am " + str(age) + " years old")
|
||||
|
||||
# Output
|
||||
# Hello, I am 18 years old
|
||||
```
|
||||
<a href='https://repl.it/Jz8Q/0' target='_blank' rel='nofollow'>Run code on repl.it</a>
|
||||
|
||||
Print `1 2 3 4 5 6 7 8 9 10` using a single string
|
||||
```py
|
||||
result = ""
|
||||
|
||||
for i in range(1, 11):
|
||||
result += str(i) + " "
|
||||
|
||||
print(result)
|
||||
|
||||
# Output
|
||||
# 1 2 3 4 5 6 7 8 9 10
|
||||
```
|
||||
<a href='https://repl.it/KBLB/0' target='_blank' rel='nofollow'>Run code on repl.it</a>
|
||||
|
||||
#### Line by Line explanation of the above code
|
||||
|
||||
1. First of all a variable 'result' is assigned to an empty string.
|
||||
2. For loop is being used to iterate over a list of numbers.
|
||||
3. This list of numbers is generated using the range function.
|
||||
4. so range(1,11) is going to generate a list of numbers from 1 to 10.
|
||||
5. On each for loop iteration this 'i' variable is going to take up values from 1 to 10.
|
||||
6. On first iteration when the variable i=1,then the variable [result=result+str(i)+"(space character)"],str(i) converts the 'i' which is an integer value to a string value.
|
||||
7. Since i=1, on the first iteration finally result=1.
|
||||
8. And the same process goes on until i=10 and finally after the last iteration result=1 2 3 4 5 6 7 8 9 10.
|
||||
9. Therefore when we finally print the result after the for loop the output on the console is '1 2 3 4 5 6 7 8 9 10'.
|
||||
|
||||
|
||||
#### More Information:
|
||||
<a href='https://docs.python.org/3/library/stdtypes.html#str' target='_blank' rel='nofollow'>Official Python documentation for `str()`</a>
|
||||
|
||||
|
||||
|
@ -0,0 +1,108 @@
|
||||
---
|
||||
title: The Python Dict
|
||||
---
|
||||
|
||||
A Dictionary (a.k.a "dict") in python is a built-in datatype that can be used to store **`key-value`** pairs. This allows you to treat a **`dict`** like it's a *database* to store and organize data.
|
||||
|
||||
The special thing about dictionaries is the way they are implemented. Hash-table-like structure makes it easy to check for
|
||||
existence - which means that we can easily determine if a specific key is present in the dictionary without needing to examine
|
||||
every element. The Python interpreter can just go to the location key and check if the key is there.
|
||||
|
||||
Dictionaries can use almost any arbitrary datatypes, like strings, integers etc, for keys. However, values that are not hashable,
|
||||
that is, values containing lists, dictionaries or other mutable types (that are compared by value rather than by object identity) may not be used as keys. Numeric types used for keys obey the normal rules for numeric comparison: if two numbers compare equal (such as `1` and `1.0`) then they can be used interchangeably to index the same dictionary entry. (Note however, that since computers store floating-point numbers as approximations it is usually unwise to use them as dictionary keys.)
|
||||
|
||||
One most important requirement of a dictionary is that the keys **must** be unique.
|
||||
To create an empty dictionary just use a pair of braces:
|
||||
```python
|
||||
>>> teams = {}
|
||||
>>> type(teams)
|
||||
>>> <class 'dict'>
|
||||
```
|
||||
To create a non-empty dictionary with some initial values, place a comma-seperated list of key-value pairs:
|
||||
```python
|
||||
>>> teams = {'barcelona': 1875, 'chelsea': 1910}
|
||||
>>> teams
|
||||
{'barcelona': 1875, 'chelsea': 1910}
|
||||
```
|
||||
It's easy to add key-value pairs to an existing dictionary:
|
||||
```python
|
||||
>>> teams['santos'] = 1787
|
||||
>>> teams
|
||||
{'chelsea': 1910, 'barcelona': 1875, 'santos': 1787} # Notice the order - Dictionaries are unordered !
|
||||
>>> # extracting value - Just provide the key
|
||||
...
|
||||
>>> teams['barcelona']
|
||||
1875
|
||||
```
|
||||
**`del`** operator is used to delete a key-value pair from the dict. In scenarios where a key that's already in use is again used to store values, the old value associated with that key is completely lost. Also, keep in mind that it's an error to extract the value using an non-existent key.
|
||||
```python
|
||||
>>> del teams['santos']
|
||||
>>> teams
|
||||
{'chelsea': 1910, 'barcelona': 1875}
|
||||
>>> teams['chelsea'] = 2017 # overwriting
|
||||
>>> teams
|
||||
{'chelsea': 2017, 'barcelona': 1875}
|
||||
```
|
||||
**`in`** keyword can be used to check whether a key exist in the dict or not:
|
||||
|
||||
```python
|
||||
>>> 'sanots' in teams
|
||||
False
|
||||
>>> 'barcelona' in teams
|
||||
True
|
||||
>>> 'chelsea' not in teams
|
||||
False
|
||||
```
|
||||
**`keys`** is a built-in *method* that can be used to get the keys of a given dictionary. To extract the keys present in a dict as lists:
|
||||
```python
|
||||
>>> club_names = list(teams.keys())
|
||||
>>> club_names
|
||||
['chelsea', 'barcelona']
|
||||
```
|
||||
Yet another way of creating dictionary is using the **`dict()`** method:
|
||||
```python
|
||||
>>> players = dict( [('messi','argentina'), ('ronaldo','portugal'), ('kaka','brazil')] ) # sequence of key-value pair is passed
|
||||
>>> players
|
||||
{'ronaldo': 'portugal', 'kaka': 'brazil', 'messi': 'argentina'}
|
||||
>>>
|
||||
>>> # If keys are simple strings, it's quite easier to specify pairs using keyword arguments
|
||||
...
|
||||
>>> dict( totti = 38, zidane = 43 )
|
||||
{'zidane': 43, 'totti': 38}
|
||||
```
|
||||
Dict comprehensions can be used as well to create dictionaries from arbitrary key and value expressions:
|
||||
```python
|
||||
>>> {x: x**2 for x in (2, 4, 6)}
|
||||
{2: 4, 4: 16, 6: 36}
|
||||
```
|
||||
|
||||
**Looping in Dictionary**
|
||||
To simply loop over the keys in the dictionary, rather than the keys and values:
|
||||
```python
|
||||
>>> d = {'x': 1, 'y': 2, 'z': 3}
|
||||
>>> for key in d:
|
||||
... print(key) # do something
|
||||
...
|
||||
x
|
||||
y
|
||||
z
|
||||
```
|
||||
To loop over both key and value you can use the following:
|
||||
For Python 2.x:
|
||||
```python
|
||||
>>> for key, item in d.iteritems():
|
||||
... print items
|
||||
...
|
||||
1
|
||||
2
|
||||
3
|
||||
```
|
||||
Use **`items()`** for Python 3.x:
|
||||
```python
|
||||
>>> for key, item in d.items():
|
||||
... print(key, items)
|
||||
...
|
||||
x 1
|
||||
y 2
|
||||
z 3
|
||||
```
|
@ -0,0 +1,108 @@
|
||||
---
|
||||
title: Python Floating Point Numbers
|
||||
---
|
||||
Some general information about floating point numbers and how they work in Python, can be found <a href='https://docs.python.org/3/tutorial/floatingpoint.html' target='_blank' rel='nofollow'>here</a>.
|
||||
|
||||
Nearly all implementations of Python follow the IEEE 754 specification: Standard for Binary Floating-Point Arithmetic. More information found on the <a href='http://grouper.ieee.org/groups/754/' target='_blank' rel='nofollow'>IEEE site</a>.
|
||||
|
||||
Float objects can be created using using <a href='https://docs.python.org/3/reference/lexical_analysis.html#floating-point-literals' target='_blank' rel='nofollow'>floating point literals</a>:
|
||||
|
||||
>>> 3.14
|
||||
3.14
|
||||
>>> 314\. # Trailing zero(s) not required.
|
||||
314.0
|
||||
>>> .314 # Leading zero(s) not required.
|
||||
0.314
|
||||
>>> 3e0
|
||||
3.0
|
||||
>>> 3E0 # 'e' or 'E' can be used.
|
||||
3.0
|
||||
>>> 3e1 # Positive value after e moves the decimal to the right.
|
||||
30.0
|
||||
>>> 3e-1 # Negative value after e moves the decimal to the left.
|
||||
0.3
|
||||
>>> 3.14e+2 # '+' not required but can be used for exponent part.
|
||||
314.0
|
||||
|
||||
Numeric literals do not contain a sign, however creating negative float objects is possible by prefixing with a unary `-` (minus) operator with no space before the literal
|
||||
|
||||
>>> -3.141592653589793
|
||||
-3.141592653589793
|
||||
>>> type(-3.141592653589793)
|
||||
<class 'float'>
|
||||
|
||||
Likewise, positive float objects can be prefixed with a unary `+ (`plus) operator with no space before the literal. Usually `+` is omitted:
|
||||
|
||||
>>> +3.141592653589793
|
||||
3.141592653589793
|
||||
|
||||
Note that leading and trailing zero(s) are valid for floating point literals
|
||||
|
||||
>>> 0.0
|
||||
0.0
|
||||
>>> 00.00
|
||||
0.0
|
||||
>>> 00100.00100
|
||||
100.001
|
||||
>>> 001e0010 # Same as 1e10
|
||||
10000000000.0
|
||||
|
||||
The <a href='https://docs.python.org/3/library/functions.html#float' target='_blank' rel='nofollow'>`float` constructor</a> is another way to create `float` objects.
|
||||
|
||||
Creating `float` objects with floating point literals is preferred when possible:
|
||||
|
||||
>>> a = 3.14 # Prefer floating point literal when possible.
|
||||
>>> type(a)
|
||||
<class 'float'>
|
||||
>>> b = int(3.14) # Works but unnecessary.
|
||||
>>> type(b)
|
||||
<class 'float'>
|
||||
|
||||
However, the float constructor allows for creating float objects from other number types:
|
||||
|
||||
>>> a = 4
|
||||
>>> type(a)
|
||||
<class 'int'>
|
||||
>>> print(a)
|
||||
4
|
||||
>>> b = float(4)
|
||||
>>> type(b)
|
||||
<class 'float'>
|
||||
>>> print(b)
|
||||
4.0
|
||||
>>> float(400000000000000000000000000000000)
|
||||
4e+32
|
||||
>>> float(.00000000000000000000000000000004)
|
||||
4e-32
|
||||
>>> float(True)
|
||||
1.0
|
||||
>>> float(False)
|
||||
0.0
|
||||
|
||||
The `float` constructor will also make `float` objects from strings that represent number literals:
|
||||
|
||||
>>> float('1')
|
||||
1.0
|
||||
>>> float('.1')
|
||||
0.1
|
||||
>>> float('3.')
|
||||
3.0
|
||||
>>> float('1e-3')
|
||||
0.001
|
||||
>>> float('3.14')
|
||||
3.14
|
||||
>>> float('-.15e-2')
|
||||
-0.0015
|
||||
|
||||
The `float` constructor can also be used to make numeric representation of `NaN` (Not a Number), negative `infinity` and `infinity` (note strings for these are case insensitive):
|
||||
|
||||
>>> float('nan')
|
||||
nan
|
||||
>>> float('inf')
|
||||
inf
|
||||
>>> float('-inf')
|
||||
-inf
|
||||
>>> float('infinity')
|
||||
inf
|
||||
>>> float('-infinity')
|
||||
-inf
|
@ -0,0 +1,15 @@
|
||||
---
|
||||
title: The Python Data Structures
|
||||
---
|
||||
A data structure is a particular way of organizing data in a computer so that it can be used efficiently. Python comes with a robust set of inbuilt data structures. Some of the most commonly used ones are :-
|
||||
* Lists
|
||||
* Tuples
|
||||
* Dictionaries
|
||||
|
||||
Majorly, the data structures can be divided into two categories :-
|
||||
* Mutable :- A mutable data structure is a structure whose state can be modified after it is created. Python Lists and Dictionaries are mutable.
|
||||
* Immutable :- An immutable data structure can't be modified. Example :- Once a tuple is created, we can't update the values inside it.
|
||||
|
||||
## Reference:
|
||||
|
||||
[Python Data Structures](https://docs.python.org/3.7/tutorial/datastructures.html)
|
@ -0,0 +1,147 @@
|
||||
---
|
||||
title: Python Integers
|
||||
---
|
||||
The theoretical domain for integers in python is negative infinity to infinity. In practice, integer values are limited by the amount of available memory.
|
||||
|
||||
In Python 2, there was a distinction between **`int`**, numbers that fit in a 32 or 64 bit _C long_, and **`long`**, numbers limited by available memory. Python 3 unified the two types into just **`int`**, more info in <a href='https://www.python.org/dev/peps/pep-0237/' target='_blank' rel='nofollow'>PEP 237</a>.
|
||||
|
||||
**`int` creation using integer literals**
|
||||
|
||||
<a href='https://docs.python.org/3/reference/lexical_analysis.html#integer-literals' target='_blank' rel='nofollow'>Integer Literals</a>
|
||||
|
||||
_Integer objects_ can be created using using integer literals. Unadorned numbers without decimals are integer literals:
|
||||
|
||||
>>> 1234567890 # Unadorned numbers are integer literals
|
||||
1234567890
|
||||
>>> type(1234567890)
|
||||
<class 'int'>
|
||||
|
||||
Numeric literals do not contain a sign, however creating negative _integer objects_ is possible by prefixing with a unary `-` (minus) operator with no space before the literal:
|
||||
|
||||
>>> -1234567890
|
||||
-1234567890
|
||||
>>> type(-1234567890)
|
||||
<class 'int'>
|
||||
|
||||
Likewise, positive integer objects can be created by prefixing a unary `+` (plus) operator with no space before the digits. Usually `+` is ommited:
|
||||
|
||||
>>> +1234
|
||||
1234
|
||||
|
||||
Binary (base 2, prefix: `0b` or `0B`), octal (base 8, prefix: `0o` or `0O`), and hexadecimal (base 16, prefix: `0x` or `0X`) integers can also be created using integer literals:
|
||||
|
||||
>>> 0b1, 0b10, 0b11
|
||||
(1, 2, 3)
|
||||
>>> 0o1, 0o10, 0o11
|
||||
(1, 8, 9)
|
||||
>>> 0x1, 0x10, 0x11
|
||||
(1, 16, 17)
|
||||
|
||||
Note that leading 0's for non-zero integer literals are **not allowed**:
|
||||
|
||||
>>> 0 # Zero by itself is okay.
|
||||
0
|
||||
>>> 01 # Leading zero(s) cause SyntaxError.
|
||||
File "<stdin>", line 1
|
||||
01
|
||||
^
|
||||
SyntaxError: invalid token
|
||||
|
||||
The `int` <a href='https://docs.python.org/3/library/functions.html#int' target='_blank' rel='nofollow'>constructor</a> is another way to create _integer objects_.
|
||||
|
||||
class int(x=0)
|
||||
class int(x, base=10)
|
||||
|
||||
Creating _integer objects_ with integer literals is preferred when possible:
|
||||
|
||||
>>> a = 1 # Prefer integer literal when possible.
|
||||
>>> type(a)
|
||||
<class 'int'>
|
||||
>>> b = int(1) # Works but unnecessary.
|
||||
>>> type(b)
|
||||
<class 'int'>
|
||||
|
||||
However, the constructor allows for creating _integer objects_ from other number types:
|
||||
|
||||
>>> a = 1.123
|
||||
>>> type(a)
|
||||
<class 'float'>
|
||||
>>> print(a)
|
||||
1.123
|
||||
>>> b = int(1.123)
|
||||
>>> type(b)
|
||||
<class 'int'>
|
||||
>>> print(b)
|
||||
1
|
||||
|
||||
Using the `int` constructor for floating point numbers will truncate the number towards zero:
|
||||
|
||||
>>> int(-1.23)
|
||||
-1
|
||||
>>> int(1.23)
|
||||
1
|
||||
|
||||
The built-in `boolean` constants are instances of the `bool` class, and are subclasses of the `int` class, making them a kind of numeric type:
|
||||
|
||||
>>> type(True)
|
||||
<class 'bool'>
|
||||
>>> issubclass(bool, int)
|
||||
True
|
||||
|
||||
If that doesn't make sense to you, don't worry. For now just remember that calling the int constructor with `boolean` objects will return _integer objects_:
|
||||
|
||||
>>> int(True)
|
||||
1
|
||||
>>> int(False)
|
||||
0
|
||||
|
||||
The `int` constructor will also make _integer objects_ from strings:
|
||||
|
||||
>>> a = "10"
|
||||
>>> type(a)
|
||||
<class 'str'>
|
||||
>>> b = int("10")
|
||||
>>> type(b)
|
||||
<class 'int'>
|
||||
|
||||
_Strings_ for the `int` constructor must represent an integer literal:
|
||||
|
||||
The second parameter of the `int` constructor is to specify a base (default: 10). Valid bases are 0 and 2-36.
|
||||
|
||||
If an explicit base is provided the first argument must be a string.
|
||||
|
||||
>>> int("111", 2)
|
||||
7
|
||||
>>> int(111, 2)
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
TypeError: int() can't convert non-string with explicit base
|
||||
|
||||
The string used for the `int` constructor with an explicit base must be a valid integer literal for that base:
|
||||
|
||||
>>> int('11', 2)
|
||||
3
|
||||
>>> int('12', 2)
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
ValueError: invalid literal for int() with base 2: '12'
|
||||
|
||||
Both prefixed and non-prefixed strings of integer literals can be used, however, if used, the prefix must match the provided base.
|
||||
|
||||
>>> int('1101', 2)
|
||||
13
|
||||
>>> int('0b1101', 2)
|
||||
13
|
||||
>>> int('0x1101', 2)
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
ValueError: invalid literal for int() with base 2: '0x1101'
|
||||
|
||||
If a prefixed string and base 0 is used, the created integer object will use the base specified by the prefix. If no prefix is used, then the base is assumed 10
|
||||
|
||||
>>> int('100', 0)
|
||||
100
|
||||
>>> int('0b100', 0)
|
||||
4
|
||||
>>> int('0o100', 0)
|
||||
64
|
@ -0,0 +1,115 @@
|
||||
---
|
||||
title: The Python Objects
|
||||
---
|
||||
> In Python, everything is an _object_.
|
||||
|
||||
_Objects_ represent a logical grouping of attributes. Attributes are data and/or functions. When an object is created in Python it is created with an _identity_, _type_, and _value_.
|
||||
|
||||
In other languages, _primitives_ are _values_ that have no _properties_ (attributes). For example, in javascript `undefined`, `null`, `boolean`, `string`, `number`, and `symbol` (new in ECMAScript 2015) are primitives.
|
||||
|
||||
In Python, there are no primitives. `None`, _booleans_, _strings_, _numbers_, and even _functions_ are all _objects_ regardless how they are created.
|
||||
|
||||
We can demonstrate this using some built-in functions:
|
||||
|
||||
* <a href='https://docs.python.org/3/library/functions.html#id' target='_blank' rel='nofollow'>`id`</a>
|
||||
* <a href='https://docs.python.org/3/library/functions.html#type' target='_blank' rel='nofollow'>`type`</a>
|
||||
* <a href='https://docs.python.org/3/library/functions.html#dir' target='_blank' rel='nofollow'>`dir`</a>
|
||||
* <a href='https://docs.python.org/3/library/functions.html#issubclass' target='_blank' rel='nofollow'>`issubclass`</a>
|
||||
|
||||
Built-in constants `None`, `True`, and `False` are _objects_:
|
||||
|
||||
We test the `None` object here.
|
||||
|
||||
```python
|
||||
>>> id(None)
|
||||
4550218168
|
||||
>>> type(None)
|
||||
<class 'NoneType'>
|
||||
>>> dir(None)
|
||||
[__bool__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
|
||||
>>> issubclass(type(None), object)
|
||||
True
|
||||
```
|
||||
|
||||
Next, let's inspect `True`.
|
||||
|
||||
```python
|
||||
>>> id(True)
|
||||
4550117616
|
||||
>>> type(True)
|
||||
<class 'bool'>
|
||||
>>> dir(True)
|
||||
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
|
||||
>>> issubclass(type(True), object)
|
||||
True
|
||||
```
|
||||
|
||||
No reason to leave out `False`!
|
||||
|
||||
```python
|
||||
>>> id(False)
|
||||
4550117584
|
||||
>>> type(False)
|
||||
<class 'bool'>
|
||||
>>> dir(False)
|
||||
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
|
||||
>>> issubclass(type(False), object)
|
||||
True
|
||||
```
|
||||
|
||||
_Strings_, even when created by a string literals, are also _objects_.
|
||||
|
||||
```python
|
||||
>>> id("Hello campers!")
|
||||
4570186864
|
||||
>>> type('Hello campers!')
|
||||
<class 'str'>
|
||||
>>> dir("Hello campers!")
|
||||
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
|
||||
>>> issubclass(type('Hello campers!'), object)
|
||||
True
|
||||
```
|
||||
|
||||
Same with _numbers_
|
||||
|
||||
```python
|
||||
>>> id(42)
|
||||
4550495728
|
||||
>>> type(42)
|
||||
<class 'int'>
|
||||
>>> dir(42)
|
||||
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
|
||||
>>> issubclass(type(42), object)
|
||||
True
|
||||
```
|
||||
|
||||
## Functions are Objects Too
|
||||
|
||||
> In Python, functions are first class objects.
|
||||
|
||||
_Functions_ in Python are also _objects_, created with an _identity_, _type_, and _value_. They too can be passed into other _functions_:
|
||||
|
||||
```python
|
||||
>>> id(dir)
|
||||
4568035688
|
||||
>>> type(dir)
|
||||
<class 'builtin_function_or_method'>
|
||||
>>> dir(dir)
|
||||
['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__text_signature__']
|
||||
>>> issubclass(type(dir), object)
|
||||
True
|
||||
```
|
||||
|
||||
It is also possible to bind functions to a name and called the bound function using that name:
|
||||
|
||||
```python
|
||||
>>> a = dir
|
||||
>>> print(a)
|
||||
<built-in function dir>
|
||||
>>> a(a)
|
||||
['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__text_signature__']
|
||||
```
|
||||
|
||||
Resources:
|
||||
|
||||
* <a href='https://www.jeffknupp.com/blog/2014/06/18/improve-your-python-python-classes-and-object-oriented-programming/' target='_blank' rel='nofollow'>Click Here</a> to learn more.
|
@ -0,0 +1,85 @@
|
||||
---
|
||||
title: The Python Range
|
||||
---
|
||||
## Python Ranges
|
||||
|
||||
Rather than being a function, a range is actually an <a href='https://docs.python.org/3/library/stdtypes.html#immutable-sequence-types' target='_blank' rel='nofollow'>immutable sequence type</a> and is commonly used for looping a specific number of times in for loops.
|
||||
|
||||
**Creation:**
|
||||
|
||||
`ranges` are created using the `range` constructor. The parameters for the constructor are:
|
||||
|
||||
* `start`: Inclusive first value of the range (optional integer, defaults to 0).
|
||||
* `stop` : Exclusive stop value, range stops when this value or greater would be provided (required integer).
|
||||
* `step` : The amount added to the current value to get the next value (optional integer, defaults to 1).
|
||||
|
||||
```python
|
||||
>>> range(10) # Only the stop parameter is required.
|
||||
range(0, 10)
|
||||
>>> range(0, 10) # Default for start parameter is 0.
|
||||
range(0, 10)
|
||||
>>> range(0, 10, 1) # Default for step is 1\. Start parameter is required if
|
||||
step is needed.
|
||||
range(0, 10)
|
||||
```
|
||||
|
||||
**Examples:**
|
||||
|
||||
Since `ranges` are iterables they can be passed into the `list` and `tuple` constructors to create those types of sequences. Using this fact, we can visualize some examples:
|
||||
|
||||
```python
|
||||
>>> list(range(10)) # range as argument for list constructor.
|
||||
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
|
||||
>>> tuple(range(10)) # range as argument for tuple constructor.
|
||||
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
|
||||
```
|
||||
|
||||
Zero length `ranges`:
|
||||
|
||||
```python
|
||||
>>> list(range(10, 0)) # start greater than stop with postive step.
|
||||
[]
|
||||
>>> list(range(10, 10)) # start equal to stop with postive step.
|
||||
[]
|
||||
>>> list(range(10, 10, -1)) # start equal to stop with negative step.
|
||||
[]
|
||||
>>> list(range(0, 10, -1)) # start less than stop with negative step.
|
||||
[]
|
||||
```
|
||||
|
||||
`ranges` with step arguments:
|
||||
|
||||
```python
|
||||
>>> list(range(0, 10, 2)) # next value would be 10, stops at 8.
|
||||
[0, 2, 4, 6, 8]
|
||||
>>> list(range(0, 10, 3)) # next value would be 12, stops at 9.
|
||||
[0, 3, 6, 9]
|
||||
>>> list(range(0, 10, 4)) # next value would be 12, stops at 8.
|
||||
[0, 4, 8]
|
||||
>>> list(range(10, 0, -1)) # negative step makes decreasing ranges.
|
||||
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
|
||||
>>> list(range(-5, -30, -3)) # negative integers are valid arguments.
|
||||
[-5, -8, -11, -14, -17, -20, -23, -26, -29]
|
||||
```
|
||||
|
||||
**Benefits:**
|
||||
|
||||
The benefit of using `range` is that regardless of how large of a range specified, only a small amount of memory is needed to store the `range`, the values for start, stop, and step. The individual values of the `ranges` are calculated upon iteration.
|
||||
|
||||
```python
|
||||
>>> import sys
|
||||
>>> a_range = range(1000000)
|
||||
>>> a_list = list(a_range)
|
||||
>>> a_tuple = tuple(a_range)
|
||||
>>> sys.getsizeof(a_range)
|
||||
48
|
||||
>>> sys.getsizeof(a_list)
|
||||
9000112
|
||||
>>> sys.getsizeof(a_tuple)
|
||||
8000048
|
||||
```
|
||||
|
||||
### More Inforamtion:
|
||||
<a href='https://docs.python.org/3/library/stdtypes.html#ranges' target='_blank' rel='nofollow'>Python Doc - Ranges</a>
|
||||
|
||||
**TODO: Methods `ranges` do and do not implement**
|
@ -0,0 +1,12 @@
|
||||
---
|
||||
title: The Python Scopes
|
||||
---
|
||||
**TODO: NOTE**
|
||||
|
||||
* This belongs near the code block and indentation information.
|
||||
* This is also related to variables since name finding and binding is related to scopes.
|
||||
|
||||
**TODO: CONTENT**
|
||||
|
||||
* `global`
|
||||
* `nonlocal`
|
@ -0,0 +1,26 @@
|
||||
---
|
||||
title: The Python Strings
|
||||
---
|
||||
Python allows `str` objects, or _strings_, to be expressed in a few different ways:
|
||||
|
||||
* Single quotes: `'Single quote strings can have "double" quotes inside.'`
|
||||
* Double quotes: `"Double quote strings can have 'single' quotes inside."`
|
||||
* Triple quoted:
|
||||
|
||||
"""Triple quoted strings can span multiple lines.
|
||||
Unescaped "double" and 'single' quotes in triple quoted strings are retained."""
|
||||
|
||||
'''Triple quoted strings can be 'single'or "double" quotes.
|
||||
Unescaped newlines are also retained.'''
|
||||
* Immutable: You cannot directly edit/change a Python string after you have created it. For example, if you try to directly reassign/change the first letter in a string, an error is thrown.
|
||||
|
||||
>>> foo = "my string"
|
||||
>>> foo[0] = "a"
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
TypeError: 'str' object does not support item assignment
|
||||
|
||||
|
||||
## Reference:
|
||||
|
||||
<a href='https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str' target='_blank' rel='nofollow'>Text Sequence Type _str_</a>
|
@ -0,0 +1,170 @@
|
||||
---
|
||||
title: The Tuples
|
||||
---
|
||||
## The Tuples
|
||||
|
||||
A tuple is a sequence of Python objects. Tuples are immutable which means they cannot be modified after creation, unlike lists.
|
||||
|
||||
**Creation:**
|
||||
|
||||
An empty `tuple` is created using a pair of round brackets, `()`:
|
||||
```shell
|
||||
>>> empty_tuple = ()
|
||||
>>> print(empty_tuple)
|
||||
()
|
||||
>>> type(empty_tuple)
|
||||
<class 'tuple'>
|
||||
>>> len(empty_tuple)
|
||||
0
|
||||
```
|
||||
A `tuple` with elements is created by separating the elements with commas (surrounding round brackets, `()`, are optional with exceptions):
|
||||
```shell
|
||||
>>> tuple_1 = 1, 2, 3 # Create tuple without round brackets.
|
||||
>>> print(tuple_1)
|
||||
(1, 2, 3)
|
||||
>>> type(tuple_1)
|
||||
<class 'tuple'>
|
||||
>>> len(tuple_1)
|
||||
3
|
||||
>>> tuple_2 = (1, 2, 3) # Create tuple with round brackets.
|
||||
>>> print(tuple_2)
|
||||
(1, 2, 3)
|
||||
>>> tuple_3 = 1, 2, 3, # Trailing comma is optional.
|
||||
>>> print(tuple_3)
|
||||
(1, 2, 3)
|
||||
>>> tuple_4 = (1, 2, 3,) # Trailing comma in round brackets is also optional.
|
||||
>>> print(tuple_4)
|
||||
(1, 2, 3)
|
||||
```
|
||||
A `tuple` with a single element must have the trailing comma (with or without round brackets):
|
||||
```shell
|
||||
>>> not_tuple = (2) # No trailing comma makes this not a tuple.
|
||||
>>> print(not_tuple)
|
||||
2
|
||||
>>> type(not_tuple)
|
||||
<class 'int'>
|
||||
>>> a_tuple = (2,) # Single element tuple. Requires trailing comma.
|
||||
>>> print(a_tuple)
|
||||
(2,)
|
||||
>>> type(a_tuple)
|
||||
<class 'tuple'>
|
||||
>>> len(a_tuple)
|
||||
1
|
||||
>>> also_tuple = 2, # Round brackets omitted. Requires trailing comma.
|
||||
>>> print(also_tuple)
|
||||
(2,)
|
||||
>>> type(also_tuple)
|
||||
<class 'tuple'>
|
||||
```
|
||||
Round brackets are required in cases of ambiguity (if the tuple is part of a larger expression):
|
||||
|
||||
> Note that it is actually the comma which makes a tuple, not the parentheses. The parentheses are optional, except in the empty tuple case, or when they are needed to avoid syntactic ambiguity. For example, `f(a, b, c)` is a function call with three arguments, while `f((a, b, c))` is a function call with a 3-tuple as the sole argument.
|
||||
```shell
|
||||
>>> print(1,2,3,4,) # Calls print with 4 arguments: 1, 2, 3, and 4
|
||||
1 2 3 4
|
||||
>>> print((1,2,3,4,)) # Calls print with 1 argument: (1, 2, 3, 4,)
|
||||
(1, 2, 3, 4)
|
||||
>>> 1, 2, 3 == (1, 2, 3) # Equivalent to 1, 2, (3 == (1, 2, 3))
|
||||
(1, 2, False)
|
||||
>>> (1, 2, 3) == (1, 2, 3) # Use surrounding round brackets when ambiguous.
|
||||
True
|
||||
```
|
||||
A `tuple` can also be created with the `tuple` constructor:
|
||||
```shell
|
||||
>>> empty_tuple = tuple()
|
||||
>>> print(empty_tuple)
|
||||
()
|
||||
>>> tuple_from_list = tuple([1,2,3,4])
|
||||
>>> print(tuple_from_list)
|
||||
(1, 2, 3, 4)
|
||||
>>> tuple_from_string = tuple("Hello campers!")
|
||||
>>> print(tuple_from_string)
|
||||
('H', 'e', 'l', 'l', 'o', ' ', 'c', 'a', 'm', 'p', 'e', 'r', 's', '!')
|
||||
>>> a_tuple = 1, 2, 3
|
||||
>>> b_tuple = tuple(a_tuple) # If the constructor is called with a tuple for
|
||||
the iterable,
|
||||
>>> a_tuple is b_tuple # the tuple argument is returned.
|
||||
True
|
||||
```
|
||||
**Accessing elements of a `tuple`:**
|
||||
|
||||
Elements of `tuples` are accessed and index the same way that `lists` are.
|
||||
```shell
|
||||
>>> my_tuple = 1, 2, 9, 16, 25
|
||||
>>> print(my_tuple)
|
||||
(1, 2, 9, 16, 25)
|
||||
```
|
||||
_Zero indexed_
|
||||
```shell
|
||||
>>> my_tuple[0]
|
||||
1
|
||||
>>> my_tuple[1]
|
||||
2
|
||||
>>> my_tuple[2]
|
||||
9
|
||||
```
|
||||
_Wrap around indexing_
|
||||
```shell
|
||||
>>> my_tuple[-1]
|
||||
25
|
||||
>>> my_tuple[-2]
|
||||
16
|
||||
```
|
||||
**Packing and Unpacking:**
|
||||
|
||||
The statement `t = 12345, 54321, 'hello!'` is an example of tuple packing: the values `12345`, `54321` and `'hello!'` are packed together in a tuple. The reverse operation is also possible:
|
||||
```shell
|
||||
>>> x, y, z = t
|
||||
```
|
||||
This is called, appropriately enough, sequence unpacking and works for any sequence on the right-hand side. Sequence unpacking requires that there are as many variables on the left side of the equals sign as there are elements in the sequence. Note that multiple assignment is really just a combination of tuple packing and sequence unpacking.
|
||||
```shell
|
||||
>>> t = 1, 2, 3 # Tuple packing.
|
||||
>>> print(t)
|
||||
(1, 2, 3)
|
||||
>>> a, b, c = t # Sequence unpacking.
|
||||
>>> print(a)
|
||||
1
|
||||
>>> print(b)
|
||||
2
|
||||
>>> print(c)
|
||||
3
|
||||
>>> d, e, f = 4, 5, 6 # Multiple assignment combines packing and unpacking.
|
||||
>>> print(d)
|
||||
4
|
||||
>>> print(e)
|
||||
5
|
||||
>>> print(f)
|
||||
6
|
||||
>>> a, b = 1, 2, 3 # Multiple assignment requires each variable (right)
|
||||
have a matching element (left).
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
ValueError: too many values to unpack (expected 2)
|
||||
```
|
||||
**Immutable:**
|
||||
|
||||
`tuples` are immutable containers, guaranteeing **which** objects they contain will not change. It does **not** guarantee that the objects they contains will not change:
|
||||
```shell
|
||||
>>> a_list = []
|
||||
>>> a_tuple = (a_list,) # A tuple (immutable) with a list (mutable) element.
|
||||
>>> print(a_tuple)
|
||||
([],)
|
||||
|
||||
>>> a_list.append("Hello campers!")
|
||||
>>> print(a_tuple) # Element of the immutable is mutated.
|
||||
(['Hello campers!'],)
|
||||
```
|
||||
**Uses:**
|
||||
|
||||
Functions can only return a single value, however, a heterogenuous `tuple` can be used to return multiple values from a function. One example is the built-in `enumerate` function that returns an iterable of heterogenuous `tuples`:
|
||||
```shell
|
||||
>>> greeting = ["Hello", "campers!"]
|
||||
>>> enumerator = enumerate(greeting)
|
||||
>>> enumerator.next()
|
||||
>>> enumerator.__next__()
|
||||
(0, 'Hello')
|
||||
>>> enumerator.__next__()
|
||||
(1, 'campers!')
|
||||
```
|
||||
### More Inforamtion:
|
||||
<a href='https://docs.python.org/3/library/stdtypes.html#tuples' target='_blank' rel='nofollow'>Python Docs - Tuples</a>
|
246
client/src/pages/guide/english/python/decorators/index.md
Normal file
246
client/src/pages/guide/english/python/decorators/index.md
Normal file
@ -0,0 +1,246 @@
|
||||
---
|
||||
title: Python Decorators
|
||||
---
|
||||
Decorators essentially work as wrappers. They modify the behaviour of the code before and after a target function execution, without the need to modify the function itself, augmenting the original functionality, thus decorating it.
|
||||
|
||||
Before going in detail about decorators, there are some concepts that should be clear. In Python, functions are objects and we can do a lot of useful stuff with them.
|
||||
|
||||
> ### Assigning funtions to a variables:
|
||||
|
||||
def greet(name):
|
||||
return "Hello "+name
|
||||
greet_someone = greet
|
||||
print greet_someone("John")
|
||||
|
||||
> Output: Hello John
|
||||
|
||||
 <a href='https://repl.it/CXGk' target='_blank' rel='nofollow'>Run code</a>
|
||||
|
||||
> ### Defining functions inside other functions:
|
||||
|
||||
def greet(name):
|
||||
def get_message():
|
||||
return "Hello "
|
||||
result = get_message()+name
|
||||
return result
|
||||
print(greet("John"))
|
||||
|
||||
> Output: Hello John
|
||||
|
||||
 <a href='https://repl.it/CXGu' target='_blank' rel='nofollow'>Run code</a>
|
||||
|
||||
> ### Functions can also be passed as parameters to other functions:
|
||||
|
||||
def greet(name):
|
||||
return "Hello " + name
|
||||
def call_func(func):
|
||||
other_name = "John"
|
||||
return func(other_name)
|
||||
print call_func(greet)
|
||||
|
||||
> Output: Hello John
|
||||
|
||||
 <a href='https://repl.it/CXHC' target='_blank' rel='nofollow'>Run code</a>
|
||||
|
||||
> ### Functions can return other functions:
|
||||
>
|
||||
> In other words, functions generating other functions.
|
||||
|
||||
def compose_greet_func():
|
||||
def get_message():
|
||||
return "Hello there!"
|
||||
return get_message
|
||||
greet = compose_greet_func()
|
||||
print(greet())
|
||||
|
||||
Output: Hello there!
|
||||
|
||||
 <a href='https://repl.it/CXHG' target='_blank' rel='nofollow'>Run code</a>
|
||||
|
||||
> ### Inner functions have access to the enclosing scope
|
||||
>
|
||||
> More commonly known as a <a href='http://www.shutupandship.com/2012/01/python-closures-explained.html' target='_blank' rel='nofollow'>closure</a>. A very powerful pattern that we will come across while building decorators. Another thing to note, Python only allows <a href='http://www.tech-thoughts-blog.com/2013/07/writing-closure-in-python.html' target='_blank' rel='nofollow'>read access to the outer scope</a> and not assignment. Notice how we modified the example above to read a "name" argument from the enclosing scope of the inner function and return the new function.
|
||||
|
||||
def compose_greet_func(name):
|
||||
def get_message():
|
||||
return "Hello there "+name+"!"
|
||||
return get_message
|
||||
greet = compose_greet_func("John")
|
||||
print(greet())
|
||||
|
||||
> Output: Hello there John!
|
||||
|
||||
 <a href='https://repl.it/CXHI' target='_blank' rel='nofollow'>Run code</a>
|
||||
|
||||
## Composition of Decorators
|
||||
|
||||
Function decorators are simply wrappers to existing functions. Putting the ideas mentioned above together, we can build a decorator. In this example let's consider a function that wraps the string output of another function by p tags.
|
||||
|
||||
def get_text(name):
|
||||
return "lorem ipsum, {0} dolor sit amet".format(name)
|
||||
|
||||
def p_decorate(func):
|
||||
def func_wrapper(name):
|
||||
return "<p>{0}</p>".format(func(name))
|
||||
return func_wrapper
|
||||
|
||||
my_get_text = p_decorate(get_text)
|
||||
print (my_get_text("John"))
|
||||
|
||||
> Output: `<p>`lorem ipsum, John dolor sit amet`</p>`
|
||||
|
||||
 <a href='https://repl.it/CXHL' target='_blank' rel='nofollow'>Run code</a>
|
||||
|
||||
That was our first decorator. A function that takes another function as an argument, generates a new function, augmenting the work of the original function, and returning the generated function so we can use it anywhere. To have `get_text` itself be decorated by `p_decorate`, we just have to assign get_text to the result of p_decorate.
|
||||
|
||||
get_text = p_decorate(get_text)
|
||||
print (get_text("John"))
|
||||
|
||||
> Output: lorem ipsum, John dolor sit amet
|
||||
|
||||
Another thing to notice is that our decorated function takes a name argument. All what we had to do in the decorator is to let the wrapper of get_text pass that argument.
|
||||
|
||||
> ### Python's Decorator Syntax
|
||||
|
||||
Python makes creating and using decorators a bit cleaner and nicer for the programmer through some <a href='http://en.wikipedia.org/wiki/Syntactic_sugar' target='_blank' rel='nofollow'>syntactic sugar</a> To decorate get_text we don't have to get_text = p_decorator(get_text) There is a neat shortcut for that, which is to mention the name of the decorating function before the function to be decorated. The name of the decorator should be perpended with an @ symbol.
|
||||
|
||||
def p_decorate(func):
|
||||
def func_wrapper(name):
|
||||
return "<p>{0}</p>".format(func(name))
|
||||
return func_wrapper
|
||||
|
||||
@p_decorate
|
||||
def get_text(name):
|
||||
return "lorem ipsum, {0} dolor sit amet".format(name)
|
||||
|
||||
print get_text("John")
|
||||
|
||||
> Output: `<p>`lorem ipsum, John dolor sit amet`</p>`
|
||||
|
||||
 <a href='https://repl.it/CXHN' target='_blank' rel='nofollow'>Run code</a>
|
||||
|
||||
Now let's consider we wanted to decorate our get_text function by 2 other functions to wrap a div and strong tag around the string output.
|
||||
|
||||
def p_decorate(func):
|
||||
def func_wrapper(name):
|
||||
return "<p>{0}</p>".format(func(name))
|
||||
return func_wrapper
|
||||
|
||||
def strong_decorate(func):
|
||||
def func_wrapper(name):
|
||||
return "<strong>{0}</strong>".format(func(name))
|
||||
return func_wrapper
|
||||
|
||||
def div_decorate(func):
|
||||
def func_wrapper(name):
|
||||
return "<div>{0}</div>".format(func(name))
|
||||
return func_wrapper
|
||||
|
||||
With the basic approach, decorating get_text would be along the lines of
|
||||
|
||||
get_text = div_decorate(p_decorate(strong_decorate(get_text)))
|
||||
|
||||
With Python's decorator syntax, same thing can be achieved with much more expressive power.
|
||||
|
||||
@div_decorate
|
||||
@p_decorate
|
||||
@strong_decorate
|
||||
def get_text(name):
|
||||
return "lorem ipsum, {0} dolor sit amet".format(name)
|
||||
|
||||
print (get_text("John"))
|
||||
|
||||
> Output: `<div><p><strong>`lorem ipsum, John dolor sit amet`</strong></p></div>`
|
||||
|
||||
 <a href='https://repl.it/CXHQ' target='_blank' rel='nofollow'>Run code</a>
|
||||
|
||||
One important thing to notice here is that the order of setting our decorators matters. If the order was different in the example above, the output would have been different. ## Decorating Methods In Python, methods are functions that expect their first parameter to be a reference to the current object. We can build decorators for methods the same way, while taking self into consideration in the wrapper function.
|
||||
|
||||
def p_decorate(func):
|
||||
def func_wrapper(self):
|
||||
return "<p>{0}</p>".format(func(self))
|
||||
return func_wrapper
|
||||
|
||||
class Person(object):
|
||||
def __init__(self):
|
||||
self.name = "John"
|
||||
self.family = "Doe"
|
||||
@p_decorate
|
||||
def get_fullname(self):
|
||||
return self.name+" "+self.family
|
||||
|
||||
my_person = Person()
|
||||
print (my_person.get_fullname())
|
||||
|
||||
> Output: `<p>`John Doe`</p>`
|
||||
|
||||
 <a href='https://repl.it/CXH2' target='_blank' rel='nofollow'>Run code</a>
|
||||
|
||||
A much better approach would be to make our decorator useful for functions and methods alike. This can be done by putting <a href='http://docs.python.org/2/tutorial/controlflow.html#arbitrary-argument-lists' target='_blank' rel='nofollow'>*args and **kwargs</a> as parameters for the wrapper, then it can accept any arbitrary number of arguments and keyword arguments.
|
||||
|
||||
def p_decorate(func):
|
||||
def func_wrapper(*args, **kwargs):
|
||||
return "<p>{0}</p>".format(func(*args, **kwargs))
|
||||
return func_wrapper
|
||||
|
||||
class Person(object):
|
||||
def __init__(self):
|
||||
self.name = "John"
|
||||
self.family = "Doe"
|
||||
@p_decorate
|
||||
def get_fullname(self):
|
||||
return self.name+" "+self.family
|
||||
|
||||
my_person = Person()
|
||||
print (my_person.get_fullname())
|
||||
|
||||
> Output : `<p>`John Doe`</p>`
|
||||
|
||||
 <a href='https://repl.it/CXH5' target='_blank' rel='nofollow'>Run code</a>
|
||||
|
||||
### Passing arguments to decorators Looking back at the example before the one above, you can notice how redundant the decorators in the example are. 3 decorators(div_decorate, p_decorate, strong_decorate) each with the same functionality but wrapping the string with different tags. We can definitely do much better than that. Why not have a more general implementation for one that takes the tag to wrap with as a string? Yes please!
|
||||
|
||||
def tags(tag_name):
|
||||
def tags_decorator(func):
|
||||
def func_wrapper(name):
|
||||
return "<{0}>{1}</{0}>".format(tag_name, func(name))
|
||||
return func_wrapper
|
||||
return tags_decorator
|
||||
|
||||
@tags("p")
|
||||
def get_text(name):
|
||||
return "Hello "+name
|
||||
|
||||
print (get_text("John"))
|
||||
|
||||
> Output: `<p>`Hello John`</p>`
|
||||
|
||||
 <a href='https://repl.it/CXH6' target='_blank' rel='nofollow'>Run code</a>
|
||||
|
||||
It took a bit more work in this case. Decorators expect to receive a function as an argument, that is why we will have to build a function that takes those extra arguments and generate our decorator on the fly. In the example above tags, is our decorator generator. Debugging decorated functions At the end of the day decorators are just wrapping our functions, in case of debugging that can be problematic since the wrapper function does not carry the name, module and docstring of the original function. Based on the example above if we do:
|
||||
|
||||
print (get_text.__name__)
|
||||
|
||||
> Output: func_wrapper The output was expected to be get_text yet, the attributes __name__, __doc__, and __module__ of get_text got overridden by those of the wrapper(func_wrapper. Obviously we can re-set them within func_wrapper but Python provides a much nicer way. ### Functools to the rescue
|
||||
|
||||
from functools import wraps
|
||||
def tags(tag_name):
|
||||
def tags_decorator(func):
|
||||
@wraps(func)
|
||||
def func_wrapper(name):
|
||||
return "<{0}>{1}</{0}>".format(tag_name, func(name))
|
||||
return func_wrapper
|
||||
return tags_decorator
|
||||
|
||||
@tags("p")
|
||||
def get_text(name):
|
||||
"""returns some text"""
|
||||
return "Hello "+name
|
||||
|
||||
print (get_text.__name__) # get_text
|
||||
print (get_text.__doc__) # returns some text
|
||||
print (get_text.__module__) # __main__
|
||||
|
||||
 <a href='https://repl.it/CXHb' target='_blank' rel='nofollow'>Run code</a>
|
||||
|
||||
You can notice from the output that the attributes of get_text are the correct ones now.
|
@ -0,0 +1,22 @@
|
||||
---
|
||||
title: Python Defining Functions
|
||||
---
|
||||
<a href='https://docs.python.org/3/tutorial/controlflow.html#defining-functions' target='_blank' rel='nofollow'>Python Docs</a>
|
||||
|
||||
We can create a function that writes the Fibonacci series to an arbitrary boundary:
|
||||
|
||||
>>> def fib(n): # write Fibonacci series up to n
|
||||
... """Print a Fibonacci series up to n."""
|
||||
... a, b = 0, 1
|
||||
... while a < n:
|
||||
... print(a, end=' ')
|
||||
... a, b = b, a+b
|
||||
... print()
|
||||
...
|
||||
>>> # Now call the function we just defined:
|
||||
... fib(2000)
|
||||
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
|
||||
|
||||
The [`def`](https://docs.python.org/3/reference/compound_stmts.html#def) keyword introduces a function definition. It must be followed by the function name and the parenthesized list of formal parameters. The statements that form the body of the function start at the next line and must be indented.
|
||||
|
||||
The first statement of the function body can optionally be a string literal; this string literal is the function's documentation string, or [docstring](https://www.python.org/dev/peps/pep-0257/) (More about docstrings can be found in the section Documentation Strings). Some tools use docstrings to automatically produce online or printed documentation or to let the user interactively browse through code. It's good practice to include docstrings in code that you write, so try to make a habit of it.
|
@ -0,0 +1,26 @@
|
||||
---
|
||||
title: Difference between Python 'is' and '==' operators
|
||||
---
|
||||
`is` is a check for object identity - ie, checking if two or more variables are referring to the same object. You can't overload `is`.
|
||||
|
||||
`==` evaluates to true if object referred to by the variables are equal. You can overload `==` via the `__eq__` operator.
|
||||
|
||||
|
||||
## Return Value
|
||||
|
||||
The return value for both would be either `True` or `False`.
|
||||
|
||||
## Code Sample
|
||||
|
||||
a = 2.3
|
||||
a is 2.3 # => False
|
||||
a == 2.3 # => True
|
||||
|
||||
a = [234,123,321]
|
||||
b = [234,123,321]
|
||||
a == b # => True
|
||||
a is b # => False
|
||||
a = b
|
||||
a == b # => True
|
||||
a is b # => True, because if we change a, b changes too
|
||||
|
65
client/src/pages/guide/english/python/docstring/index.md
Normal file
65
client/src/pages/guide/english/python/docstring/index.md
Normal file
@ -0,0 +1,65 @@
|
||||
---
|
||||
title: Docstring
|
||||
---
|
||||
## Docstring
|
||||
|
||||
Docstring is a way for developers to communicate the purpose, parameters, requirements, and usage of a function in Python to other developers. It allows for ease of code maintenance and understanding.
|
||||
|
||||
Unlike conventional source code comments the docstring should describe what the
|
||||
function does, not how.
|
||||
|
||||
A similar example to Docstring is @Javadoc in Java.
|
||||
|
||||
Docstring is written as a multi-line comment just after the declaration header in Python. There are 4 different parts to a docstring:
|
||||
|
||||
1. Type of input, and type of output
|
||||
* Input/output can be ```obj, list, bool, int, str, float```
|
||||
2. Description of function
|
||||
* Brief, but thorough description of what your function does
|
||||
3. Requirements
|
||||
* This is read by a human, so it does not have to be code
|
||||
4. Test cases (normally 2-3)
|
||||
|
||||
The general format is listed below.
|
||||
|
||||
## Format of Docstring
|
||||
|
||||
```python
|
||||
def my_examplefunc(input_type1, input_type2):
|
||||
'''(input_type1, input_type2) -> output_type # Your first line will be the input/output. Remember the space around the arrow!
|
||||
Here is a description of my example function # Your second line will be the description
|
||||
REQ: type(input_type1) == list # Your next line (or lines) will be the requirements for the input of your function
|
||||
REQ: type(input_type2) == str
|
||||
>>> my_example_func([2, 3], "Hello World!") # After the requirements come test cases
|
||||
[2, 3] "Hello World"
|
||||
>>> my_example_func([7, 2], "Another test case") # Your first line of the test case is an example of the usage, prefaced by >>>
|
||||
[7, 2] "Another test case" # Your second line of the test case is the output
|
||||
>>> my_example_func([5, 6], "Last test case")
|
||||
[5, 6] "Last test case"
|
||||
'''
|
||||
# Your code goes here, underneath the Docstring
|
||||
```
|
||||
|
||||
Docstring is best understood with examples, so take a look at the below example program where the program outputs True if a number is less than 5, and False if a number is greater than 5.
|
||||
|
||||
## Example 1
|
||||
```python
|
||||
def is_less_than_five(some_number):
|
||||
'''(int) -> bool
|
||||
Returns True if the given number is less than 5, and False is the given number is greater than 5.
|
||||
REQ: some_number != 5
|
||||
>>> is_less_than_five(4)
|
||||
True
|
||||
>>> is_less_than_five(6)
|
||||
False
|
||||
>>> is_less_than_five(100000)
|
||||
False
|
||||
'''
|
||||
# Your code goes here
|
||||
```
|
||||
|
||||
### Some useful links:
|
||||
Numpy and Google Docstrings are two commonly used approaches:
|
||||
* Google: http://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html
|
||||
* Numpy: http://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_numpy.html
|
||||
Also, refer to some good old PEP commentary: https://www.python.org/dev/peps/pep-0257/
|
@ -0,0 +1,35 @@
|
||||
---
|
||||
title: Python Escape Sequences
|
||||
---
|
||||
A list of escape sequences can be found <a href='https://docs.python.org/3/reference/lexical_analysis.html#strings' target='_blank' rel='nofollow'>here</a>
|
||||
|
||||
Escape sequences allow for including special characters into strings.
|
||||
|
||||
>>> print('Single quote strings can have \'single\' quotes if they are escaped')
|
||||
"Single quote strings can have 'single' quotes if they are escaped"
|
||||
>>> print("Double quote strings can have \"double\" quotes if they are escaped")
|
||||
'Double quote strings can have "double" quotes if they are escaped'
|
||||
>>> print("Multiline strings\ncan be created\nusing escape sequences.")
|
||||
Multiline strings
|
||||
can be created
|
||||
using escape sequences.
|
||||
>>> print("Backslashes \\ need to be escaped.")
|
||||
Backslashes \ need to be escaped.
|
||||
|
||||
A _raw_ string can be used by prefixing the string with `r` or `R` which allows for backslashes to be included without the need to escape them -
|
||||
|
||||
>>> print(r"Backslashes \ don't need to be escaped in raw strings.")
|
||||
Backslashes \ don't need to be escaped in raw strings.
|
||||
>>> print(r"An odd number of backslashes at the end of a raw string will cause an error\")
|
||||
File "<stdin>", line 1
|
||||
print(r"An odd number of backslashes at the end of a raw string will cause an error\")
|
||||
^
|
||||
SyntaxError: EOL while scanning string literal.
|
||||
#Some more examples of escape sequences.
|
||||
Escape Sequence
|
||||
\\ Prints Backslash
|
||||
\` Prints single-quote
|
||||
\" Prints double quote
|
||||
\a ASCII bell makes ringing the bell alert sounds ( eg. xterm )
|
||||
\b ASCII backspace ( BS ) removes previous character
|
||||
\n Adds newline.
|
99
client/src/pages/guide/english/python/files-and-io/index.md
Normal file
99
client/src/pages/guide/english/python/files-and-io/index.md
Normal file
@ -0,0 +1,99 @@
|
||||
---
|
||||
title: Files and IO
|
||||
---
|
||||
|
||||
## Files and IO
|
||||
File is a named location on disk to store related information. It is used to permanently store data in non-volatile memory (e.g. hard disk). Since, random access memory (RAM) is volatile which loses its data when computer is turned off, we use files for future use of the data.
|
||||
|
||||
When we want to read from or write to a file we need to open it first. When we are done, it needs to be closed, so that resources that are tied with the file are freed.
|
||||
|
||||
Hence, in Python, a file operation takes place in the following order:
|
||||
1) Open a file
|
||||
2) Read or write (perform operation)
|
||||
3) Close the file
|
||||
|
||||
Python has many ways of input and output operations. Some of the output operations can be printing a text, console logs and even output a text or spreadsheet file.
|
||||
|
||||
### Output to Screen
|
||||
Python provides the simplest way to produce output to the screen.
|
||||
```python
|
||||
print "Python is a powerful language.","It is easy to learn."
|
||||
```
|
||||
Output:
|
||||
```
|
||||
Python is a powerful language.It is easy to learn.
|
||||
```
|
||||
|
||||
### Input from User
|
||||
There are two ways to take input from a user.
|
||||
<dl>
|
||||
<dt> raw_input([prompt]) </dt>
|
||||
<dd>Used to read one line from standard input and returns it as a string</dd>
|
||||
</dl>
|
||||
|
||||
```python
|
||||
str = raw_input("Enter your name: ")
|
||||
print "Welcome ", str
|
||||
```
|
||||
Output:
|
||||
```
|
||||
Enter your name: John Doe
|
||||
Welcome John Doe
|
||||
```
|
||||
<dl>
|
||||
<dt>input(prompt)</dt>
|
||||
<dd>Similar functionality to raw_input(), but assumes the input is a valid Python expression</dd>
|
||||
</dl>
|
||||
|
||||
```python
|
||||
str = input("Enter input: ")
|
||||
print "Input: ", str
|
||||
```
|
||||
Output:
|
||||
```
|
||||
Enter input: [x*5 for x in range(2,10,2)]
|
||||
Input: [10,20,30,40]
|
||||
```
|
||||
|
||||
### Interacting with Files in Python
|
||||
Using Python, files can be easily opened, read, written and closed. With the available functions :
|
||||
1. <code>open()</code>
|
||||
2. <code>read()</code>
|
||||
3. <code>write()</code>
|
||||
4. <code>close()</code>
|
||||
|
||||
Example:
|
||||
```python
|
||||
file1 = open("foo.txt", "r+") # Opens the file with read permission.
|
||||
file1.write("Python is a powerful language.It is easy to learn.") # Writes data into the file.
|
||||
data = file1.read(15) # Reads first 15 characters in the file.
|
||||
print "First 15 characters are:\n", data # Prints output
|
||||
file1.close() # Closes the opened file.
|
||||
```
|
||||
|
||||
Output:
|
||||
```
|
||||
First 15 characters are:
|
||||
Python is a pow
|
||||
```
|
||||
|
||||
#### Opening Files
|
||||
The python method open() can be used to return a file object. It is most commonly used with two arguments which are the file name and the mode of access. The mode of access is used to describe the way the file is accessed or used.
|
||||
|
||||
The most commonly used modes are 'w' which is for writing into the file and 'r' which is used for reading the file while 'r+' is used to read and write the file. 'a' is the mode that is used for appending text into the file. The mode argument is also optional and will be assumed to be 'r' if it is ommitted.
|
||||
|
||||
A file has to be closed after the input and output operation has been completed to free up any resources.
|
||||
|
||||
Sample code to open a text file:
|
||||
|
||||
``` python
|
||||
file = open('hello_world.txt','w')
|
||||
file.write('Hello World!')
|
||||
file.close()
|
||||
```
|
||||
|
||||
#### More Information:
|
||||
[Python Documentation - IO](https://docs.python.org/2/tutorial/inputoutput.html)
|
||||
[Automate the Boring Stuff](https://automatetheboringstuff.com/chapter8/)
|
||||
[Tutorials Point - Python IO](https://www.tutorialspoint.com/python/python_files_io.htm)
|
||||
|
@ -0,0 +1,186 @@
|
||||
---
|
||||
title: For Loop Statements
|
||||
---
|
||||
## For Loop Statements
|
||||
|
||||
Python utilizes a for loop to iterate over a list of elements. Unlike C or Java, which use the for loop to change a value in steps and access something such as an array using that value.
|
||||
|
||||
For loops iterate over collection based data structures like lists, tuples, and dictionaries.
|
||||
|
||||
The basic syntax is:
|
||||
|
||||
```python
|
||||
for value in list_of_values:
|
||||
# use value inside this block
|
||||
```
|
||||
|
||||
In general, you can use anything as the iterator value, where entries of the iterable can be assigned to. E.g. you can unpack tuples from a list of tuples:
|
||||
|
||||
```python
|
||||
list_of_tuples = [(1,2), (3,4)]
|
||||
|
||||
for a, b in list_of_tuples:
|
||||
print("a:", a, "b:", b)
|
||||
```
|
||||
On the other hand, you can loop over anything that is iterable. You can call a function or use a list literal.
|
||||
|
||||
```python
|
||||
for person in load_persons():
|
||||
print("The name is:", person.name)
|
||||
```
|
||||
|
||||
```python
|
||||
for character in ["P", "y", "t", "h", "o", "n"]:
|
||||
print("Give me a '{}'!".format(character))
|
||||
```
|
||||
|
||||
Some ways in which For loops are used:
|
||||
|
||||
**Iterate over the range() function**
|
||||
|
||||
```python
|
||||
for i in range(10):
|
||||
print(i)
|
||||
```
|
||||
Rather than being a function, range is actually an immutable sequence type.
|
||||
The output will contain results from lower bound i.e 0 to the upper bound i.e 10 but excluding 10.By default the lower bound or the starting index is set to zero.
|
||||
Output:
|
||||
|
||||
```
|
||||
>
|
||||
0
|
||||
1
|
||||
2
|
||||
3
|
||||
4
|
||||
5
|
||||
6
|
||||
7
|
||||
8
|
||||
9
|
||||
>
|
||||
```
|
||||
Additionally, one can specify the lower bound of the sequence and even the step of the sequence by adding a second and a third parameter.
|
||||
|
||||
```python
|
||||
for i in range(4,10,2): #From 4 to 9 using a step of two
|
||||
print(i)
|
||||
```
|
||||
Output:
|
||||
|
||||
```
|
||||
>
|
||||
4
|
||||
6
|
||||
8
|
||||
>
|
||||
```
|
||||
|
||||
**xrange() function**
|
||||
|
||||
For the most part, xrange and range are the exact same in terms of functionality. They both provide a way to generate a list of integers for you to use, however you please. The only difference is that range returns a Python list object and xrange returns an xrange object. It means that xrange doesn't actually generate a static list at run-time like range does. It creates the values as you need them with a special technique called yielding. This technique is used with a type of object known as generators.
|
||||
|
||||
One more thing to add. In Python 3.x, the xrange function does not exist anymore. The range function now does what xrange does in Python 2.x
|
||||
|
||||
**Iterate over values in a list or tuple**
|
||||
|
||||
```python
|
||||
A = ["hello", 1, 65, "thank you", [2, 3]]
|
||||
for value in A:
|
||||
print(value)
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
>
|
||||
hello
|
||||
1
|
||||
65
|
||||
thank you
|
||||
[2, 3]
|
||||
>
|
||||
```
|
||||
|
||||
**Iterate over keys in a dictionary (aka hashmap)**
|
||||
|
||||
```python
|
||||
fruits_to_colors = {"apple": "#ff0000",
|
||||
"lemon": "#ffff00",
|
||||
"orange": "#ffa500"}
|
||||
|
||||
for key in fruits_to_colors:
|
||||
print(key, fruits_to_colors[key])
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
>
|
||||
apple #ff0000
|
||||
lemon #ffff00
|
||||
orange #ffa500
|
||||
>
|
||||
```
|
||||
**Iterate over two lists of same size in a single loop with the zip() function**
|
||||
|
||||
```python
|
||||
A = ["a", "b", "c"]
|
||||
B = ["a", "d", "e"]
|
||||
|
||||
for a, b in zip(A, B):
|
||||
print a, b, a == b
|
||||
|
||||
```
|
||||
|
||||
Output:
|
||||
```
|
||||
>
|
||||
a a True
|
||||
b d False
|
||||
c e False
|
||||
>
|
||||
```
|
||||
|
||||
|
||||
**Iterate over a list and get the corresponding index with the enumerate() function**
|
||||
|
||||
```python
|
||||
A = ["this", "is", "something", "fun"]
|
||||
|
||||
for index,word in enumerate(A):
|
||||
print(index, word)
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
>
|
||||
0 this
|
||||
1 is
|
||||
2 something
|
||||
3 fun
|
||||
>
|
||||
```
|
||||
|
||||
A common use case is iterating over a dictionary:
|
||||
|
||||
```python
|
||||
for name, phonenumber in contacts.items():
|
||||
print(name, "is reachable under", phonenumber)
|
||||
```
|
||||
|
||||
If you absolutely need to access the current index of your iteration, do **NOT** use `range(len(iterable))`! This is an extremely bad practice and will get you plenty of chuckles from senior Python developers. Use the built in function `enumerate()` instead:
|
||||
|
||||
```python
|
||||
for index, item in enumerate(shopping_basket):
|
||||
print("Item", index, "is a", item)
|
||||
```
|
||||
|
||||
#### More Information:
|
||||
|
||||
- <a href='https://docs.python.org/2.7/tutorial/controlflow.html#for-statements' target='_blank' rel='nofollow'>Python2 for loop documentation</a>
|
||||
|
||||
- <a href='https://docs.python.org/3/tutorial/controlflow.html#for-statements' target='_blank' rel='nofollow'>Python3 for loop documentation</a>
|
||||
|
||||
|
@ -0,0 +1,32 @@
|
||||
---
|
||||
title: Python from X Import Y
|
||||
---
|
||||
If you have read the <a>`import statements`</a> wiki then you'd have seen me use this statement in one of the examples. Today, we'll try to understand what it does
|
||||
|
||||
So picking up the same example:
|
||||
|
||||
>>> from math import ceil, sqrt
|
||||
>>> # here it would be
|
||||
>>> sqrt(36)
|
||||
<<< 6
|
||||
|
||||
 <a href='https://repl.it/CS5t/1' target='_blank' rel='nofollow'>Run Code</a>
|
||||
|
||||
Or we could use this:
|
||||
|
||||
>>> import math
|
||||
>>> # here it would be
|
||||
>>> math.sqrt(36)
|
||||
<<< 6
|
||||
|
||||
 <a href='https://repl.it/CS5u' target='_blank' rel='nofollow'>Run Code</a>
|
||||
|
||||
Then our code would look like`math.sqrt(x)` instead of `sqrt(x)`. This happens because when we use `import x`, a namespace `x` is itself created to avoid name conflicts. You have to access every single object of the module as `x.<name>`. But when we use `from x import y` we agree to add `y` to the main global namespace. So while using this we have to make sure that we don't have an object with same name in our program.
|
||||
|
||||
> **Never use `from x import y` if an object named `y` already exists**
|
||||
|
||||
For example, in `os` module there's a method `open`. But we even have a built-in function called `open`. So, here we should avoid using `from os import open`.
|
||||
|
||||
We can even use `form x import *`, this would import all the methods, classes of that module to the global namespace of the program. This is a bad programming practice. Please avoid it.
|
||||
|
||||
In general you should avoid ` from x import y` simply because of the problems it may cause in large scale programs. For example, you never know if a fellow programmer might want to make a new function that happens to be the name of one of the existing functions. You also do not know whether Python will change the library that you are importing functions from. While these problems won't exist as often for solo projects, as stated before, it is bad programming practice and should be avoided.
|
39
client/src/pages/guide/english/python/frozenset/index.md
Normal file
39
client/src/pages/guide/english/python/frozenset/index.md
Normal file
@ -0,0 +1,39 @@
|
||||
---
|
||||
title: Python Frozenset
|
||||
---
|
||||
**`frozenset` basic info**<br>
|
||||
The `frozenset` type is a builtin set types which is immutable and hashable -- its contents cannot be altered after it is created; however, it can be used as a dictionary key or as an element of another set. Frozensets are like sets except that they cannot be changed, i.e they are immutale.
|
||||
|
||||
>>> cities = frozenset(["Frankfurt", "Basel", "Freiburg"])
|
||||
>>> cities.add("Strasbourg")
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
AttributeError: 'frozenset' object has no attribute 'add'
|
||||
>>>
|
||||
|
||||
`frozenset` constructor:<br>
|
||||
`frozenset([iterable])` <br>
|
||||
The iterable contains elements to initialize the frozenset with. The iterable can be set, dictionary, tuple etc. If no parameter is passed, the `frozenset()` method returns an empty frozenset.
|
||||
|
||||
**Examples** <br>
|
||||
|
||||
>>> vowels = ('a', 'e', 'i', 'o', 'u')
|
||||
>>> fSet = frozenset(vowels)
|
||||
>>> print("The frozen set is: ", fSet)
|
||||
The frozen set is: frozenset({'i', 'e', 'a', 'u', 'o'})
|
||||
>>> print("The empty frozen set is: ", frozenset())
|
||||
The empty frozen set is: frozenset()
|
||||
>>>
|
||||
|
||||
**Another Example** <br>
|
||||
|
||||
>>> person = {"name": "John", "age": 23, "sex": "male"}
|
||||
>>> fSet = frozenset(person)
|
||||
>>> print("The frozen set is: ", fSet)
|
||||
The frozen set is: frozenset({'sex', 'name', 'age'})
|
||||
>>>
|
||||
|
||||
**Additional Information** <br>
|
||||
<a href="https://www.programiz.com/python-programming/methods/built-in/frozenset">Python Frozenset()</a> <br>
|
||||
<a href="https://docs.python.org/2.4/lib/types-set.html">Set Types -- set, frozenset</a> <br>
|
||||
<a href="https://www.python-course.eu/sets_frozensets.php">Python Tutorial: Sets and Frozen sets</a>
|
128
client/src/pages/guide/english/python/functions/index.md
Normal file
128
client/src/pages/guide/english/python/functions/index.md
Normal file
@ -0,0 +1,128 @@
|
||||
---
|
||||
title: Functions
|
||||
---
|
||||
## Functions
|
||||
|
||||
A function allows you to define a reusable block of code that can be executed many times within your program.
|
||||
|
||||
Functions allow you to create more modular and [DRY](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself) solutions to complex problems.
|
||||
|
||||
While Python already provides many built-in functions such as `print()` and `len()`, you can also define your own functions to use within your projects.
|
||||
|
||||
### Syntax
|
||||
|
||||
In Python, a function definition has the following features:
|
||||
|
||||
1. The keyword `def`
|
||||
2. a function name
|
||||
3. input parameters (optional)
|
||||
4. some block of code to execute
|
||||
5. a return statement (optional)
|
||||
|
||||
```python
|
||||
# a function with no parameters or returned values
|
||||
def sayHello():
|
||||
print("Hello!")
|
||||
|
||||
sayHello() # calls the function, 'Hello!' is printed to the console
|
||||
|
||||
# a function with a parameter
|
||||
def helloWithName(name):
|
||||
print("Hello " + name + "!")
|
||||
|
||||
helloWithName("Ada") # calls the function, 'Hello Ada!' is printed to the console
|
||||
|
||||
# a function with multiple parameters with a return statement
|
||||
def multiply(val1, val2):
|
||||
return val1 * val2
|
||||
|
||||
print(multiply(3, 5)) # prints 15 to the console
|
||||
```
|
||||
|
||||
Functions are blocks of code that can be reused simply by calling the function. This enables simple, elegent code reuse without explicitly re-writing sections of code. This makes code both more readable, makes for easier debugging, and limits typing errors.
|
||||
|
||||
Functions in Python are created using the `def` keyword, followed by a function name and function parameters inside parentheses.
|
||||
|
||||
The `return` keyword is used by the function to return a value, if you don't want to return any value, the default value `None` will returned.
|
||||
|
||||
The function name is used to call the function, passing the needed parameters inside parentheses.
|
||||
|
||||
```python
|
||||
# this is a basic sum function
|
||||
def sum(a, b):
|
||||
return a + b
|
||||
|
||||
result = sum(1, 2)
|
||||
# result = 3
|
||||
```
|
||||
|
||||
You can define default values for the parameters, that way Python will interpretate that the value of that parameter is the default one if none is given.
|
||||
|
||||
```python
|
||||
def sum(a, b=3):
|
||||
return a + b
|
||||
|
||||
result = sum(1)
|
||||
# result = 4
|
||||
```
|
||||
|
||||
You can pass the parameters in the order you want, using the name of the parameter.
|
||||
|
||||
```python
|
||||
result = sum(b=2, a=2)
|
||||
# result = 4
|
||||
```
|
||||
|
||||
However, it is not possible to pass a keyword argument before a non-keyword one
|
||||
|
||||
```Python
|
||||
result = sum(3, b=2)
|
||||
#result = 5
|
||||
result2 = sum(b=2, 3)
|
||||
#Will raise SyntaxError
|
||||
```
|
||||
|
||||
Functions are also Objects, so you can assign them to a variable, and use that variable like a function.
|
||||
|
||||
```python
|
||||
s = sum
|
||||
result = s(1, 2)
|
||||
# result = 3
|
||||
```
|
||||
|
||||
### Notes
|
||||
|
||||
- If a function definition includes parameters, you must provide the same number of parameters when you call the function.
|
||||
|
||||
```python
|
||||
print(multiply(3)) # TypeError: multiply() takes exactly 2 arguments (0 given)
|
||||
|
||||
print(multiply('a', 5)) # 'aaaaa' printed to the console
|
||||
|
||||
print(multiply('a', 'b')) # TypeError: Python can't multiply two strings
|
||||
```
|
||||
|
||||
- The block of code that the function will run includes all statements indented within the function.
|
||||
|
||||
```python
|
||||
def myFunc():
|
||||
print('this will print')
|
||||
print('so will this')
|
||||
|
||||
x = 7
|
||||
# the assignment of x is not a part of the function since it is not indented
|
||||
```
|
||||
|
||||
- Variables defined within a function only exist within the scope of that function.
|
||||
|
||||
```python
|
||||
def double(num):
|
||||
x = num * 2
|
||||
return x
|
||||
|
||||
print(x) # error - x is not defined
|
||||
print(double(4)) # prints 8
|
||||
```
|
||||
|
||||
### More Information:
|
||||
- <a href='https://docs.python.org/3/tutorial/controlflow.html#defining-functions' target='_blank' rel='nofollow'>Python 3 Docs: Defining Functions</a>
|
54
client/src/pages/guide/english/python/generators/index.md
Normal file
54
client/src/pages/guide/english/python/generators/index.md
Normal file
@ -0,0 +1,54 @@
|
||||
---
|
||||
title: Generators
|
||||
---
|
||||
## Generators
|
||||
Generators are a special type of function that allows you to return values without ending a function. It does this by using the `yield` keyword. Similar to `return`, the `yield` expression will return a value to the caller. The key difference between the two is that `yield` will suspend the function, allowing for more values to be returned in the future.
|
||||
|
||||
Generators are iterable so they can be used cleanly with for loops or anything else that iterates.
|
||||
```python
|
||||
def my_generator():
|
||||
yield 'hello'
|
||||
yield 'world'
|
||||
yield '!'
|
||||
|
||||
for item in my_generator():
|
||||
print(item)
|
||||
|
||||
# output:
|
||||
# hello
|
||||
# world
|
||||
# !
|
||||
```
|
||||
|
||||
Like other iterators, generators can be passed to the `next` function to retrieve the next item. When a generator has no more values to yield, a `StopIteration` error is raised.
|
||||
```python
|
||||
g = my_generator()
|
||||
print(next(g))
|
||||
# 'hello'
|
||||
print(next(g))
|
||||
# 'world'
|
||||
print(next(g))
|
||||
# '!'
|
||||
print(next(g))
|
||||
# Traceback (most recent call last):
|
||||
# File "<stdin>", line 1, in <module>
|
||||
# StopIteration
|
||||
```
|
||||
|
||||
Generators are particularly useful when you need to create a large set of values but do not need to keep them all in memory at the same time. For example, if you need to print the first million fibonacci numbers, you would typically return a list of a million values and iterate over the list to print each value. However with a generator, you can return each value one at a time:
|
||||
```python
|
||||
def fib(n):
|
||||
a = 1
|
||||
b = 1
|
||||
for i in range(n):
|
||||
yield a
|
||||
a, b = b, a + b
|
||||
|
||||
for x in fib(1000000):
|
||||
print(x)
|
||||
```
|
||||
|
||||
### More Information
|
||||
* [PEP 255](https://www.python.org/dev/peps/pep-0255/)
|
||||
* [Python Wiki](https://wiki.python.org/moin/Generators)
|
||||
* [Yield Statement Documentation](https://docs.python.org/2/reference/simple_stmts.html#yield)
|
22
client/src/pages/guide/english/python/hex-functions/index.md
Normal file
22
client/src/pages/guide/english/python/hex-functions/index.md
Normal file
@ -0,0 +1,22 @@
|
||||
---
|
||||
title: Python Hex Function
|
||||
---
|
||||
`hex(x)` is a built-in function in Python 3 to convert an integer number to a lowercase <a href='https://www.mathsisfun.com/hexadecimals.html' target='_blank' rel='nofollow'>hexadecimal</a> string prefixed with “0x”.
|
||||
|
||||
## Argument
|
||||
|
||||
This function takes one argument, `x`, that should be of integer type.
|
||||
|
||||
## Return
|
||||
|
||||
This function returns a lowercase hexadecimal string prefixed with "0x".
|
||||
|
||||
## Example
|
||||
|
||||
print(hex(16)) # prints 0x10
|
||||
print(hex(-298)) # prints -0x12a
|
||||
print(hex(543)) # prints 0x21f
|
||||
|
||||
 <a href='https://repl.it/CV0S' target='_blank' rel='nofollow'>Run Code</a>
|
||||
|
||||
<a href='https://docs.python.org/3/library/functions.html#hex' target='_blank' rel='nofollow'>Official Documentation</a>
|
@ -0,0 +1,71 @@
|
||||
---
|
||||
title: How to Convert Strings into Integers in Python
|
||||
---
|
||||
## How to Convert Strings into Integers in Python
|
||||
|
||||
Just like the `str()` built-in, Python also offers a handy built-in which takes a string object as an argument and returns the corresponding integer object.
|
||||
|
||||
#### Example Usage:
|
||||
|
||||
```py
|
||||
# Here age is a string object
|
||||
age = "18"
|
||||
print(age)
|
||||
# Converting string to integer
|
||||
int_age = int(age)
|
||||
print(int_age)
|
||||
```
|
||||
Output
|
||||
```py
|
||||
18
|
||||
18
|
||||
```
|
||||
Here although the output is visually similar but you should keep in mind that the first line prints a string object while the line next to it prints a integer object which is further illustrated in the next example:
|
||||
|
||||
```py
|
||||
age = "18"
|
||||
print(age+2)
|
||||
```
|
||||
Output:
|
||||
```py
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
TypeError: cannot concatenate 'str' and 'int' objects
|
||||
````
|
||||
The error should make it clear to you that you need to convert the `age` object to an integer before adding something to it.
|
||||
|
||||
```py
|
||||
age = "18"
|
||||
age_int = int(age)
|
||||
print(age_int+2)
|
||||
```
|
||||
Output:
|
||||
```py
|
||||
20
|
||||
```
|
||||
|
||||
But you should keep in mind some special cases:
|
||||
|
||||
1. A floating point(an integer with fractional part) as an argument will return the float rounded down to the nearest whole integer.
|
||||
For example : `print(int(7.9))` will print `7`.
|
||||
Also `print(int("7.9"))` will result an error since the string is an invalid argument to convert to an integer.
|
||||
|
||||
```py
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
ValueError: invalid literal for int() with base 10: '7.9'
|
||||
```
|
||||
|
||||
2. Also any integer in words if given as an argument will return the same error as above:
|
||||
`print(int("one"))` will give an error as follows:
|
||||
|
||||
```py
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
ValueError: invalid literal for int() with base 10: 'one'
|
||||
```
|
||||
|
||||
#### More Information:
|
||||
Official documentation for `int()` built-in can be found <a href='https://docs.python.org/3.6/library/functions.html#int' target='_blank' rel='nofollow'>here</a>
|
||||
|
||||
|
41
client/src/pages/guide/english/python/idobject/index.md
Normal file
41
client/src/pages/guide/english/python/idobject/index.md
Normal file
@ -0,0 +1,41 @@
|
||||
---
|
||||
title: Python Idobject
|
||||
---
|
||||
`id()` is a built-in function in Python 3, which returns the _identity_ of an object. The _identity_ is a unique integer for that object during its lifetime. This is also the address of the object in memory.
|
||||
|
||||
## Argument
|
||||
|
||||
#### object
|
||||
|
||||
The `object` argument can typically be a `int`,`float`,`str`,`list`,`dict`,`tuple` etc.
|
||||
|
||||
## Code Sample
|
||||
|
||||
a = 2
|
||||
print(id(a)) #=> 140454723286976 (Values returned by id() might be different for different users)
|
||||
|
||||
b = 3
|
||||
print(id(b)) #=> 140454723287008
|
||||
|
||||
c = 2
|
||||
print(id(c)) #=> 140454723286976 (This is same as id(a) since they both contain the same value and hence have same memory address)
|
||||
|
||||
print(id(a) == id(b)) #=> False (since a and b have different values stored in them)
|
||||
print(id(a) == id(c)) #=> True (since a and c have same values stored in them)
|
||||
|
||||
d = 1.1
|
||||
e = 1.1
|
||||
print(id(d) == id(e)) #=> True (since d and e have same values stored in them)
|
||||
|
||||
str1 = 'hello'
|
||||
str2 = 'hello'
|
||||
print(id(str1) == id(str2)) #=> True (since str1 and str2 have same values stored in them)
|
||||
|
||||
# For complex objects like lists, tuples, dictionaries etc. id() would give a unique integer even if the content of those containers is same.
|
||||
tup1 = (1,1)
|
||||
tup2 = (1,1)
|
||||
print(id(tup1) == id(tup2)) #=> False
|
||||
|
||||
 <a href='https://repl.it/CQw7/1' target='_blank' rel='nofollow'>Run Code</a>
|
||||
|
||||
<a href='https://docs.python.org/3/library/functions.html#id' target='_blank' rel='nofollow'>Official Docs</a>
|
@ -0,0 +1,73 @@
|
||||
---
|
||||
title: If Elif Else Statements
|
||||
---
|
||||
|
||||
## If Elif Else Statements
|
||||
|
||||
The `if`/`elif`/`else` structure is a common way to control the flow of a program, allowing you to execute specific blocks of code depending on the value of some data. If the condition following the keyword `if` evaluates as `true`, the block of code will execute:
|
||||
Note that parenthesis is not used before and after the condition check as in other languages .
|
||||
```python
|
||||
if True:
|
||||
print('If block will execute!')
|
||||
```
|
||||
|
||||
```python
|
||||
x = 5
|
||||
|
||||
if x > 4:
|
||||
print("The condition was true!") #this statement executes
|
||||
```
|
||||
|
||||
You can optionally add an `else` response that will execute if the condition is `false`:
|
||||
```python
|
||||
if not True:
|
||||
print('If statement will execute!')
|
||||
else:
|
||||
print('Else statement will execute!')
|
||||
```
|
||||
Or you can also see this example
|
||||
```python
|
||||
y = 3
|
||||
|
||||
if y > 4:
|
||||
print("I won't print!") #this statement does not execute
|
||||
else:
|
||||
print("The condition wasn't true!") #this statement executes
|
||||
```
|
||||
|
||||
*Note that there is no condition following the `else` keyword - it catches all situations where the condition was `false`*
|
||||
|
||||
Multiple conditions can be checked by including one or more `elif` checks after your initial `if` statement but only one condition will execute:
|
||||
|
||||
```python
|
||||
z = 7
|
||||
|
||||
if z > 8:
|
||||
print("I won't print!") #this statement does not execute
|
||||
elif z > 5:
|
||||
print("I will!") #this statement will execute
|
||||
elif z > 6:
|
||||
print("I also won't print!") #this statement does not execute
|
||||
else:
|
||||
print("Neither will I!") #this statement does not execute
|
||||
```
|
||||
|
||||
*Note only the first condition that evaluates as `true` will execute. Even though `z > 6` is `true`, the `if/elif/else` block terminates after the first true condition. This means that an `else` will only execute if none of the conditions were `true`.*
|
||||
|
||||
We can also create nested if's for decision making. Before preceding please refer to the href='https://guide.freecodecamp.org/python/code-blocks-and-indentation' target='_blank' rel='nofollow'>indentation guide once</a> before preceding.
|
||||
|
||||
Let's take an example of finding a number which is even and also greater than '10`
|
||||
```
|
||||
python
|
||||
x = 34
|
||||
if x % 2 == 0: # this is how you create a comment and now, checking for even.
|
||||
if x > 10:
|
||||
print("This number is even and is greater than 10")
|
||||
else:
|
||||
print("This number is even, but not greater 10")
|
||||
else:
|
||||
print ("The number is not even. So point checking further.")
|
||||
```
|
||||
This was just a simple example for nested if's. Please feel free to explore more online.
|
||||
|
||||
While the examples above are simple, you can create complex conditions using <a href='https://guide.freecodecamp.org/python/comparisons' target='_blank' rel='nofollow'>boolean comparisons</a> and <a href='https://guide.freecodecamp.org/python/boolean-operations' target='_blank' rel='nofollow'>boolean operators</a>.
|
@ -0,0 +1,90 @@
|
||||
---
|
||||
title: Python Import Statements
|
||||
---
|
||||
While learning programming and reading some resources you'd have come across this word 'abstraction' which simply means to reduce and reuse the code as much as possible.
|
||||
|
||||
Functions and Modules facilitate abstraction. You create functions when you want to do something repeatedly within a file.
|
||||
|
||||
Modules come into picture when you want to reuse a group of functions in different source files. Modules are also useful in structuring the program well.
|
||||
|
||||
* Using Standard Libraries and other third party modules:
|
||||
* Structuring the program
|
||||
|
||||
## Using Standard Libraries
|
||||
|
||||
Example: You can read about the methods/functions of all the standard libraries in the official Python Docs in detail.
|
||||
|
||||
import time
|
||||
for i in range(100):
|
||||
time.sleep(1) # Waits for 1 second and then executes the next command
|
||||
print(str(i) + ' seconds have passed') # prints the number of seconds passed after the program was started
|
||||
|
||||
 <a href='https://repl.it/CS6C' target='_blank' rel='nofollow'>Run Code</a>
|
||||
|
||||
# To calculate the execution time of a part of program
|
||||
import time
|
||||
start = time.time()
|
||||
# code here
|
||||
end = time.time()
|
||||
print('Execution time:' , end-start)
|
||||
|
||||
 <a href='https://repl.it/CS6C/1' target='_blank' rel='nofollow'>Run Code</a>
|
||||
|
||||
# Using math Module
|
||||
import math
|
||||
print(math.sqrt(100)) # prints 10
|
||||
|
||||
 <a href='https://repl.it/CS6C/2' target='_blank' rel='nofollow'>Run Code</a>
|
||||
|
||||
## Using third party Modules
|
||||
|
||||
Third party modules don't come bundled with python , but we have to install it externally using package managers like <a href='https://bootstrap.pypa.io/get-pip.py' target='_blank' rel='nofollow'>`pip`</a> and <a href='https://bootstrap.pypa.io/ez_setup.py' target='_blank' rel='nofollow'>`easy install`</a>
|
||||
|
||||
# To make http requests
|
||||
import requests
|
||||
rq = requests.get(target_url)
|
||||
print(rq.status_code)
|
||||
|
||||
Find out more about python-requests module <a href='http://docs.python-requests.org/en/master/' target='_blank' rel='nofollow'>here</a>
|
||||
|
||||
## To structure programs
|
||||
|
||||
We want to make a program that has various functions regarding prime numbers. So lets start. We will define all the functions in `prime_functions.py`
|
||||
|
||||
# prime_functions.py
|
||||
from math import ceil, sqrt
|
||||
def isPrime(a):
|
||||
if a == 2:
|
||||
return True
|
||||
elif a % 2 == 0:
|
||||
return False
|
||||
else:
|
||||
for i in range(3,ceil(sqrt(a)) + 1,2):
|
||||
if a % i == 0:
|
||||
return False
|
||||
return True
|
||||
|
||||
def print_n_primes(a):
|
||||
i = 0
|
||||
m = 2
|
||||
while True:
|
||||
if isPrime(m) ==True:
|
||||
print(m)
|
||||
i += 1
|
||||
m += 1
|
||||
if i == a:
|
||||
break
|
||||
|
||||
Now we want to use the functions that we just created in `prime_functions.py` so we create a new file `playground.py` to use those functions.
|
||||
|
||||
> _Please note that this program is far too simple to make two separate files, it is just to demonstrate. But when there are large complex programs, making different files is really useful._
|
||||
|
||||
# playground.py
|
||||
import prime_functions
|
||||
print(prime_functions.isPrime(29)) # returns True
|
||||
|
||||
## Sorting Imports
|
||||
|
||||
Good practice is to sort `import` modules in three groups - standard library imports, related third-party imports, and local imports. Within each group it is sensible to sort alphabetically by module name. You can find [more information in PEP8](https://www.python.org/dev/peps/pep-0008/?#imports).
|
||||
|
||||
One of the most important thing for Python language is legibility, and alphabetically sorting modules are quicker to read and search. Also it is easier to verify that something is imported, and avoid duplicated imports.
|
162
client/src/pages/guide/english/python/index.md
Normal file
162
client/src/pages/guide/english/python/index.md
Normal file
@ -0,0 +1,162 @@
|
||||
---
|
||||
title: Python
|
||||
---
|
||||
|
||||
## What is Python?
|
||||
|
||||
<a href='https://www.python.org' target='_blank' rel='nofollow'>Python</a> is a general purpose programming language which is dynamically typed, interpreted, and known for its easy readability with great design principles.
|
||||
|
||||
To know more about Python, you might want to check <a href='https://www.python.org/doc/essays/blurb/' target='_blank' rel='nofollow'>this</a> and <a href='https://docs.python.org/3/faq/general.html' target='_blank' rel='nofollow'>this</a>.
|
||||
|
||||
## Python 2 or Python 3
|
||||
|
||||
* The two versions are similar, with knowledge of one switching to writing code for the other is easy.
|
||||
* <a href='https://wiki.python.org/moin/Python2orPython3' target='_blank' rel='nofollow'>Python 2 or Python 3</a>
|
||||
* <a href='https://www.python.org/dev/peps/pep-0373/' target='_blank' rel='nofollow'>Python 2.x will not be maintained past 2020.</a>
|
||||
* 3.x is under active development. This means that all recent standard library improvements, for example, are only available by default in Python 3.x.
|
||||
* Python ecosystem has amassed a significant amount of quality software over the years. The downside of breaking backwards compatibility in 3.x is that some of that software (especially in-house software in companies) still doesn't work on 3.x yet.
|
||||
|
||||
## Installation
|
||||
|
||||
Most *nix based operating systems come with Python installed (usually Python 2). Replacing the system Python is not recommended and may cause problems. However, different versions of Python can be safely installed alongside the system Python. See <a href='https://docs.python.org/3/using/index.html' target='_blank' rel='nofollow'>Python Setup and Usage</a>.
|
||||
|
||||
Windows doesn't come with Python, the installer and instructions can be found <a href='https://docs.python.org/3/using/windows.html' target='_blank' rel='nofollow'>here</a>
|
||||
|
||||
## Python Interpreter
|
||||
|
||||
The Python interpreter is what is used to run Python scripts.
|
||||
|
||||
If it is available and in Unix shell’s search path makes it possible to start it by typing the command `python` followed by the script name will invoke the interpreter and run the script.
|
||||
|
||||
`hello_campers.py`
|
||||
|
||||
```python
|
||||
print('Hello campers!')
|
||||
```
|
||||
|
||||
From terminal:
|
||||
|
||||
$ python hello_campers.py
|
||||
Hello campers!
|
||||
|
||||
"When multiple versions of Python are installed, calling them by version is possible depending on the install configuration. In the Cloud9 ide custom environment, they can be invoked like:
|
||||
|
||||
$ python --version
|
||||
Python 2.7.6
|
||||
$ python3 --version
|
||||
Python 3.4.3
|
||||
$ python3.5 --version
|
||||
Python 3.5.1
|
||||
$ python3.6 --version
|
||||
Python 3.6.2
|
||||
|
||||
## Python Interpreter Interactive Mode
|
||||
|
||||
Interactive mode can be started by invoking the Python interpreter with the `-i` flag or without any arguments.
|
||||
|
||||
Interactive mode has a prompt where Python commands can be entered and run:
|
||||
|
||||
$ python3.5
|
||||
Python 3.5.1 (default, Dec 18 2015, 00:00:00)
|
||||
GCC 4.8.4 on linux
|
||||
Type "help", "copyright", "credits" or "license" for more information.
|
||||
>>> print("Hello campers!")
|
||||
Hello campers!
|
||||
>>> 1 + 2
|
||||
3
|
||||
>>> exit()
|
||||
$
|
||||
|
||||
## The Zen of Python
|
||||
|
||||
Some of the principles that influenced the design of Python are included as an Easter egg and can be read by using the command inside Python interpreter interactive mode:
|
||||
|
||||
>>> 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!
|
||||
|
||||
|
||||
## Pros and Cons of Python
|
||||
### Pros
|
||||
1. Interactive language with a module support for almost all functionality.
|
||||
2. Open Source: So, you can contribute to the community, the functions you have developed for future use and to help others
|
||||
3. A lot of good interpreters and notebooks available for better experience like jupyter notebook.
|
||||
|
||||
#### Cons
|
||||
1. Being open source, many different ways have developed over the year for same function. This sometimes, creates chaos for others to read someone else code.
|
||||
2. It is a slow language. So, a very bad language to use for developing general algorithms.
|
||||
|
||||
## Documentation
|
||||
|
||||
<a href='https://docs.python.org/3/' target='_blank' rel='nofollow'>Python is well documented</a>. These docs include tutorials, guides, references and meta information for language.
|
||||
|
||||
Another important reference is the Python Enhancement Proposals (<a href='https://www.python.org/dev/peps/' target='_blank' rel='nofollow'>PEPs</a>). Included in the PEPs is a style guide for writing Python code, <a href='https://www.python.org/dev/peps/pep-0008/' target='_blank' rel='nofollow'>`PEP 8`</a>.
|
||||
|
||||
## Debugging
|
||||
|
||||
Inline `print` statements can be used for simple debugging:
|
||||
|
||||
> **... often the quickest way to debug a program is to add a few print statements to the source: the fast edit-test-debug cycle makes this simple approach very effective.**
|
||||
>
|
||||
> --<a href='https://www.python.org/doc/essays/blurb/' target='_blank' rel='nofollow'>Executive Summary</a>
|
||||
|
||||
Python also includes more powerful tools for debugging, such as:
|
||||
|
||||
* logging module, <a href='https://docs.python.org/3/library/logging.html' target='_blank' rel='nofollow'>_logging_</a>
|
||||
* debugging module, <a href='https://docs.python.org/3/library/pdb.html' target='_blank' rel='nofollow'>_pdb_</a>
|
||||
|
||||
Just note that these exist for now.
|
||||
|
||||
## Hello World!
|
||||
|
||||
Going back to the docs, we can read about the <a href='https://docs.python.org/3/library/functions.html#print' target='_blank' rel='nofollow'>`print`</a> function, a <a href='https://docs.python.org/3/library/functions.html' target='_blank' rel='nofollow'>_built-in function_</a> of the <a href='https://docs.python.org/3/library/index.html' target='_blank' rel='nofollow'>Python Standard Library</a>.
|
||||
|
||||
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
|
||||
|
||||
The built-in functions are listed in alphabetical order. The name is followed by a parenthesized list of formal parameters with optional default values. Under that is a short description of the function and its parameters are given and occasionally an example.
|
||||
|
||||
The <a href='https://docs.python.org/3/library/functions.html#print' target='_blank' rel='nofollow'>`print`</a> function in Python 3 replaces the <a href='https://docs.python.org/2/reference/simple_stmts.html#print' target='_blank' rel='nofollow'>`print`</a> statement in Python 2.
|
||||
|
||||
>>> print("Hello world!")
|
||||
Hello world!
|
||||
|
||||
A function is called when the name of the function is followed by `()`. For the Hello world! example, the print function is called with a string as an argument for the first parameter. For the rest of the parameters the defaults are used.
|
||||
|
||||
The argument that we called the `print` function with is a `str` object or _string_, one of Python's <a href='https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str' target='_blank' rel='nofollow'>_built-in types_</a>.
|
||||
Also the most important thing about python is that you don't have to specify the data type while declaring a variable, python's compiler
|
||||
will do that itself based on the type of value assigned.
|
||||
|
||||
The `objects` parameter is prefixed with a `*` which indicates that the function will take an arbitrary number of arguments for that parameter.
|
||||
|
||||
## Want to learn more?
|
||||
|
||||
Free Code Camp has some great resources. The web is a big place, there's plenty more to explore:
|
||||
* Python Practice Book: http://anandology.com/python-practice-book/index.html
|
||||
* Think Python: http://greenteapress.com/thinkpython/html/index.html
|
||||
* Practical Business Python: http://pbpython.com/
|
||||
* Another course: https://realpython.com/?utm_source=fsp&utm_medium=promo&utm_campaign=bestresources
|
||||
* General: https://www.fullstackpython.com/
|
||||
* Learn the Basics: https://www.codecademy.com/learn/learn-python
|
||||
* Computer science using Python: https://www.edx.org/course/introduction-computer-science-mitx-6-00-1x-11?ref=hackernoon#!
|
||||
* List of more resources for learning python: https://github.com/vinta/awesome-python
|
||||
* Interactive Python: http://interactivepython.org/runestone/static/thinkcspy/index.html
|
||||
* Developer's Guide to Python: https://devguide.python.org/
|
@ -0,0 +1,42 @@
|
||||
---
|
||||
title: Python Input Function
|
||||
---
|
||||
Many a time, in a program we need some input from the user. Taking inputs from the user makes the program feel interactive. In Python 3, to take input from the user we have a function `input()`. If the input function is called, the program flow will be stopped until the user has given an input and has ended the input with the return key. Let's see some examples:
|
||||
|
||||
1. When we just want to take the input:
|
||||
|
||||
# This will just give a prompt without any message
|
||||
inp = input()
|
||||
|
||||
 <a href='https://repl.it/CUqX/0' target='_blank' rel='nofollow'>Run Code</a>
|
||||
|
||||
1. To give a prompt with a message:
|
||||
|
||||
prompt_with_message = input('<Your prompt message should appear here>')
|
||||
# <Your prompt message should appear here> _
|
||||
# The '_' in the output is the prompt
|
||||
|
||||
 <a href='https://repl.it/CUqX/1' target='_blank' rel='nofollow'>Run Code</a>
|
||||
|
||||
3\. When we want to take an integer input:
|
||||
|
||||
number = int(input('Please enter a number: '))
|
||||
|
||||
 <a href='https://repl.it/CUqX/2' target='_blank' rel='nofollow'>Run Code</a>
|
||||
|
||||
If you enter a non integer value then Python will throw an error `ValueError`. **So whenever you use this, please make sure that you catch it too.** Otherwise, your program will stop unexpectedly after the prompt.
|
||||
|
||||
number = int(input('Please enter a number: '))
|
||||
# Please enter a number: as
|
||||
# Enter a string and it will throw this error
|
||||
# ValueError: invalid literal for int() with base 10 'as'
|
||||
|
||||
4\. When we want a string input:
|
||||
|
||||
string = str(input('Please enter a string: '))
|
||||
|
||||
 <a href='https://repl.it/CUqX/3' target='_blank' rel='nofollow'>Run Code</a>
|
||||
|
||||
Though, inputs are stored by default as a string. Using the `str()` function makes it clear to the code-reader that the input is going to be a 'string'. It is a good practice to mention what type of input will be taken beforehand.
|
||||
|
||||
<a href='https://docs.python.org/3/library/functions.html#input' target='_blank' rel='nofollow'>Official Docs</a>
|
@ -0,0 +1,67 @@
|
||||
---
|
||||
title: Installing and Using Python 3
|
||||
---
|
||||
|
||||
## Installing Python 3
|
||||
You can download Python from this official <a href='https://www.python.org/downloads/' target='_blank' rel='nofollow'>link</a>. Based on your OS (Windows or Linux or OSX), you might want to install Python 3 following <a href='http://docs.python-guide.org/en/latest/starting/installation/' target='_blank' rel='nofollow'>these instructions</a>.
|
||||
|
||||
## Using Virtual Environments
|
||||
It is always a great idea to <a href='https://en.wikipedia.org/wiki/Sandbox_(computer_security)' target='_blank' rel='nofollow'>sandbox</a> your Python installation; and keeping it separate from your _System Python_. The _System Python_ is the path to Python interpreter, which is used by other modules installed along with your OS.
|
||||
|
||||
It's **not safe** to install Python Web-frameworks or libraries directly using _System Python_. Instead, you can use <a href='https://virtualenv.readthedocs.org/en/latest/' target='_blank' rel='nofollow'>Virtualenv</a> to create and spawn a separate Python process when you are developing Python applications.
|
||||
|
||||
### Virtualenvwrapper
|
||||
The <a href='https://virtualenvwrapper.readthedocs.org/en/latest/' target='_blank' rel='nofollow'>Virtualenvwrapper module</a> makes it easy for you to manage and sandbox multiple Python sandboxed environments in one machine; without corrupting any modules or services written in Python and used by your machine.
|
||||
|
||||
Of course, most cloud hosted development environment such as <a href='https://www.nitrous.io/' target='_blank' rel='nofollow'>Nitrous</a> or <a href='https://c9.io/' target='_blank' rel='nofollow'>Cloud9</a> also comes with these pre-installed and ready for you to get coding! You can quickly pick a box from your dashboard, and start coding after activating a Python 3 environment.
|
||||
|
||||
In <a href='https://c9.io/' target='_blank' rel='nofollow'>Cloud9</a>, you need to select the Django box while creating a new development environment.
|
||||
|
||||
A few shell command examples would follow. If you wish to copy-paste, do note that the `$` sign is a shorthand for the terminal prompt, it's not part of the command. My terminal prompt looks something like this:
|
||||
|
||||
alayek:~/workspace (master) $
|
||||
|
||||
And, an `ls` would look like
|
||||
|
||||
alayek:~/workspace (master) $ ls
|
||||
|
||||
But, while writing the same in this documentation, I would be writing it as
|
||||
|
||||
$ ls
|
||||
|
||||
Getting back to our discussion, you can create a Python 3 interpreter-included sandbox on Cloud9 by running on your cloud terminal:
|
||||
|
||||
$ mkvirtualenv py3 --python=/usr/bin/python3
|
||||
|
||||
You have to run it only once after creating a new box for your project. Once executed, this command would create a new sandboxed virtualenv ready for you to use, named `py3`.
|
||||
|
||||
To view available virtual environments, you can use
|
||||
|
||||
$ workon
|
||||
|
||||
To activate `py3`, you can use the `workon` command with the name of the environment:
|
||||
|
||||
$ workon py3
|
||||
|
||||
All three terminal commands above would also work on local Linux machines or OSX machines. These are <a href='https://virtualenvwrapper.readthedocs.org/en/latest/#introduction' target='_blank' rel='nofollow'>virtualenvwrapper</a> commands; so if you are planning on using them, make sure you have this module installed and added to `PATH` variable.
|
||||
|
||||
If you are inside a virtual environment; you can easily find that out by checking your terminal prompt. The environment name would be clearly shown in your terminal prompt.
|
||||
|
||||
For instance, when I am inside the `py3` environment; I would be seeing this as my terminal prompt:
|
||||
|
||||
(py3)alayek:~/workspace (master) $
|
||||
|
||||
Notice the `(py3)` in braces! If for some reason, you are not seeing this, even if you are inside a virtual env; you can try doing one of the things <a href='http://stackoverflow.com/questions/1871549/python-determine-if-running-inside-virtualenv' target='_blank' rel='nofollow'>mentioned here</a>.
|
||||
|
||||
To get out of a virtual environment; or to deactivate one - use the command
|
||||
|
||||
$ deactivate
|
||||
|
||||
Again, this works only with virtualenvwrapper module.
|
||||
|
||||
### Pipenv
|
||||
|
||||
An alternative to using virtualenvwrapper is [Pipenv](https://docs.pipenv.org/). It automatically creates virtual environments for your projects, and maintains a `Pipfile` which contains the dependencies. Using Pipenv means you no longer need to use pip and virtualenv separately, or manage your own `requirements.txt` file. For those familiar with JavaScript, Pipenv is similar to using a packaging tool like `npm`.
|
||||
|
||||
To get started with Pipenv, you can follow this very detailed [guide](https://docs.pipenv.org/install.html#installing-pipenv). Pipenv makes it easy to [specify which version of Python](https://docs.pipenv.org/basics.html#specifying-versions-of-python) you wish to use for each project, [import](https://docs.pipenv.org/basics.html#importing-from-requirements-txt) from an existing `requirements.txt` file and [graph](https://docs.pipenv.org/#pipenv-graph) your dependencies.
|
||||
|
@ -0,0 +1,111 @@
|
||||
---
|
||||
title: Is There a Way to Substring a String in Python
|
||||
---
|
||||
|
||||
## Is There a Way to Substring a String in Python
|
||||
|
||||
Python offers many ways to substring a string. It is often called 'slicing'.
|
||||
|
||||
It follows this template:
|
||||
|
||||
```python
|
||||
string[start: end: step]
|
||||
```
|
||||
Where,
|
||||
|
||||
`start`: The starting index of the substring. The character at this index is included in the substring. If _start_ is not included, it is assumed to equal to 0.
|
||||
|
||||
`end`: The terminating index of the substring. The character at this index is _NOT_ included in the substring. If _end_ is not included, or if the specified value exceeds the string length, it is assumed to be equal to the length of the string by default.
|
||||
|
||||
`step`: Every 'step' character after the current character to be included. The default value is 1. If the _step_ value is omitted, it is assumed to equal to 1.
|
||||
|
||||
#### Template
|
||||
|
||||
`string[start:end]`: Get all characters from index _start_ to _end-1_
|
||||
|
||||
`string[:end]`: Get all characters from the beginning of the string to _end-1_
|
||||
|
||||
`string[start:]`: Get all characters from index _start_ to the end of the string
|
||||
|
||||
`string[start:end:step]`: Get all characters from _start_ to _end-1_ discounting every _step_ character
|
||||
|
||||
|
||||
#### Examples
|
||||
|
||||
* **Get the first 5 characters of a string**
|
||||
|
||||
```python
|
||||
string = "freeCodeCamp"
|
||||
print(string[0:5])
|
||||
```
|
||||
Output:
|
||||
```shell
|
||||
> freeC
|
||||
```
|
||||
|
||||
Note: `print(string[:5])` returns the same result as `print(string[0:5])`
|
||||
|
||||
* **Get a substring of length 4 from the 3rd character of the string**
|
||||
|
||||
```python
|
||||
string = "freeCodeCamp"
|
||||
print(string[2:6])
|
||||
```
|
||||
Output:
|
||||
```shell
|
||||
> eeCo
|
||||
```
|
||||
|
||||
Please note that the start or end index may be a negative number. A negative index means that you start counting from the end of the string instead of the beginning (i.e from the right to left). Index -1 represents the last character of the string, -2 represents the second to last character and so on...
|
||||
|
||||
* **Get the last character of the string**
|
||||
|
||||
```python
|
||||
string = "freeCodeCamp"
|
||||
print(string[-1])
|
||||
```
|
||||
Output:
|
||||
```shell
|
||||
> p
|
||||
```
|
||||
|
||||
* **Get the last 5 characters of a string**
|
||||
|
||||
```python
|
||||
string = "freeCodeCamp"
|
||||
print(string[-5:])
|
||||
```
|
||||
Output:
|
||||
```shell
|
||||
> eCamp
|
||||
```
|
||||
|
||||
* **Get a substring which contains all characters except the last 4 characters and the 1st character**
|
||||
|
||||
```python
|
||||
string = "freeCodeCamp"
|
||||
print(string[1:-4])
|
||||
```
|
||||
Output:
|
||||
```shell
|
||||
> reeCode
|
||||
```
|
||||
|
||||
#### More examples
|
||||
```py
|
||||
str = “freeCodeCamp”
|
||||
|
||||
print str[-5:-2] # prints ‘eCa’
|
||||
print str[-1:-2] # prints ‘’ (empty string)
|
||||
```
|
||||
|
||||
* **Get every other character from a string**
|
||||
|
||||
```python
|
||||
string = "freeCodeCamp"
|
||||
print(string[::2])
|
||||
```
|
||||
Output:
|
||||
```shell
|
||||
> feCdCm
|
||||
```
|
40
client/src/pages/guide/english/python/iterators/index.md
Normal file
40
client/src/pages/guide/english/python/iterators/index.md
Normal file
@ -0,0 +1,40 @@
|
||||
---
|
||||
title: Python Iterators
|
||||
---
|
||||
Python supports a concept of iteration over containers. This is implemented using two distinct methods; these are used to allow user-defined classes to support iteration.
|
||||
|
||||
<a href='https://docs.python.org/3/library/stdtypes.html#iterator-types' target='_blank' rel='nofollow'>Python Docs - Iterator Types</a>
|
||||
|
||||
**TODO: Clarify what iteration means and what iterators can be used for.**
|
||||
|
||||
* Objects can implement a `__iter__()` method that returns an iterator object to support iteration.
|
||||
* Iterator objects must implement:
|
||||
* `__iter__()`: returns the iterator object.
|
||||
|
||||
* `__next__()`: returns the next object of the container.
|
||||
|
||||
iterator_object = 'abc'.__iter__()
|
||||
print(iterator_object)
|
||||
print(id(iterator_object))
|
||||
print(id(iterator_object.__iter__())) # Returns the iterator itself.
|
||||
print(iterator_object.__next__()) # Returns 1st object and advances iterator.
|
||||
print(iterator_object.__next__()) # Returns 2nd object and advances iterator.
|
||||
print(iterator_object.__next__()) # Returns 3rd object and advances iterator.
|
||||
print(iterator_object.__next__()) # Raises StopIteration Exception.
|
||||
|
||||
Output :
|
||||
|
||||
<str_iterator object at 0x102e196a0>
|
||||
4343305888
|
||||
4343305888
|
||||
a
|
||||
b
|
||||
c
|
||||
---------------------------------------------------------------------------
|
||||
StopIteration Traceback (most recent call last)
|
||||
<ipython-input-1-d466eea8c1b0> in <module>()
|
||||
6 print(iterator_object.__next__()) # Returns 2nd object and advances iterator.
|
||||
7 print(iterator_object.__next__()) # Returns 3rd object and advances iterator.
|
||||
----> 8 print(iterator_object.__next__()) # Raises StopIteration Exception.
|
||||
|
||||
StopIteration:
|
14
client/src/pages/guide/english/python/itertools/index.md
Normal file
14
client/src/pages/guide/english/python/itertools/index.md
Normal file
@ -0,0 +1,14 @@
|
||||
---
|
||||
title: Itertools
|
||||
---
|
||||
|
||||
Itertools is a python module of functions that return generators, objects that only function when iterated over.
|
||||
Some examples of itertool functions include but not limited to: chain(), imap(), product(), and compress().
|
||||
|
||||
```py
|
||||
import itertools
|
||||
a = itertools.chain([1, 2], [3, 4])
|
||||
|
||||
# Output
|
||||
# [1, 2, 3, 4]
|
||||
```
|
28
client/src/pages/guide/english/python/keywords/index.md
Normal file
28
client/src/pages/guide/english/python/keywords/index.md
Normal file
@ -0,0 +1,28 @@
|
||||
---
|
||||
title: Python Keywords
|
||||
---
|
||||
## Python Keywords
|
||||
|
||||
Python has a list of <a href='https://docs.python.org/3/reference/lexical_analysis.html#keywords' target='_blank' rel='nofollow'>keywords</a> that cannot be used as identifiers (variable names). Trying to use any of these keywords as variables will create a <b>Syntax Error</b> and your Python script will not be run:
|
||||
|
||||
>>> False = "Hello campers!"
|
||||
File "<stdin>"
|
||||
SyntaxError: can't assign to keyword
|
||||
|
||||
>>> break = "Hello campers!"
|
||||
File "<stdin>", line 1
|
||||
break = "Hello campers!"
|
||||
^
|
||||
SyntaxError: invalid syntax
|
||||
|
||||
#### List of Keywords
|
||||
|
||||
Keyword | - | - | - | -
|
||||
--- | --- | --- | --- | ---
|
||||
`False` | `class` | `finally` | `is` | `return`
|
||||
`None` | `continue` | `for` | `lambda` | `try`
|
||||
`True` | `def` | `from` | `nonlocal` | `while`
|
||||
`and` | `del` | `global` | `not` | `with`
|
||||
`as` | `elif` | `if` | `or` | `yield`
|
||||
`assert` | `else` | `import` | `pass`
|
||||
`break` | `except` | `in` | `raise`
|
@ -0,0 +1,84 @@
|
||||
---
|
||||
title: Lambda Expressions
|
||||
---
|
||||
## Lambda Expressions
|
||||
|
||||
Lambda Expressions in Python are a short way to declare small and anonymous functions (it is not necessary to provide a name for lambda functions). Lambda functions behave just like regular functions declared with the `def` keyword. They come in handy when you want to define a small function in a concise way. They can contain only one expression, so they are not best suited for functions with control-flow statements.
|
||||
|
||||
#### Syntax of Lambda Function
|
||||
`lambda arguments: expression`
|
||||
|
||||
Lambda functions can have any number of arguments but only one expression
|
||||
|
||||
#### Example code
|
||||
```py
|
||||
# Lambda function to calculate square of a number
|
||||
square = lambda x: x ** 2
|
||||
print(square(3)) # Output: 9
|
||||
|
||||
# Traditional function to calculate square of a number
|
||||
def square1(num):
|
||||
return num ** 2
|
||||
print(square(5)) # Output: 25
|
||||
|
||||
```
|
||||
In the above lambda example `lambda x: x ** 2` yields an anonymous function object which can be associated with any name.
|
||||
So, we associated the function object with `square` and hence from now on we can call the `square` object like any traditional function. e.g. `square(10)`
|
||||
|
||||
## Examples
|
||||
|
||||
### Beginner
|
||||
```py
|
||||
lambda_func = lambda x: x**2 # Function that takes an integer and returns its square
|
||||
lambda_func(3) # Returns 9
|
||||
```
|
||||
### Intermediate
|
||||
```py
|
||||
lambda_func = lambda x: True if x**2 >= 10 else False
|
||||
lambda_func(3) # Returns False
|
||||
lambda_func(4) # Returns True
|
||||
```
|
||||
### Complex
|
||||
```py
|
||||
my_dict = {"A": 1, "B": 2, "C": 3}
|
||||
sorted(my_dict, key=lambda x: my_dict[x]%3) # Returns ['C', 'A', 'B']
|
||||
```
|
||||
### Use-case
|
||||
|
||||
Let's say you want to filter out odd numbers from a `list`. You could use a `for` loop:
|
||||
|
||||
```python
|
||||
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
||||
filtered = []
|
||||
|
||||
for num in my_list:
|
||||
if num % 2 != 0:
|
||||
filtered.append(num)
|
||||
|
||||
print(filtered) # Python 2: print filtered
|
||||
# [1, 3, 5, 7, 9]
|
||||
```
|
||||
|
||||
You could write this as a one liner with list-comprehensions
|
||||
|
||||
```python
|
||||
filtered = [x for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] if x % 2 != 0]
|
||||
```
|
||||
|
||||
But you might be tempted to use the built-in `filter` function. Why? The first example is a bit to verbose, the one-liner can be harder to understand, where as `filter` offers the best of both words. What is more, the built-in functions are usually faster.
|
||||
|
||||
```python
|
||||
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
||||
|
||||
filtered = filter(lambda x: x % 2 != 0, my_list)
|
||||
|
||||
list(filtered)
|
||||
# [1, 3, 5, 7, 9]
|
||||
```
|
||||
NOTE: in Python 3 built in function return generator objects, so you have to call `list`, while in Python 2 they return a `list`, `tuple`or `string`.
|
||||
|
||||
What happened? You told `filter` to take each element in `my_list` and apply the lambda expressions. The values that return `False` are filtered out.
|
||||
|
||||
#### More Information:
|
||||
- [Official Doc](https://docs.python.org/3/reference/expressions.html#lambda)
|
||||
- [Further Read](https://dbader.org/blog/python-lambda-functions)
|
@ -0,0 +1,108 @@
|
||||
---
|
||||
title: Learn About Python Lists
|
||||
---
|
||||
**TODO: `list` basic info**
|
||||
|
||||
[Python Docs - Lists](https://docs.python.org/3/library/stdtypes.html#lists)
|
||||
|
||||
**Creation:**
|
||||
|
||||
An empty `list` is created using a pair of square brackets:
|
||||
|
||||
>>> empty_list = []
|
||||
>>> type(empty_list)
|
||||
<class 'list'>
|
||||
>>> len(empty_list)
|
||||
0
|
||||
|
||||
A `list` can be created with elements by enclosing a comma separated list of elements with square brackets. Lists allow for the elements to be of different types (heterogeneous) but are most commonly of a single type (homogeneous):
|
||||
|
||||
>>> homogeneous_list = [1, 1, 2, 3, 5, 8]
|
||||
>>> type(homogeneous_list)
|
||||
<class 'list'>
|
||||
>>> print(homogeneous_list)
|
||||
[1, 1, 2, 3, 5, 8]
|
||||
>>> len(homogeneous_list)
|
||||
6
|
||||
>>> heterogeneous_list = [1, "Hello Campers!"]
|
||||
>>> print(heterogeneous_list)
|
||||
[1, "Hello Campers!"]
|
||||
>>> len(heterogeneous_list)
|
||||
2
|
||||
|
||||
The `list` constructor can also be used to create a `list`:
|
||||
|
||||
>>> empty_list = list() # Creates an empty list
|
||||
>>> print(empty_list)
|
||||
[]
|
||||
>>> list_from_iterable = list("Hello campers!") # Creates a list from an
|
||||
iterable.
|
||||
>>> print(list_from_iterable)
|
||||
['H', 'e', 'l', 'l', 'o', ' ', 'c', 'a', 'm', 'p', 'e', 'r', 's', '!']
|
||||
|
||||
**Accessing elements of a `list`:**
|
||||
|
||||
>>> my_list = [1, 2, 9, 16, 25]
|
||||
>>> print(my_list)
|
||||
[1, 2, 9, 16, 25]
|
||||
|
||||
_Zero indexed_
|
||||
|
||||
>>> my_list[0]
|
||||
1
|
||||
>>> my_list[1]
|
||||
2
|
||||
>>> my_list[2]
|
||||
9
|
||||
|
||||
_Wrap around indexing_
|
||||
|
||||
>>> my_list[-1]
|
||||
25
|
||||
>>> my_list[-2]
|
||||
16
|
||||
_Unpacking lists for python-3_
|
||||
|
||||
>>> print(*my_list)
|
||||
1 2 9 16 25
|
||||
|
||||
**Mutable:**
|
||||
|
||||
`lists` are mutable containers. Mutable containers are containers that allow changes to which objects are contained by the container. **TODO: ADD MORE?**
|
||||
|
||||
_Re-arranging elements in a list_
|
||||
|
||||
Elements from a `list` may be extracted and re-arranged using another `list` as index.
|
||||
|
||||
>>> my_list = [1, 2, 9, 16, 25, 34, 53, 21]
|
||||
>>> my_index = [5, 2, 0]
|
||||
>>> my_new_list = [my_list[i] for i in my_index]
|
||||
>>> print(my_new_list)
|
||||
[34, 9, 1]
|
||||
|
||||
|
||||
**TODO: Which of these should be discussed here:**
|
||||
|
||||
[Python Docs - More on Lists](https://docs.python.org/3/tutorial/datastructures.html#more-on-lists)
|
||||
|
||||
* `list.append(x)` Add an item to the end of the list. Equivalent to a[len(a):] = [x].
|
||||
|
||||
* `list.extend(L)` Extend the list by appending all the items in the given list. Equivalent to a[len(a):] = L.
|
||||
|
||||
* `list.insert(i, x)` Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).
|
||||
|
||||
* `list.remove(x)` Remove the first item from the list whose value is x. It is an error if there is no such item.
|
||||
|
||||
* `list.pop([i])` Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)
|
||||
|
||||
* `list.clear()` Remove all items from the list. Equivalent to del a[:].
|
||||
|
||||
* `list.index(x)` Return the index in the list of the first item whose value is x. It is an error if there is no such item.
|
||||
|
||||
* `list.count(x)` Return the number of times x appears in the list.
|
||||
|
||||
* `list.sort(key=None, reverse=False)` Sort the items of the list in place (the arguments can be used for sort customization, see sorted() for their explanation).
|
||||
|
||||
* `list.reverse()` Reverse the elements of the list in place.
|
||||
|
||||
* `list.copy()` Return a shallow copy of the list. Equivalent to a[:].
|
@ -0,0 +1,32 @@
|
||||
---
|
||||
title: Learn About Python Sets
|
||||
---
|
||||
`Set`s in Python are a type of mutable but unordered data structure, which can only contain *unique* elements.
|
||||
|
||||
**Creation:**
|
||||
|
||||
`set` literal:
|
||||
|
||||
Curly brackets, `{}`, *cannot* be used to create an empty set:
|
||||
|
||||
```python
|
||||
>>> not_set = {} # set constructor must be used to make empty sets.
|
||||
>>> type(not_set) # Empty curly brackets create empty dictionaries.
|
||||
<class 'dict'>
|
||||
```
|
||||
|
||||
You can only create an empty set by using the `set()` method.
|
||||
|
||||
```python
|
||||
>>> example_set = set()
|
||||
>>> type(example_set)
|
||||
<class 'set'>
|
||||
```
|
||||
|
||||
However, if elements are included within the curly brackets, then it would be acceptable syntax to create a set.
|
||||
|
||||
```python
|
||||
>>> example_set_2 = {1, 2, 3}
|
||||
>>> type(example_set_2)
|
||||
<class 'set'>
|
||||
````
|
30
client/src/pages/guide/english/python/len-function/index.md
Normal file
30
client/src/pages/guide/english/python/len-function/index.md
Normal file
@ -0,0 +1,30 @@
|
||||
---
|
||||
title: Python Len Function
|
||||
---
|
||||
`len()` is a built-in function in Python 3\. This method returns the length (the number of items) of an object. It takes one argument `x`.
|
||||
|
||||
## Arguments
|
||||
|
||||
It takes one argument, `x`. This argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).
|
||||
|
||||
## Return Value
|
||||
|
||||
This function returns the number of elements in the argument which is passed to the `len()` function.
|
||||
|
||||
## Code Sample
|
||||
|
||||
list1 = [123, 'xyz', 'zara'] # list
|
||||
print(len(list1)) # prints 3 as there are 3 elements in the list1
|
||||
|
||||
str1 = 'basketball' # string
|
||||
print(len(str1)) # prints 10 as the str1 is made of 10 characters
|
||||
|
||||
tuple1 = (2, 3, 4, 5) # tuple
|
||||
print(len(tuple1)) # prints 4 as there are 4 elements in the tuple1
|
||||
|
||||
dict1 = {'name': 'John', 'age': 4, 'score': 45} # dictionary
|
||||
print(len(dict1)) # prints 3 as there are 3 key and value pairs in the dict1
|
||||
|
||||
 <a href='https://repl.it/CUmt/15' target='_blank' rel='nofollow'>Run Code</a>
|
||||
|
||||
<a href='https://docs.python.org/3/library/functions.html#len' target='_blank' rel='nofollow'>Official Docs</a>
|
@ -0,0 +1,26 @@
|
||||
---
|
||||
title: List Append Method
|
||||
---
|
||||
## List Append Method
|
||||
|
||||
There are many methods for lists, you can explore all of them by typing `help(list)` in your python console.
|
||||
One of them is the append function which, as the name says appends the argument given list.
|
||||
|
||||
#### Example Usage
|
||||
|
||||
```py
|
||||
words = ["I", "love", "Python"]
|
||||
words.append("very much")
|
||||
print(words)
|
||||
```
|
||||
#### Output
|
||||
```
|
||||
["I", "love", "Python", "very much"]
|
||||
```
|
||||
As you might have noticed the element `"very much"` is appended to the list.
|
||||
|
||||
#### More Information:
|
||||
|
||||
The official documentation for `append()` can be found <a href='https://docs.python.org/3.6/tutorial/datastructures.html' target='_blank' rel='nofollow'>here</a>
|
||||
|
||||
|
@ -0,0 +1,47 @@
|
||||
---
|
||||
title: List Comprehension
|
||||
---
|
||||
|
||||
## List Comprehension
|
||||
|
||||
List Comprehension is a way of looping through a list to produce a new list based on some conditions. It can be confusing at first but once you are acclimated to the syntax it is very powerful and quick.
|
||||
|
||||
The first step in learning how to use list comprehension is to look at the traditional way of looping through a list. The following is a simple example that returns a new list of even numbers.
|
||||
|
||||
```Python
|
||||
# Example list for demonstration
|
||||
some_list = [1, 2, 5, 7, 8, 10]
|
||||
|
||||
# Empty list that will be populate with a loop
|
||||
even_list = []
|
||||
|
||||
for number in some_list:
|
||||
if number % 2 == 0:
|
||||
even_list.append(number)
|
||||
|
||||
# even_list now equals [2, 8, 10]
|
||||
```
|
||||
|
||||
First a list is created with some numbers. You then create an empty list that will hold your results from the loop. In the loop you check to see if each number is divisible by 2 and if so you add it the the even_list. This took 5 lines of code not including comments and white space which isn't much in this example.
|
||||
|
||||
Now for the list comprehension example.
|
||||
|
||||
```Python
|
||||
# Example list for demonstration
|
||||
some_list = [1, 2, 5, 7, 8, 10]
|
||||
|
||||
# List Comprehension
|
||||
even_list = [number for number in some_list if number % 2 == 0]
|
||||
|
||||
# even_list now equals [2, 8, 10]
|
||||
```
|
||||
|
||||
What the list comprehension does is it adds an element from a list to a new list if some condition is met. This example list comprehension says that for every number (the variable of the for loop) in some_list, if that number is divisible by 2 (the number is even) then return that number to be added to the new list (even_list).
|
||||
|
||||
The same list is produced but in this case it only took 2 lines of code. The List Comprehension allows for the 3 lines of the for loop plus the 1 line of creating an empty list to be condensed into a single line. Not only is this much neater but it is much faster in most cases. This example is pretty simple and easy to read so list comprehension is a good choice. There are cases where list comprehension makes readability very bad so you have to weigh your options when choosing to use list comprehension.
|
||||
|
||||
Further documentation of this can be seen on the official Python website under data structures:
|
||||
https://docs.python.org/2.7/tutorial/datastructures.html
|
||||
|
||||
Also a good resourse is Python for Beginners:
|
||||
http://www.pythonforbeginners.com/basics/list-comprehensions-in-python
|
@ -0,0 +1,25 @@
|
||||
---
|
||||
title: List Extend Method
|
||||
---
|
||||
## List Extend Method
|
||||
|
||||
There are many methods for lists, you can explore all of them by typing `help(list)` in your python console.
|
||||
One of them is the extend function which, as the name says extends the list by adding all items of a list (passed as an argument) to the end.
|
||||
|
||||
|
||||
#### Example Usage
|
||||
|
||||
```py
|
||||
cities = ["San Francisco", "Los Angeles", "New York"]
|
||||
cities_in_texas = ["San Antonio", "Austin", "Dallas"]
|
||||
cities.extend(cities_in_texas)
|
||||
print(cities)
|
||||
```
|
||||
#### Output
|
||||
```
|
||||
["San Francisco", "Los Angeles", "New York", "San Antonio", "Austin", "Dallas"]
|
||||
```
|
||||
|
||||
#### More Information:
|
||||
|
||||
The official documentation for `extend()` can be found <a href='https://docs.python.org/3.6/tutorial/datastructures.html' target='_blank' rel='nofollow'>here</a>
|
@ -0,0 +1,58 @@
|
||||
---
|
||||
title: List Index Method
|
||||
---
|
||||
## List Index Method
|
||||
|
||||
Among the many functions which come along with the list data structure the `index()` returns the the first occurrence/index of the element in the list given as an argument to the function.
|
||||
|
||||
Lists are the most basic Python data structure and stores a list of values in order (in comparison to dictionaries, which order doesn't matter). We retrieve the items by numerical index.
|
||||
|
||||
Keeping in mind the fact that indexing starts from 0, or the first element is taken to be at the 0 index, let's have a look at some examples.
|
||||
|
||||
#### Example Usage:
|
||||
|
||||
```py
|
||||
numbers = [1, 2, 2, 3, 9, 5, 6, 10]
|
||||
words = ["I", "love", "Python", "I", "love"]
|
||||
|
||||
print(numbers.index(9))
|
||||
print(numbers.index(2))
|
||||
print(words.index("I"))
|
||||
print(words.index("am"))
|
||||
```
|
||||
|
||||
##### Output:
|
||||
|
||||
```py
|
||||
4
|
||||
1
|
||||
0
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
ValueError: 'am' is not in list
|
||||
```
|
||||
|
||||
Here the first output is very obvious, but the second and third might seem confusing at first.But remember `index()` returns the first occurrence of the element and hence in this case `1` and `0` are the indices where `2` and `"I"` occur first in the lists respectively.
|
||||
|
||||
Also, if an element is not found in the list, a `ValueError` is returned as in the case of indexing `"am"` in the `words` list.
|
||||
|
||||
#### Optional arguments:
|
||||
|
||||
You can also use optional arguments to limit your search to a particular subsequence of the list as illustrated by this example:
|
||||
|
||||
```py
|
||||
words = ["I","am", "a", "I", "am", "Pythonista"]
|
||||
|
||||
print(words.index("am",2,5))
|
||||
```
|
||||
##### Output:
|
||||
```
|
||||
4
|
||||
```
|
||||
Here although the element is searched between the indices 2(inclusive) and 5(not inclusive) but the returned index is computed relative to the beginning of the full list rather than the start argument.
|
||||
|
||||
#### More Information:
|
||||
|
||||
The official documentation for `index()` can be found <a href='https://docs.python.org/3.6/tutorial/datastructures.html' target='_blank' rel='nofollow'>here</a>
|
||||
|
||||
|
@ -0,0 +1,99 @@
|
||||
---
|
||||
title: Map, Reduce, Filter
|
||||
---
|
||||
#Map,Reduce & Filter
|
||||
|
||||
Most engineers work with lists to process list of orders/users etc. Analyzing lists can get complex and cluttered quickly if using multiple for-loops and nested loops. Hence these above methods can streamline usage of list operations.
|
||||
## Map
|
||||
|
||||
If your task is to apply a specific method to each element of a list, map will come in handy. Say, you have a list of degree values and you'd like to convert all these values into list of values in Fahrenheit units.
|
||||
|
||||
|
||||
#### Example Usage
|
||||
|
||||
```py
|
||||
|
||||
inputs = [10,32,5,40,25]
|
||||
|
||||
def degreesToFahren(deg):
|
||||
fahrenheit = (9.0/5)*deg +32
|
||||
return fahrenheit
|
||||
|
||||
# The most common way of doing this
|
||||
result=[]
|
||||
for i in inputs:
|
||||
iTofahren = degreesToFahren(i)
|
||||
result.append(iTofahren)
|
||||
print(result) # [50.0, 89.6, 41.0, 104.0, 77.0]
|
||||
```
|
||||
```py
|
||||
# Using Map
|
||||
result = list(map(degreesToFahren,inputs))
|
||||
print(result) # [50.0, 89.6, 41.0, 104.0, 77.0]
|
||||
|
||||
```
|
||||
As you might have noticed, using map is simply a one liner operation. Generally, if you have data = ``` [a1,a2,...,an] ``` and a function ``` f()```, then ``` map(f,data): ```returns an iterator over ```f(a1),f(a2)...f(an). ``` use ```list()``` to convert the iterator object into a python list.
|
||||
|
||||
|
||||
## Filter
|
||||
|
||||
Filter function removes data in a list that you need/don't need , hence the name. Say, you want to filter a list based on values that you don't need, eg values above 2.
|
||||
|
||||
#### Example Usage
|
||||
|
||||
```py
|
||||
data = [1.2,2.5,5.8,0.4,4.7,9.9]
|
||||
result = list(filter(lambda x:x > 2,data))
|
||||
print(result)
|
||||
```
|
||||
#### Output
|
||||
```
|
||||
[2.5, 5.8, 4.7, 9.9]
|
||||
```
|
||||
This is also a simple 1 liner similar to the map() function above. Refer to tutorial on lambda functions if you find this term unfamiliar.
|
||||
|
||||
## Reduce
|
||||
|
||||
From creator of Python, Guido van Rossum
|
||||
```"Use functools.reduce if you really need it; however, 99% of the time an explicit for loop is more readable"```
|
||||
|
||||
What it generally does is apply a function ```f()``` to elements of data in a list and use that result for the next value in the list.
|
||||
Visually,
|
||||
|
||||
Data = [a<sub>1</sub>,a<sub>2</sub>,...,a<sub>n</sub>]
|
||||
function = f(x,y)
|
||||
|
||||
reduce(f,data):
|
||||
Step 1: val<sub>1</sub> = f(a<sub>1</sub>,a<sub>2</sub>)
|
||||
Step 2: val<sub>2</sub> = f(val<sub>1</sub>,a<sub>3</sub>)
|
||||
Step 3: val<sub>3</sub> = f(val<sub>2</sub> ,a<sub>4</sub>)
|
||||
.
|
||||
.
|
||||
.
|
||||
Step n-1: val<sub>n-1</sub> = f(val<sub>n-2</sub>,a<sub>n</sub>)
|
||||
|
||||
For example, you want to multiply all numbers in a list.
|
||||
|
||||
#### Example Usage
|
||||
|
||||
```py
|
||||
from functools import reduce
|
||||
|
||||
input = [1,2,3,4,5,6]
|
||||
multiplier = lambda x,y:x*y
|
||||
answer = reduce(multiplier,input)
|
||||
print(answer)
|
||||
```
|
||||
#### Output
|
||||
```
|
||||
720
|
||||
```
|
||||
However, the above could be computed using a simple for loop and usage of these methods are subject to preference.
|
||||
|
||||
|
||||
|
||||
#### More Information:
|
||||
|
||||
The official documentation for the above methods can be found at http://book.pythontips.com/en/latest/map_filter.html
|
||||
|
||||
|
41
client/src/pages/guide/english/python/list-pop/index.md
Normal file
41
client/src/pages/guide/english/python/list-pop/index.md
Normal file
@ -0,0 +1,41 @@
|
||||
---
|
||||
title: List Pop Method
|
||||
---
|
||||
# Pop Function
|
||||
The method pop() removes and returns last element from the list. There is an optional parameter, index of the element to be removed from the list.
|
||||
If no index is specified, a.pop() removes and returns the last item in the list.
|
||||
If the index passed to the pop() method is not in the range, it throws IndexError: pop index out of range exception.
|
||||
|
||||
|
||||
|
||||
#### Example Usage
|
||||
```py
|
||||
cities = ['New York', 'Dallas', 'San Antonio', 'Houston', 'San Francisco'];
|
||||
|
||||
print "City popped is : ", cities.pop()
|
||||
print "City at index 2 is : ", cities.pop(2)
|
||||
```
|
||||
|
||||
#### Output
|
||||
```
|
||||
City popped is : San Francisco
|
||||
City at index 2 is : San Antonio
|
||||
```
|
||||
|
||||
#### Basic Stack Functionality
|
||||
|
||||
The `pop()` method is often used in conjunction with `append()` to implement basic stack functionality in a Python application.
|
||||
|
||||
```py
|
||||
stack = []
|
||||
|
||||
for i in range(5):
|
||||
stack.append(i)
|
||||
|
||||
while len(stack):
|
||||
print(stack.pop())
|
||||
```
|
||||
|
||||
#### More Information:
|
||||
The official documentation for `pop()` can be found <a href='https://docs.python.org/3.6/tutorial/datastructures.html' target='_blank' rel='nofollow'>here</a>
|
||||
|
@ -0,0 +1,38 @@
|
||||
---
|
||||
title: List Remove Method
|
||||
---
|
||||
## List Remove Method
|
||||
|
||||
The `remove()` method removes the argument given to it from the list.
|
||||
|
||||
#### Example Usage
|
||||
|
||||
```py
|
||||
words = ["I", "love", "Python"]
|
||||
words.remove("I")
|
||||
print(words)
|
||||
```
|
||||
#### Output
|
||||
|
||||
```py
|
||||
["love","Python"]
|
||||
```
|
||||
|
||||
Note that it returns an error if the element to be removed is not found in the list as illustrated in the example below.
|
||||
|
||||
```py
|
||||
kiss = ["keep", "it", "simple", "stupid"]
|
||||
kiss.remove("complex")
|
||||
print(kiss)
|
||||
```
|
||||
|
||||
#### Output
|
||||
```
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
ValueError: list.remove(x): x not in list
|
||||
```
|
||||
#### More Information:
|
||||
More information about `remove()` can be found <a href='https://docs.python.org/3.6/tutorial/datastructures.html' target='_blank' rel='nofollow'>here</a>
|
||||
|
||||
|
116
client/src/pages/guide/english/python/list-sort-method/index.md
Normal file
116
client/src/pages/guide/english/python/list-sort-method/index.md
Normal file
@ -0,0 +1,116 @@
|
||||
---
|
||||
title: List Sort Method
|
||||
---
|
||||
## List Sort Method
|
||||
|
||||
Python lists have a built-in ```sort()``` method that modifies the list in-place and a ```sorted()``` built-in function that builds a new sorted list from an iterable.
|
||||
|
||||
list.sort(key=…, reverse=[True/False])
|
||||
|
||||
### Parameters
|
||||
|
||||
There are two optional parameters to this method
|
||||
<br><br>
|
||||
<i>key</i> - The input value for the key parameter should be a function that takes a single argument and returns a value used for comparisons to sort the items in the list
|
||||
<br><br>
|
||||
<i>reverse=[value]</i>
|
||||
<br>
|
||||
<i>value=True</i> : Sorts the items in the list in descending order
|
||||
<br>
|
||||
<i>value=False</i> : Sorts the items in the list in ascending order. This is considered the default value.
|
||||
<br><br>
|
||||
Please note that the `sort()` method does not return any value. It modifies the original list.
|
||||
|
||||
### Example Usage
|
||||
|
||||
```py
|
||||
a = [4, 2, 5, 3, 1]
|
||||
a.sort()
|
||||
print a # prints [1, 2, 3, 4, 5]
|
||||
|
||||
b = ['free', 'code', 'camp']
|
||||
b.sort()
|
||||
print b # prints ['camp', 'code', 'free']
|
||||
```
|
||||
|
||||
Consider an example with the <b>reverse</b> parameter
|
||||
|
||||
```py
|
||||
a = [4, 2, 5, 3, 1]
|
||||
|
||||
#Sorts the list in descending order
|
||||
a.sort(reverse=True)
|
||||
|
||||
print a # prints [5, 4, 3, 2, 1]
|
||||
```
|
||||
|
||||
If you want to sort the list based on your own function, then use the <b>key</b> parameter.
|
||||
<br>Here is an example to sort the strings in the list by length, in ascending order
|
||||
|
||||
```py
|
||||
a = ["hello", "hi", "hey"]
|
||||
|
||||
#The built-in len() function is given as an input to key parameter to sort the strings by length
|
||||
a.sort(key = len)
|
||||
|
||||
print a # prints ['hi', 'hey', 'hello']
|
||||
```
|
||||
|
||||
Here is another example, where the list contains tuples(name, age). <br>The usage below shows how to sort the list by age, in ascending order.
|
||||
|
||||
```py
|
||||
#Consider the second element in the tuple for sorting
|
||||
>>> def compareByAge(element):
|
||||
... return element[1]
|
||||
|
||||
b = [('Adam', 20), ('Rahman', 30), ('Rahul', 25)]
|
||||
|
||||
#Sort the list by age
|
||||
b.sort(key = compareByAge)
|
||||
|
||||
#Output
|
||||
print b # prints [('Adam', 20), ('Rahul', 25), ('Rahman', 30)]
|
||||
```
|
||||
|
||||
### Sorting Basics
|
||||
|
||||
A simple ascending sort is very easy -- just call the sorted() function. It returns a new sorted list:
|
||||
|
||||
```python
|
||||
>>> sorted([5, 2, 3, 1, 4])
|
||||
[1, 2, 3, 4, 5]
|
||||
```
|
||||
You can also use the list.sort() method of a list. It modifies the list in-place (and returns None to avoid confusion). Usually it's less convenient than sorted() - but if you don't need the original list, it's slightly more efficient.
|
||||
|
||||
```python
|
||||
>>> a = [5, 2, 3, 1, 4]
|
||||
>>> a.sort()
|
||||
>>> a
|
||||
[1, 2, 3, 4, 5]
|
||||
```
|
||||
Another difference is that the list.sort() method is only defined for lists. In contrast, the sorted() function accepts any iterable.
|
||||
|
||||
```python
|
||||
>>> sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'})
|
||||
[1, 2, 3, 4, 5]
|
||||
```
|
||||
#### Implementation Details
|
||||
|
||||
If one wants to know details about the implementation of the sort function, the algorithm, and the time complexity, etc., refer <a href='http://svn.python.org/projects/python/trunk/Objects/listsort.txt' target='_blank' rel='nofollow'>here</a>. In brief, sort function uses TimSort algorithm, which according to Python Developers, is :-
|
||||
>an adaptive, stable, natural mergesort, modestly called
|
||||
timsort (hey, I earned it <wink>). It has supernatural performance on many
|
||||
kinds of partially ordered arrays (less than lg(N!) comparisons needed, and
|
||||
as few as N-1), yet as fast as Python's previous highly tuned samplesort
|
||||
hybrid on random arrays.
|
||||
|
||||
#### sort() Parameters
|
||||
By default, sort() doesn't require any extra parameters. However, it has two optional parameters:
|
||||
* reverse - If true, the sorted list is reversed (or sorted in Descending order)
|
||||
* key - function that serves as a key for the sort comparison
|
||||
|
||||
#### More Information:
|
||||
More information about ```sort()``` can be found <a href='https://docs.python.org/3/library/functions.html#sorted' target='_blank' rel='nofollow'>here</a>
|
||||
|
||||
More information about sort() and sorted() can be found <a href='https://docs.python.org/3.6/tutorial/datastructures.html' target='_blank' rel='nofollow'>here</a>
|
||||
|
||||
More information about sort() and sorted() can be found <a href='https://docs.python.org/3.6/tutorial/datastructures.html' target='_blank' rel='nofollow'>here</a>.
|
47
client/src/pages/guide/english/python/max-function/index.md
Normal file
47
client/src/pages/guide/english/python/max-function/index.md
Normal file
@ -0,0 +1,47 @@
|
||||
---
|
||||
title: Python Max Function
|
||||
---
|
||||
`max()` is a built-in function in Python 3\. It returns the largest item in an iterable or the largest of two or more arguments.
|
||||
|
||||
## Arguments
|
||||
|
||||
This function takes two or more numbers or any kind of iterable as an argument. While giving an iterable as an argument we must make sure that all the elements in the iterable are of the same type. This means that we cannot pass a list which has both string and integer values stored in it.
|
||||
|
||||
Valid Arguments:
|
||||
|
||||
max(2, 3)
|
||||
max([1, 2, 3])
|
||||
max('a', 'b', 'c')
|
||||
|
||||
Invalid Arguments:
|
||||
|
||||
max(2, 'a')
|
||||
max([1, 2, 3, 'a'])
|
||||
max([])
|
||||
|
||||
## Return Value
|
||||
|
||||
The largest item in the iterable is returned. If two or more positional arguments are provided, the largest of the positional arguments is returned. If the iterable is empty and default is not provided, a `ValueError` is raised.
|
||||
|
||||
## Code Sample
|
||||
|
||||
print(max(2, 3)) # Returns 3 as 3 is the largest of the two values
|
||||
print(max(2, 3, 23)) # Returns 23 as 23 is the largest of all the values
|
||||
|
||||
list1 = [1, 2, 4, 5, 54]
|
||||
print(max(list1)) # Returns 54 as 54 is the largest value in the list
|
||||
|
||||
list2 = ['a', 'b', 'c' ]
|
||||
print(max(list2)) # Returns 'c' as 'c' is the largest in the list in alphabetical order
|
||||
|
||||
list3 = [1, 2, 'abc', 'xyz']
|
||||
print(max(list3)) # Gives TypeError as values in the list are of different type
|
||||
|
||||
#Fix the TypeError mentioned above first before moving on to next step
|
||||
|
||||
list4 = []
|
||||
print(max(list4)) # Gives ValueError as the argument is empty
|
||||
|
||||
 <a href='https://repl.it/CVok' target='_blank' rel='nofollow'>Run Code</a>
|
||||
|
||||
<a href='https://docs.python.org/3/library/functions.html#max' target='_blank' rel='nofollow'>Official Docs</a>
|
48
client/src/pages/guide/english/python/min-function/index.md
Normal file
48
client/src/pages/guide/english/python/min-function/index.md
Normal file
@ -0,0 +1,48 @@
|
||||
---
|
||||
title: Python Min Function
|
||||
---
|
||||
`min()` is a built-in function in Python 3\. It returns the smallest item in an iterable or the smallest of two or more arguments.
|
||||
|
||||
## Arguments
|
||||
|
||||
This function takes two or more numbers or any kind of iterable as an argument. While giving an iterable as an argument we must make sure that all the elements in the iterable are of the same type. This means that we cannot pass a list which has both string and integer values stored in it.
|
||||
|
||||
Valid Arguments:
|
||||
|
||||
min(2, 3)
|
||||
min([1, 2, 3])
|
||||
min('a', 'b', 'c')
|
||||
|
||||
Invalid Arguments:
|
||||
|
||||
min(2, 'a')
|
||||
min([1, 2, 3, 'a'])
|
||||
min([])
|
||||
|
||||
## Return Value
|
||||
|
||||
The smallest item in the iterable is returned. If two or more positional arguments are provided, the smallest of the positional arguments
|
||||
is returned. If the iterable is empty and default is not provided, a ValueError is raised.
|
||||
|
||||
## Code Sample
|
||||
|
||||
print(min(2, 3)) # Returns 2 as 2 is the smallest of the two values
|
||||
print(min(2, 3, -1)) # Returns -1 as -1 is the smallest of the two values
|
||||
|
||||
list1 = [1, 2, 4, 5, -54]
|
||||
print(min(list1)) # Returns -54 as -54 is the smallest value in the list
|
||||
|
||||
list2 = ['a', 'b', 'c' ]
|
||||
print(min(list2)) # Returns 'a' as 'a' is the smallest in the list in alphabetical order
|
||||
|
||||
list3 = [1, 2, 'abc', 'xyz']
|
||||
print(min(list3)) # Gives TypeError as values in the list are of different type
|
||||
|
||||
#Fix the TypeError mentioned above first before moving on to next step
|
||||
|
||||
list4 = []
|
||||
print(min(list4)) # Gives ValueError as the argument is empty
|
||||
|
||||
 <a href='https://repl.it/CVir/4' target='_blank' rel='nofollow'>Run Code</a>
|
||||
|
||||
<a href='https://docs.python.org/3/library/functions.html#min' target='_blank' rel='nofollow'>Official Docs</a>
|
@ -0,0 +1,8 @@
|
||||
---
|
||||
title: Python More Built in Types
|
||||
---
|
||||
The following sections describe the standard types that are built into the interpreter.
|
||||
|
||||
The principal built-in types are numerics, sequences, mappings, classes, instances and exceptions.
|
||||
|
||||
Some collection classes are mutable. The methods that add, subtract, or rearrange their members in place, and don’t return a specific item, never return the collection instance itself but None.
|
@ -0,0 +1,67 @@
|
||||
---
|
||||
title: Python Mutability and Variable Assignments
|
||||
---
|
||||
> Every object has an identity, a type and a value. An object's identity never changes once it has been created; you may think of it as the object's address in memory. <a href='https://docs.python.org/3/reference/datamodel.html#data-model' target='_blank' rel='nofollow'>source</a>
|
||||
|
||||
Once an `object` is created, the type and identity can't be changed. Whether or not the object's value(s) can change after creation determines if the object is mutable (can change) or immutable (can't change).
|
||||
|
||||
So far we have learned about a few types of objects and their subclasses: `string`s and numeric (integer, floating point, complex, and boolean) objects. All of these are **immutable** objects.
|
||||
|
||||
This concept might be confusing at first because what good is an object if you can't modify it. What makes these objects usable is the ability to assign and reassign variables. Functions and operators can return new objects that can be assigned to variables.
|
||||
|
||||
Using the built-in <a href='https://docs.python.org/3/library/functions.html#id' target='_blank' rel='nofollow'>id function</a>, which returns the identity of an object, we can see how this works.
|
||||
|
||||
Here are a few things to keep in mind:
|
||||
|
||||
* Assigning a variable does not mean that _variable_ is the _object_. We used very specific language noting that _assignment statements_ **bind** a **name** (identifier) to an _object_. Variables can be reassigned:
|
||||
|
||||
`python
|
||||
|
||||
> > > a = 1 # Bind a to an object.
|
||||
> > > id(a)
|
||||
> > > 140355241530152
|
||||
> > > a = 2 # Rebind a to another object.
|
||||
> > > id(a)
|
||||
> > > 140355241530128
|
||||
> > > `
|
||||
|
||||
* Assigning two different variables to _immutable objects_ with the same value may result (not guaranteed) in them being bound to the same _object_
|
||||
|
||||
`python
|
||||
|
||||
> > > a = 1
|
||||
> > > b = 1
|
||||
> > > id(a)
|
||||
> > > 140355241530152
|
||||
> > > id(b) # In this case a and b are bound to the same object.
|
||||
> > > 140355241530152
|
||||
> > > `
|
||||
|
||||
* Assigning two different variables to _imutable objects_ with different values will always result in them being bound to different _objects_:
|
||||
|
||||
`python
|
||||
|
||||
> > > a = 1
|
||||
> > > b = 2
|
||||
> > > id(a)
|
||||
> > > 140355241530152
|
||||
> > > id(b) # a and b are bound to different objects.
|
||||
> > > 140355241530128
|
||||
> > > `
|
||||
|
||||
* Reassigning variables does not change the original object, it binds them to a different object.
|
||||
|
||||
`python
|
||||
|
||||
> > > a = 1
|
||||
> > > b = 1
|
||||
> > > id(a)
|
||||
> > > 140355241530152
|
||||
> > > id(b)
|
||||
> > > 140355241530152
|
||||
> > > a = 2
|
||||
> > > id(a) # a is rebound to a different object.
|
||||
> > > 140355241530128
|
||||
> > > id(b) # b is still bound to the original object.
|
||||
> > > 140355241530152
|
||||
> > > `
|
@ -0,0 +1,24 @@
|
||||
---
|
||||
title: Python Name Binding and Aliasing Functions
|
||||
---
|
||||
A function definition introduces the function name in the current symbol table. The value of the function name has a type that is recognized by the interpreter as a user-defined function.
|
||||
|
||||
>>> something = 1
|
||||
>>> type(something)
|
||||
<type 'int'>
|
||||
>>> def something():
|
||||
... pass
|
||||
...
|
||||
>>> type(something)
|
||||
<type 'function'>
|
||||
>>> something = []
|
||||
>>> type(something)
|
||||
<type 'list'>
|
||||
|
||||
This value can be assigned to another name which can then also be used as a function. This serves as a general renaming mechanism:
|
||||
|
||||
>>> fib
|
||||
<function fib at 10042ed0>
|
||||
>>> f = fib
|
||||
>>> f(100)
|
||||
0 1 1 2 3 5 8 13 21 34 55 89
|
134
client/src/pages/guide/english/python/nested-functions/index.md
Normal file
134
client/src/pages/guide/english/python/nested-functions/index.md
Normal file
@ -0,0 +1,134 @@
|
||||
---
|
||||
title: Nested Functions in Python
|
||||
---
|
||||
|
||||
### Namespaces
|
||||
|
||||
A function’s parameters, plus any variables that are bound (by assignment or by other binding statements, such as def) in the function body, make up the function’s local namespace, also known as local scope. Each of these variables is known as a local variable of the function.
|
||||
|
||||
Variables that are not local are known as global variables (in the absence of nested function definitions, which we’ll discuss shortly). Global variables are attributes of the module object, as covered in "Attributes of module objects" on page 140. Whenever a function’s local variable has the same name as a global variable, that name, within the function body, refers to the local variable, not the global one. We express this by saying that the local variable hides the global variable of the same name throughout the function body.
|
||||
|
||||
### The global statement
|
||||
|
||||
By default, any variable that is bound within a function body is a local variable of the function. If a function needs to rebind some global variables, the first
|
||||
statement of the function must be:
|
||||
|
||||
global identifiers
|
||||
|
||||
where identifiers is one or more identifiers separated by commas (,). The identifiers listed in a global statement refer to the global variables (i.e., attributes of the module object) that the function needs to rebind. For example, the function counter that we saw in "Other attributes of function objects" on page 73 could be implemented using global and a global variable, rather than an attribute of the function object:
|
||||
|
||||
_count = 0
|
||||
def counter():
|
||||
global _count
|
||||
_count += 1
|
||||
return _count
|
||||
|
||||
Without the global statement, the counter function would raise an UnboundLocal-Error exception because _count would then be an uninitialized (unbound) local variable. While the global statement enables this kind of programming, this style is often inelegant and unadvisable. As I mentioned earlier, when you want to group together some state and some behavior, the object-oriented mechanisms covered in Chapter 5 are usually best.
|
||||
|
||||
Don’t use global if the function body just uses a global variable (including mutating the object bound to that variable if the object is mutable). Use a global statement only if the function body rebinds a global variable (generally by assigning to the variable’s name). As a matter of style, don’t use global unless it’s strictly necessary, as its presence will cause readers of your program to assume the statement is there for some useful purpose. In particular, never use global except as the first statement in a function body.
|
||||
|
||||
{mospagebreak title=Nested functions and nested scopes}
|
||||
|
||||
A def statement within a function body defines a nested function, and the function whose body includes the def is known as an outer function to the nested one. Code in a nested function’s body may access (but not rebind) local variables of an outer function, also known as free variables of the nested function.
|
||||
|
||||
The simplest way to let a nested function access a value is often not to rely on nested scopes, but rather to explicitly pass that value as one of the function’s arguments. If necessary, the argument’s value can be bound when the nested function is defined by using the value as the default for an optional argument. For example:
|
||||
|
||||
def percent1(a, b, c):
|
||||
def pc(x, total=a+b+c): return (x*100.0) / total
|
||||
print "Percentages are:", pc(a), pc(b), pc(c)
|
||||
|
||||
Here’s the same functionality using nested scopes:
|
||||
|
||||
def percent2(a, b, c):
|
||||
def pc(x): return (x*100.0) / (a+b+c)
|
||||
print "Percentages are:", pc(a), pc(b), pc(c)
|
||||
|
||||
In this specific case, percent1 has a tiny advantage: the computation of a+b+c happens only once, while percent2′s inner function pc repeats the computation three times. However, if the outer function rebinds its local variables between calls to the nested function, repeating the computation can be necessary. It’s therefore advisable to be aware of both approaches, and choose the most appropriate one case by case.
|
||||
|
||||
A nested function that accesses values from outer local variables is also known as a closure. The following example shows how to build a closure:
|
||||
|
||||
def make_adder(augend):
|
||||
def add(addend):
|
||||
return addend+augend
|
||||
return add
|
||||
|
||||
Closures are an exception to the general rule that the object-oriented mechanisms covered in Chapter 5 are the best way to bundle together data and code. When you need specifically to construct callable objects, with some parameters fixed at object construction time, closures can be simpler and more effective than classes. For example, the result of make_adder(7) is a function that accepts a single argument and adds 7 to that argument. An outer function that returns a closure is a "factory" for members of a family of functions distinguished by some parameters, such as the value of argument augend in the previous example, and may often help you avoid code duplication.
|
||||
|
||||
### lambda Expressions
|
||||
|
||||
If a function body is a single return expression statement, you may choose to replace the function with the special lambda expression form:
|
||||
|
||||
lambda parameters: expression
|
||||
|
||||
A lambda expression is the anonymous equivalent of a normal function whose body is a single return statement. Note that the lambda syntax does not use the return keyword. You can use a lambda expression wherever you could use a reference to a function. lambda can sometimes be handy when you want to use a simple function as an argument or return value. Here’s an example that uses a lambda expression as an argument to the built-in filter function (covered in filter on page 161):
|
||||
|
||||
aList = [1, 2, 3, 4, 5, 6, 7, 8, 9]
|
||||
low = 3
|
||||
high = 7
|
||||
filter(lambda x, l=low,
|
||||
h=high: h>x>l, aList) # returns: [4, 5, 6]
|
||||
|
||||
As an alternative, you can always use a local def statement that gives the function object a name. You can then use this name as the argument or return value. Here’s the same filter example using a local def statement:
|
||||
|
||||
aList = [1, 2, 3, 4, 5, 6, 7, 8, 9]
|
||||
low = 3
|
||||
high = 7
|
||||
def within_bounds(value, l=low, h=high):
|
||||
return h>value>l
|
||||
filter(within_bounds, aList) # returns: [4, 5, 6]
|
||||
|
||||
While lambda can occasionally be useful, many Python users prefer def, which is more general, and may make your code more readable if you choose a reasonable name for the function.
|
||||
|
||||
{mospagebreak title=Generators}
|
||||
|
||||
When the body of a function contains one or more occurrences of the keyword yield, the function is known as a generator. When you call a generator, the function body does not execute. Instead, calling the generator returns a special iterator object that wraps the function body, its local variables (including its parameters), and the current point of execution, which is initially the start of the function.
|
||||
|
||||
When the next method of this iterator object is called, the function body executes up to the next yield statement, which takes the form:
|
||||
|
||||
yield expression
|
||||
|
||||
When a yield statement executes, the function execution is "frozen," with current point of execution and local variables intact, and the expression following yield is returned as the result of the next method. When next is called again, execution of the function body resumes where it left off, again up to the next yield statement. If the function body ends, or executes a return statement, the iterator raises a StopIteration exception to indicate that the iteration is finished. return statements in a generator cannot contain expressions.
|
||||
|
||||
A generator is a very handy way to build an iterator. Since the most common way to use an iterator is to loop on it with a for statement, you typically call a generator like this:
|
||||
|
||||
for avariable in somegenerator(arguments):
|
||||
|
||||
For example, say that you want a sequence of numbers counting up from 1 to N and then down to 1 again. A generator can help:
|
||||
|
||||
def updown(N):
|
||||
for x in xrange(1, N): yield x
|
||||
for x in xrange(N, 0, -1): yield x
|
||||
for i in updown(3):
|
||||
print i # prints: 1 2 3 2 1
|
||||
|
||||
Here is a generator that works somewhat like the built-in xrange function, but returns a sequence of floating-point values instead of a sequence of integers:
|
||||
|
||||
def frange(start, stop, step=1.0):
|
||||
while start < stop:
|
||||
yield start
|
||||
start += step
|
||||
|
||||
This frange example is only somewhat like xrange because, for simplicity, it makes arguments start and stop mandatory, and silently assumes step is positive.
|
||||
|
||||
Generators are more flexible than functions that returns lists. A generator may build an unbounded iterator, meaning one that returns an infinite stream of results (to use only in loops that terminate by other means, e.g., via a break statement). Further, a generator-built iterator performs lazy evaluation: the iterator computes each successive item only when and if needed, just in time, while the equivalent function does all computations in advance and may require large amounts of memory to hold the results list. Therefore, if all you need is the ability to iterate on a computed sequence, it is often best to compute the sequence in a generator rather than in a function that returns a list. If the caller needs a list of all the items produced by some bounded generator G(arguments), the caller can simply use the following code:
|
||||
|
||||
resulting_list = list(G(arguments))
|
||||
|
||||
### Generator expressions
|
||||
|
||||
Python 2.4 introduces an even simpler way to code particularly simple generators: generator expressions, commonly known as genexps. The syntax of a genexp is just like that of a list comprehension (as covered in "List comprehensions" on page 67) except that a genexp is enclosed in parentheses (()) instead of brackets ([]); the semantics of a genexp are the same as those of the corresponding list comprehension, except that a genexp produces an iterator yielding one item at a time, while a list comprehension produces a list of all results in memory (therefore, using a genexp, when appropriate, saves memory). For example, to sum the squares of all single-digit integers, in any modern Python, you can code
|
||||
sum([x*x for x in xrange(10)]); in Python 2.4, you can express this functionality even better, coding it as sum(x*x for x in xrange(10)) (just the same, but omitting the brackets), and obtain exactly the same result while consuming less memory. Note that the parentheses that indicate the function call also "do double duty" and enclose the genexp (no need for extra parentheses).
|
||||
|
||||
{mospagebreak title=Generators in Python 2.5}
|
||||
|
||||
In Python 2.5, generators are further enhanced, with the possibility of receiving a value (or an exception) back from the caller as each yield executes. These advanced features allow generators in 2.5 to implement full-fledged co-routines, as explained at http://www.python.org/peps/pep-0342.html. The main change is that, in 2.5, yield is not a statement, but an expression, so it has a value. When a generator is resumed by calling its method next, the corresponding yield’s value is None. To pass a value x into some generator g (so that g receives x as the value of the yield on which it’s suspended), instead of calling g.next(), the caller calls g.send(x) (calling g.send(None) is just like calling g.next()). Also, a bare yield without arguments, in Python 2.5, becomes legal, and equivalent to yield None.
|
||||
|
||||
Other Python 2.5 enhancements to generators have to do with exceptions, and are covered in "Generator enhancements" on page 126.
|
||||
|
||||
### Recursion
|
||||
|
||||
Python supports recursion (i.e., a Python function can call itself), but there is a limit to how deep the recursion can be. By default, Python interrupts recursion and raises a RecursionLimitExceeded exception (covered in "Standard Exception Classes" on page 130) when it detects that the stack of recursive calls has gone over a depth of 1,000. You can change the recursion limit with function setrecursionlimit of module sys, covered in setrecursionlimit on page 171.
|
||||
|
||||
However, changing the recursion limit does not give you unlimited recursion; the absolute maximum limit depends on the platform on which your program is running, particularly on the underlying operating system and C runtime library, but it’s typically a few thousand levels. If recursive calls get too deep, your program crashes. Such runaway recursion, after a call to setrecursionlimit that exceeds the platform’s capabilities, is one of the very few ways a Python program can crash–really crash, hard, without the usual safety net of Python’s exception mechanisms. Therefore, be wary of trying to fix a program that is getting RecursionLimitExceeded exceptions by raising the recursion limit too high with setrecursionlimit. Most often, you’d be better advised to look for ways to remove the recursion or, more specifically, limit the depth of recursion that your program needs.
|
||||
|
||||
Readers who are familiar with Lisp, Scheme, or functional-programming languages must in particular be aware that Python does not implement the optimization of "tail-call elimination," which is so important in these languages. In Python, any call, recursive or not, has the same cost in terms of both time and memory space, dependent only on the number of arguments: the cost does not change, whether the call is a "tail-call" (meaning that the call is the last operation that the caller executes) or any other, nontail call.
|
@ -0,0 +1,43 @@
|
||||
---
|
||||
title: Python Numeric Operations
|
||||
---
|
||||
<a href='https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex' target='_blank' rel='nofollow'>Python Docs - Numeric Operations</a>
|
||||
|
||||
Python fully supports mixed arithmetic: when a binary arithmetic operator has operands of different numeric types, the operand with the "narrower" type is widened to that of the other, where integer is narrower than floating point, which is narrower than complex. Comparisons between numbers of mixed type use the same rule. <a href='https://docs.python.org/3/library/functions.html#abs' target='_blank' rel='nofollow'>2] The constructors int(), float(), and complex() can be used to produce numbers of a specific type.
|
||||
|
||||
All numeric types (except complex) support the following operations, sorted by ascending priority (all numeric operations have a higher priority than comparison operations):
|
||||
|
||||
Operation | Results | Notes | Full documentation
|
||||
----------------- | --------------------------------------------------------------------------- | ------ | -----------------------------------------------------------------------
|
||||
`x + y` | sum of x and y | |
|
||||
`x - y` | difference of x and y | |
|
||||
`x * y` | product of x and y | |
|
||||
`x / y` | quotient of x and y | |
|
||||
`x // y` | floored quotient of x and y | (1) |
|
||||
`x % y` | remainder of x / y | (2)
|
||||
`-x` | x negated | |
|
||||
`+x` | x unchanged | |
|
||||
`abs(x)` | absolute value or magnitude of x | | [`abs()`</a>
|
||||
`int(x)` | x converted to integer | (3)(6) | <a href='https://docs.python.org/3/library/functions.html#int' target='_blank' rel='nofollow'>`int()`</a>
|
||||
`float(x)` | x converted to floating point | (4)(6) | <a href='https://docs.python.org/3/library/functions.html#float' target='_blank' rel='nofollow'>`float()`</a>
|
||||
`complex(re, im)` | a complex number with real part re, imaginary part im. im defaults to zero. | (6) | <a href='https://docs.python.org/3/library/functions.html#complex' target='_blank' rel='nofollow'>`complex()`</a>
|
||||
`c.conjugate()` | conjugate of the complex number c | |
|
||||
`divmod(x, y)` | the pair (x // y, x % y) | (2) | <a href='https://docs.python.org/3/library/functions.html#divmod' target='_blank' rel='nofollow'>`divmod()`</a>
|
||||
`pow(x, y)` | x to the power y | (5) | <a href='https://docs.python.org/3/library/functions.html#pow' target='_blank' rel='nofollow'>`pow()`</a>
|
||||
`x ** y` | x to the power y | (5)
|
||||
|
||||
**Notes:**
|
||||
|
||||
1. Also referred to as integer division. The resultant value is a whole integer, though the result's type is not necessarily int. The result is always rounded towards minus infinity: `1//2` is `0`, `(-1)//2` is `-1`, `1//(-2)` is `-1`, and `(-1)//(-2)` is `0`.
|
||||
|
||||
2. Not for complex numbers. Instead convert to floats using `abs()` if appropriate.
|
||||
|
||||
3. Conversion from floating point to integer may round or truncate as in C; see functions <a href='https://docs.python.org/3/library/math.html#math.floor' target='_blank' rel='nofollow'>`math.floor()`</a> and <a href='https://docs.python.org/3/library/math.html#math.ceil' target='_blank' rel='nofollow'>`math.ceil()`</a> for well- defined conversions.
|
||||
|
||||
4. `float` also accepts the strings `“nan”` and `“inf”` with an optional prefix `“+”` or `“-”` for Not a Number (NaN) and positive or negative infinity.
|
||||
|
||||
5. Python defines `pow(0, 0)` and `0 ** 0` to be `1`, as is common for programming languages.
|
||||
|
||||
6. The numeric literals accepted include the digits 0 to 9 or any Unicode equivalent (code points with the `Nd` property).
|
||||
|
||||
> See <a href='http://www.unicode.org/Public/8.0.0/ucd/extracted/DerivedNumericType.txt' target='_blank' rel='nofollow'>Unicode Derived Numeric Type</a> for a complete list of code points with the `Nd` property.
|
17
client/src/pages/guide/english/python/numeric-types/index.md
Normal file
17
client/src/pages/guide/english/python/numeric-types/index.md
Normal file
@ -0,0 +1,17 @@
|
||||
---
|
||||
title: Python Numeric Types
|
||||
---
|
||||
The <a href='https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex' target='_blank' rel='nofollow'>numeric types</a> for Python are:
|
||||
|
||||
* integers (`int`)
|
||||
* floating point numbers (`float`)
|
||||
* <a href='https://docs.python.org/3/library/functions.html#float' target='_blank' rel='nofollow'>constructor</a>
|
||||
* complex numbers
|
||||
* <a href='https://docs.python.org/3/library/functions.html#complex' target='_blank' rel='nofollow'>constructor</a>
|
||||
|
||||
The standard library adds numeric types for
|
||||
|
||||
* <a href='https://docs.python.org/3/library/fractions.html#module-fractions' target='_blank' rel='nofollow'>fractions</a>
|
||||
* <a href='https://docs.python.org/3/library/decimal.html#module-decimal' target='_blank' rel='nofollow'>decimals</a>
|
||||
|
||||
Numeric objects are created from literals or as the result of functions and operators. The syntax for numeric literals is well <a href='https://docs.python.org/3/reference/lexical_analysis.html#numeric-literals' target='_blank' rel='nofollow'>documented</a>.
|
@ -0,0 +1,15 @@
|
||||
---
|
||||
title: Classes
|
||||
---
|
||||
## Classes
|
||||
|
||||
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/area-of-a-parallelogram/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
|
||||
|
||||
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
|
||||
|
||||
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
|
||||
|
||||
#### More Information:
|
||||
<!-- Please add any articles you think might be helpful to read before writing the article -->
|
||||
|
||||
|
@ -0,0 +1,15 @@
|
||||
---
|
||||
title: Constructors
|
||||
---
|
||||
## Constructors
|
||||
|
||||
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/area-of-a-parallelogram/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
|
||||
|
||||
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
|
||||
|
||||
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
|
||||
|
||||
#### More Information:
|
||||
<!-- Please add any articles you think might be helpful to read before writing the article -->
|
||||
|
||||
|
@ -0,0 +1,15 @@
|
||||
---
|
||||
title: Python Object Oriented Programming
|
||||
---
|
||||
## Python Object Oriented Programming
|
||||
|
||||
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/area-of-a-parallelogram/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
|
||||
|
||||
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
|
||||
|
||||
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
|
||||
|
||||
#### More Information:
|
||||
<!-- Please add any articles you think might be helpful to read before writing the article -->
|
||||
|
||||
|
@ -0,0 +1,15 @@
|
||||
---
|
||||
title: Inheritance
|
||||
---
|
||||
## Inheritance
|
||||
|
||||
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/area-of-a-parallelogram/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
|
||||
|
||||
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
|
||||
|
||||
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
|
||||
|
||||
#### More Information:
|
||||
<!-- Please add any articles you think might be helpful to read before writing the article -->
|
||||
|
||||
|
@ -0,0 +1,15 @@
|
||||
---
|
||||
title: Methods
|
||||
---
|
||||
## Methods
|
||||
|
||||
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/area-of-a-parallelogram/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
|
||||
|
||||
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
|
||||
|
||||
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
|
||||
|
||||
#### More Information:
|
||||
<!-- Please add any articles you think might be helpful to read before writing the article -->
|
||||
|
||||
|
@ -0,0 +1,15 @@
|
||||
---
|
||||
title: Operator Overloading
|
||||
---
|
||||
## Operator Overloading
|
||||
|
||||
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/area-of-a-parallelogram/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
|
||||
|
||||
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
|
||||
|
||||
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
|
||||
|
||||
#### More Information:
|
||||
<!-- Please add any articles you think might be helpful to read before writing the article -->
|
||||
|
||||
|
@ -0,0 +1,15 @@
|
||||
---
|
||||
title: Special Comparison Methods
|
||||
---
|
||||
## Special Comparison Methods
|
||||
|
||||
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/area-of-a-parallelogram/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
|
||||
|
||||
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
|
||||
|
||||
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
|
||||
|
||||
#### More Information:
|
||||
<!-- Please add any articles you think might be helpful to read before writing the article -->
|
||||
|
||||
|
@ -0,0 +1,15 @@
|
||||
---
|
||||
title: Special Formatting Methods
|
||||
---
|
||||
## Special Formatting Methods
|
||||
|
||||
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/area-of-a-parallelogram/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
|
||||
|
||||
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
|
||||
|
||||
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
|
||||
|
||||
#### More Information:
|
||||
<!-- Please add any articles you think might be helpful to read before writing the article -->
|
||||
|
||||
|
@ -0,0 +1,15 @@
|
||||
---
|
||||
title: Special Iteration Methods
|
||||
---
|
||||
## Special Iteration Methods
|
||||
|
||||
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/area-of-a-parallelogram/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
|
||||
|
||||
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
|
||||
|
||||
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
|
||||
|
||||
#### More Information:
|
||||
<!-- Please add any articles you think might be helpful to read before writing the article -->
|
||||
|
||||
|
@ -0,0 +1,15 @@
|
||||
---
|
||||
title: Static Variables
|
||||
---
|
||||
## Static Variables
|
||||
|
||||
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/area-of-a-parallelogram/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
|
||||
|
||||
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
|
||||
|
||||
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
|
||||
|
||||
#### More Information:
|
||||
<!-- Please add any articles you think might be helpful to read before writing the article -->
|
||||
|
||||
|
@ -0,0 +1,14 @@
|
||||
---
|
||||
title: Python Parenthesis for Boolean Operations
|
||||
---
|
||||
Just as in math, parenthesis can be used to override order of operations:
|
||||
|
||||
>>> not True or True
|
||||
True
|
||||
>>> not (True or True)
|
||||
False
|
||||
|
||||
>>> True or False and False
|
||||
True
|
||||
>>> (True or False) and False
|
||||
False
|
24
client/src/pages/guide/english/python/powxy/index.md
Normal file
24
client/src/pages/guide/english/python/powxy/index.md
Normal file
@ -0,0 +1,24 @@
|
||||
---
|
||||
title: Python Powxy
|
||||
---
|
||||
`pow(x, y, z)` is a built-in function in Python 3 to calculate `x` to the power `y`, and if `z` is present, returns `x` to the power `y` [modulo](https://processing.org/reference/modulo.html) `z`.
|
||||
|
||||
## Arguments
|
||||
|
||||
The arguments must have numeric types.
|
||||
This function takes two arguments, `x` and `y`, as well as three, `x`, `y`, and`z`.
|
||||
If `z` is present, `x` and `y` must be of integer types, and y must be non-negative.
|
||||
|
||||
## Return
|
||||
|
||||
If `z` is present, it returns `x` to the power `y` modulo `z`. If only `x` and `y` are present, it returns `x` to the power `y` (same as `x**y`).
|
||||
|
||||
## Example
|
||||
|
||||
print(pow(2,4)) # prints 16
|
||||
print(pow(10,-2)) # prints 0.01
|
||||
print(pow(4,3,5)) # prints 4
|
||||
|
||||
 <a href='https://repl.it/CTGi' target='_blank' rel='nofollow'>Run Code</a>
|
||||
|
||||
<a href='https://docs.python.org/3/library/functions.html#pow' target='_blank' rel='nofollow'>Official Documentation</a>
|
@ -0,0 +1,44 @@
|
||||
---
|
||||
title: Python 2 vs Python 3
|
||||
---
|
||||
We aren't taking a side in the debate. If you are interested in knowing more about it for academic purposes, perhaps <a href='https://wiki.python.org/moin/Python2orPython3' target='_blank' rel='nofollow'>this</a> would intrigue you.
|
||||
|
||||
But, we cannot also be ignorant of the fact that there are two major flavors of Python out there. Why shoud you care, you ask? Because code written for one version of Python can result in a syntax error in another version of Python.
|
||||
|
||||
The following is a valid `print` statement in Python 2, but does not work on Python 3:
|
||||
|
||||
print "Hello World"
|
||||
|
||||
In Python 3, the same statement throws an error like this:
|
||||
|
||||
>>> print "hello"
|
||||
File "<stdin>", line 1
|
||||
print "hello"
|
||||
^
|
||||
SyntaxError: Missing parentheses in call to 'print'
|
||||
|
||||
In Python 2, “print” is treated as a statement rather than a function. There is no need to wrap the text you want to print in parentheses, although you can if you want.
|
||||
Python 3 explicitly treats “print” as a function, which means you have to pass the items you need to print to the function in parentheses in the standard way, or you will get a syntax error
|
||||
|
||||
Using the `print()` function is 'safe' in both Python 2 and 3:
|
||||
|
||||
```python
|
||||
print("Hello World")
|
||||
```
|
||||
|
||||
So, the only question you need to concern yourself with right now; is which one you should pick. Python 2 currently has its End Of Life date set to 2020. Meaning regular bugfixes are not guaranteed going forward and yes, it takes time to even get familiar with most common aspects with either Python; and your time is important. So, invest your time and effort wisely!
|
||||
|
||||
Both Python 2 and Python 3 are cool. Most Linux and macOS distributions come pre-installed with Python 2 as the default version of Python. And Python 3 was born out of the insatiable quest for more readable and more beautiful language constructs.
|
||||
|
||||
The only question you need to concern yourself with right now is, which one you should pick? Yes, it takes time to even get familiar with the most common aspects with either version Python, and your time is important, so invest your time and effort wisely!
|
||||
|
||||
If you are new to Python, you should pick Python 3\. Python 2 will <a href='https://www.python.org/dev/peps/pep-0373/#release-schedule' target='_blank' rel='nofollow'>not</a>be supported past 2020\.
|
||||
While Python 2 is well-supported and popular, most common libraries and frameworks in Python prefer Python 3\. Django officially <a href='https://docs.djangoproject.com/en/1.9/faq/install/#faq-python-version-support' target='_blank' rel='nofollow'>recommends</a> Python 3\. Flask and all its dependencies are also <a href='http://flask.pocoo.org/docs/0.10/python3/#python3-support' target='_blank' rel='nofollow'>supported</a> on Python 3.
|
||||
|
||||
This article uses Python 3 to set up the web-frameworks in your development environment. But before that, you need to ensure you have Python 3 and know how to use it!
|
||||
|
||||
|
||||
|
||||
#### More Information:
|
||||
|
||||
- <a href='https://wiki.python.org/moin/Python2orPython3' target='_blank' rel='nofollow'>Additional Reference</a>
|
@ -0,0 +1,79 @@
|
||||
---
|
||||
title: Python List Comprehensions
|
||||
---
|
||||
## List Comprehensions
|
||||
|
||||
List comprehensions are a simple way to create and populate a list in python.
|
||||
|
||||
Here is an example for-loop that can be replaced with a list comprehension. This code will create a list of numbers that correspond to the numbers in ```my_starting_list``` multiplied by 7.
|
||||
|
||||
```
|
||||
my_starting_list = [1, 2, 3, 4, 5, 6, 7, 8]
|
||||
my_new_list = []
|
||||
|
||||
for item in my_starting_list:
|
||||
my_new_list.append(item * 7)
|
||||
```
|
||||
|
||||
When this code is run, the final value of my_new_list is:
|
||||
```[7, 14, 21, 28, 35, 42, 49, 56]```
|
||||
|
||||
A developer using list comprehensions could achieve the same result using the following list comprehension:
|
||||
|
||||
```
|
||||
my_starting_list = [1, 2, 3, 4, 5, 6, 7, 8]
|
||||
|
||||
my_new_list = [item * 7 for item in my_starting_list]
|
||||
```
|
||||
|
||||
When this code is run, the value of my_new_list will be the same as above:
|
||||
```[7, 14, 21, 28, 35, 42, 49, 56]```
|
||||
|
||||
Follow this form to create a list comprehension:
|
||||
|
||||
``` my_list = [{operation with input n} for n in {python iterable}]```
|
||||
|
||||
Replace ```{operation with input n}``` with however you want to change the item returned from the iterable. The above example uses ```n * 7``` but the operation can be as simple or as complex as necessary.
|
||||
|
||||
Replace ```{python iterable}``` with any iterable. [Sequence types](https://guide.freecodecamp.org/python/sequence-types) will be most common. A list was used in the above example, but tuples and ranges are also common.
|
||||
|
||||
## List Comprehensions with Conditionals
|
||||
|
||||
The flow of control in list comprehensions can be controlled using conditionals. For exmaple:
|
||||
|
||||
```
|
||||
only_even_list = [i for i in range(13) if i%2==0]
|
||||
```
|
||||
|
||||
This is equivalent to the following loop:
|
||||
|
||||
```
|
||||
only_even_list = list()
|
||||
for i in range(13):
|
||||
if i%2 == 0:
|
||||
only_even_list.append(i)
|
||||
```
|
||||
|
||||
List comprehension can also contain nested if conditions. Consider the following loop:
|
||||
```
|
||||
divisible = list()
|
||||
for i in range(50):
|
||||
if i%2 == 0:
|
||||
if i%3 == 0:
|
||||
divisible.append(i)
|
||||
```
|
||||
using list comprehension this can be written as:
|
||||
```
|
||||
divisible = [i for i in range(50) if i%2==0 if i%3==0]
|
||||
```
|
||||
|
||||
If-Else statement can also be used along with list comprehension.
|
||||
```
|
||||
list_1 = [i if i%2==0 else i*-1 for i in range(10)]
|
||||
```
|
||||
|
||||
#### More Information:
|
||||
[Python For Loops](https://guide.freecodecamp.org/python/for-loop-statements)
|
||||
|
||||
[Python Lists](https://guide.freecodecamp.org/python/learn-about-python-lists)
|
||||
|
@ -0,0 +1,60 @@
|
||||
---
|
||||
title: Python Resources
|
||||
---
|
||||
## Tutorials
|
||||
|
||||
* <a href='https://docs.python.org/3/tutorial/' target='_blank' rel='nofollow'>Python Official Tutorials</a>
|
||||
* <a href='https://python-guide.readthedocs.org/en/latest/' target='_blank' rel='nofollow'>The Hitchhiker's Guide to Python</a>
|
||||
* <a href='https://developers.google.com/edu/python/' target='_blank' rel='nofollow'>Google Python Class</a>
|
||||
* <a href='http://learnpythonthehardway.org/book/' target='_blank' rel='nofollow'>Learn Python the Hard Way</a>
|
||||
* <a href='http://www.greenteapress.com/thinkpython/html/index.html' target='_blank' rel='nofollow'>Think Python</a>
|
||||
* <a href='https://learnxinyminutes.com/docs/python/' target='_blank' rel='nofollow'>Learn Python in X minutes</a>
|
||||
* <a href='https://learnxinyminutes.com/docs/python3/' target='_blank' rel='nofollow'>Learn Python 3 in X minutes</a>
|
||||
* <a href='http://www.diveintopython3.net/' target='_blank' rel='nofollow'>Dive into Python 3</a>
|
||||
* <a href='http://www.fullstackpython.com/' target='_blank' rel='nofollow'>Full Stack Python</a>
|
||||
* <a href='https://automatetheboringstuff.com/' target='_blank' rel='nofollow'>Automate the Boring Stuff with Python</a>
|
||||
* <a href='https://repl.it/languages/python3' target='_blank' rel='nofollow'>Python REPL in Browser</a>
|
||||
* <a href='http://pythontutor.com/' target='_blank' rel='nofollow'>Visual Python Code Walkthrough</a>
|
||||
* <a href='https://www.codecademy.com/learn/python' target='_blank' rel='nofollow'>Codecademy Python</a>
|
||||
* <a href='http://interactivepython.org/runestone/static/thinkcspy/index.html' target='_blank' rel='nofollow'>How to Think Like a Computer Scientist</a> - Interactive textbook that teaches programming with Python
|
||||
* <a href='https://www.edx.org/course/introduction-computer-science-mitx-6-00-1x-8' target='_blank' rel='nofollow'>Introduction to Computer Science and Programming Using Python</a> (MIT)
|
||||
* <a href='https://www.edx.org/course/cs-all-introduction-computer-science-harveymuddx-cs005x-0' target='_blank' rel='nofollow'>CS for All: Introduction to Computer Science & Python Programming</a>
|
||||
* <a href='https://www.packtpub.com/packt/free-ebook/learning-python' target='_blank' rel='nofollow'>Learning Python</a> - Free ebook
|
||||
* <a href='http://newcoder.io/' target='_blank' rel='nofollow'>New Coder</a> - Tutorials/challenges to take you from newbie to actual coder.
|
||||
* <a href='https://inventwithpython.com/' target='_blank' rel='nofollow'>Invent with Python</a> (plus two other books by the Automate the Boring Stuff guy)
|
||||
* <a href='http://interactivepython.org/runestone/static/pythonds/index.html' target='_blank' rel='nofollow'>Problem Solving with Algorithms and Data Structures Using Python</a>
|
||||
* <a href='https://github.com/faif/python-patterns' target='_blank' rel='nofollow'>Python Design Patterns</a>
|
||||
* <a href='https://www.djangoproject.com/start/' target='_blank' rel='nofollow'>Django Getting Started Tutorial</a>
|
||||
* <a href='http://chimera.labs.oreilly.com/books/1234000000754/index.html' target='_blank' rel='nofollow'>Test-Driven Development with Python</a>
|
||||
* <a href='http://www.tangowithdjango.com/' target='_blank' rel='nofollow'>Tango with Django</a>
|
||||
* <a href='http://tutorial.djangogirls.org/en/' target='_blank' rel='nofollow'>Django Girls' Tutorial</a> - Build a blog
|
||||
* <a href='http://www.marinamele.com/taskbuster-django-tutorial' target='_blank' rel='nofollow'>TaskBuster Django Tutorial</a> - Build a Django project from scratch
|
||||
* <a href='http://www.tutorialspoint.com/python/'>Tutorials Point - Python</a>
|
||||
* <a href='https://pythonprogramming.net' target='_blank' rel='nofollow'> Set of Starter Projects with Videos </a> - From the basics onward.
|
||||
|
||||
## Challenges
|
||||
|
||||
* <a href='https://github.com/gregmalcolm/python_koans' target='_blank' rel='nofollow'>Python Koans</a>
|
||||
* <a href='http://exercism.io/languages/python' target='_blank' rel='nofollow'>Exercism Python Challenges</a>
|
||||
* <a href='http://codingbat.com/python' target='_blank' rel='nofollow'>CodingBat Python Challenges</a>
|
||||
* <a href='http://www.learnpython.org/' target='_blank' rel='nofollow'>Learn Python Interactively</a>
|
||||
* <a href='http://projecteuler.net/' target='_blank' rel='nofollow'>Project Euler</a>
|
||||
* <a href='http://rosalind.info/problems/locations/' target='_blank' rel='nofollow'>Rosalind Python Bio-informatics Problems</a>
|
||||
* <a href='https://github.com/mshang/python-elevator-challenge' target='_blank' rel='nofollow'>Python Elevator Challenge</a>
|
||||
* <a href='https://coderbyte.com/' target='_blank' rel='nofollow'>CoderByte Challenges</a>
|
||||
* <a href='https://checkio.org' target='_blank' rel='nofollow'>CheckiO</a> - the game for coders
|
||||
* <a href='http://www.codeabbey.com/' target='_blank' rel='nofollow'>CodeAbbey</a>
|
||||
* <a href='https://hackerrank.com/domains/python/py-introduction'>HackerRank - Python Challenges</a>
|
||||
|
||||
## Community
|
||||
|
||||
* <a href='https://github.com/vinta/awesome-python' target='_blank' rel='nofollow'>Awesome Python</a>
|
||||
* <a href='https://www.reddit.com/r/python' target='_blank' rel='nofollow'>/r/Python</a>
|
||||
* <a href='https://www.reddit.com/r/learnpython' target='_blank' rel='nofollow'>/r/LearnPython</a>
|
||||
* <a href='http://planetpython.org/' target='_blank' rel='nofollow'>Planet Python</a>
|
||||
* <a href='http://www.pyladies.com/' target='_blank' rel='nofollow'>PyLadies</a>
|
||||
* <a href='https://djangogirls.org/' target='_blank' rel='nofollow'>DjangoGirls</a>
|
||||
|
||||
## Tools:
|
||||
|
||||
* <a href='https://www.jetbrains.com/pycharm-edu/' target='_blank' rel='nofollow'>PyCharm Edu</a> - a free educational version of PyCharm that comes with tutorials to teach you Python and the ability to download more.
|
@ -0,0 +1,21 @@
|
||||
---
|
||||
title: Range Method
|
||||
---
|
||||
# Range Function
|
||||
If you do need to iterate over a sequence of numbers, the built-in function range() comes in handy. It generates arithmetic progressions:
|
||||
|
||||
#### Example Usage
|
||||
```py
|
||||
for i in range(5):
|
||||
print(i)
|
||||
```
|
||||
|
||||
#### Output
|
||||
```
|
||||
0
|
||||
1
|
||||
2
|
||||
3
|
||||
4
|
||||
```
|
||||
|
@ -0,0 +1,102 @@
|
||||
---
|
||||
title: REST APIs with Falcon
|
||||
---
|
||||
|
||||
|
||||
## Introduction
|
||||
|
||||
RESTful APIs are a major component of any well-architected stack, and Python happens to have some brilliant frameworks for quickly composing APIs. One of these frameworks is called [Falcon](https://falconframework.org) - and it's great! Essentially a microframework, it ships with a sizable number of advantages:
|
||||
|
||||
1. It's fast. Really fast. Check out the benchmarks [here](https://falconframework.org/#sectionBenchmarks).
|
||||
|
||||
2. HTTP Resources are defined as classes, with class methods being used for different REST operations on these resources. This helps maintaining a clean codebase.
|
||||
|
||||
3. It's quite extensible - check out [this section](https://github.com/falconry/falcon/wiki/Complementary-Packages) on their wiki, to get a feel for it.
|
||||
|
||||
4. It's based on WSGI - the Pythonic standard for web apps - so it works with Python 2.6, 2.7, and 3.3+. And if you need more performance, run it using PyPy!
|
||||
|
||||
|
||||
## Getting started
|
||||
|
||||
First, let's prepare our environment. Personally, it's always great to work in virtual environments - you can use `virtualenv`, `virtualenvwrapper` or `venv`. Next, install Falcon using `pip`: `pip install falcon`.
|
||||
|
||||
We're going to develop a small sample API that does very basic time-zone manipulations for us. It will display the current time in UTC, as well as the corresponding epoch time. To that end, we'll grab a nifty library called `arrow`: `pip install arrow`.
|
||||
|
||||
You can find the finished sample at [https://github.com/rudimk/freecodecamp-guides-rest-api-falcon](https://github.com/rudimk/freecodecamp-guides-rest-api-falcon).
|
||||
|
||||
## Resources
|
||||
|
||||
Think of a resource as an entity that your API needs to manipulate. In our case, the best resource would be a `Timestamp`. Our routing would typically be something like this:
|
||||
|
||||
```
|
||||
GET /timestamp
|
||||
```
|
||||
|
||||
Here, `GET` is the HTTP verb used to call this endpoint, and `/timestamp` is the URL itself. Now that we've gotten this bit out of the way, let's create a module!
|
||||
|
||||
`$ touch timestamp.py`
|
||||
|
||||
Time to import the Falcon library:
|
||||
|
||||
```python
|
||||
|
||||
import json
|
||||
|
||||
import falcon
|
||||
|
||||
import arrow
|
||||
|
||||
```
|
||||
|
||||
Note we've also import the `json` package and the `arrow` library. Now, let's define a class for our resource:
|
||||
|
||||
```python
|
||||
|
||||
class Timestamp(object):
|
||||
|
||||
def on_get(self, req, resp):
|
||||
payload = {}
|
||||
payload['utc'] = arrow.utcnow().format('YYYY-MM-DD HH:mm:SS')
|
||||
payload['unix'] = arrow.utcnow().timestamp
|
||||
|
||||
resp.body = json.dumps(payload)
|
||||
resp.status = falcon.HTTP_200
|
||||
|
||||
```
|
||||
|
||||
Let's go through this snippet. We've defined a `Timestamp` class, and defined a class method called `on_get` - this function tells Falcon that when a `GET` request is issued to an endpoint for this resource, run the `on_get` function and provide the request and response objects as parameters. After that, it's smooth sailing - we create an empty dictionary, fill it up with the current UTC and UNIX timestamps, convert it to JSON and attach it to the response object.
|
||||
|
||||
Pretty simple, right? But sadly, that's not all. We now need to create a Falcon server and hook up the resource class we've just defined to an actual endpoint.
|
||||
|
||||
`$ touch app.py`
|
||||
|
||||
Now, add the code below:
|
||||
|
||||
```python
|
||||
|
||||
import falcon
|
||||
|
||||
from timestamp import Timestamp
|
||||
|
||||
api = application = falcon.API()
|
||||
|
||||
timestamp = Timestamp()
|
||||
|
||||
api.add_route('/timestamp', timestamp)
|
||||
|
||||
```
|
||||
|
||||
Here, we've defined a Falcon API, and initialized an instance of the resource class we created earlier. Then, we've hooked up the `/timestamp` endpoint with the class instance - and now we're good to go! To test this API install `gunicorn`(`pip install gunicorn`), and run `gunicorn app`. Use Postman or simple `cURL` to test this:
|
||||
|
||||
```
|
||||
|
||||
$ curl http://localhost:8000/timestamp
|
||||
{"utc": "2017-10-20 06:03:14", "unix": 1508479437}
|
||||
|
||||
```
|
||||
|
||||
And that does it!
|
||||
|
||||
## Moving on
|
||||
|
||||
Once you've got the hang of Falcon, composing powerful RESTful APIs that interact with databases or messaging queues is very easy. Do check out the [Falcon docs](https://falcon.readthedocs.io/en/stable/index.html), as well as PyPI for interesting Falcon modules that keep popping up.
|
@ -0,0 +1,82 @@
|
||||
---
|
||||
title: Python Return Statement
|
||||
---
|
||||
<a href='https://docs.python.org/3/reference/simple_stmts.html#the-return-statement' target='_blank' rel='nofollow'>Python Docs</a>
|
||||
|
||||
All functions return a value when called.
|
||||
|
||||
If a return statement is followed by an expression list, that expression list is evaluated and the value is returned:
|
||||
|
||||
>>> def greater_than_1(n):
|
||||
... return n > 1
|
||||
...
|
||||
>>> print(greater_than_1(1))
|
||||
False
|
||||
>>> print(greater_than_1(2))
|
||||
True
|
||||
|
||||
If no expression list is specified, `None` is returned:
|
||||
|
||||
>>> def no_expression_list():
|
||||
... return # No return expression list.
|
||||
...
|
||||
>>> print(no_expression_list())
|
||||
None
|
||||
|
||||
If a return statement is reached during the execution of a function, the current function call is left at that point:
|
||||
|
||||
>>> def return_middle():
|
||||
... a = 1
|
||||
... return a
|
||||
... a = 2 # This assignment is never reached.
|
||||
...
|
||||
>>> print(return_middle())
|
||||
1
|
||||
|
||||
If there is no return statement the function returns None when it reaches the end:
|
||||
|
||||
>>> def no_return():
|
||||
... pass # No return statement.
|
||||
...
|
||||
>>> print(no_return())
|
||||
None
|
||||
|
||||
A single function can have multiple `return` statements. Execution of the function ends when one of these `return` statements is reached:
|
||||
|
||||
>>> def multiple_returns(n):
|
||||
... if(n):
|
||||
... return "First Return Statement"
|
||||
... else:
|
||||
... return "Second Return Statement"
|
||||
...
|
||||
>>> print(multiple_returns(True))
|
||||
First Return Statement
|
||||
>>> print(multiple_returns(False))
|
||||
Second Return Statement
|
||||
|
||||
A single function can return various types:
|
||||
|
||||
>>> def various_return_types(n):
|
||||
... if(n==1):
|
||||
... return "Hello World." # Return a string
|
||||
... elif(n==2):
|
||||
... return 42 # Return a value
|
||||
... else:
|
||||
... return True # Return a boolean
|
||||
...
|
||||
>>> print(various_return_types(1))
|
||||
Hello World.
|
||||
>>> print(various_return_types(2))
|
||||
42
|
||||
>>> print(various_return_types(3))
|
||||
True
|
||||
|
||||
It is even possible to have a single function return multiple values with only a single return:
|
||||
|
||||
>>> def return_two_values():
|
||||
... a = 40
|
||||
... b = 2
|
||||
... return a,b
|
||||
...
|
||||
>>> print("First value = %d, Second value = %d" %(return_two_values()))
|
||||
First value = 40, Second value = 2
|
@ -0,0 +1,22 @@
|
||||
---
|
||||
title: Python Sequence Types
|
||||
---
|
||||
These represent finite ordered sets indexed by non-negative numbers. The built-in function `len()` returns the number of items of a sequence. When the length of a sequence is `n`, the index set contains the numbers `0, 1, ..., n-1`. Item `i` of sequence a is selected by `a<a href='https://docs.python.org/3/reference/datamodel.html#the-standard-type-hierarchy' target='_blank' rel='nofollow'>i]`.
|
||||
|
||||
[Python Docs - Standard Type Hierarchy</a>
|
||||
|
||||
## More
|
||||
|
||||
* Built-in sequence types are:
|
||||
* `list`
|
||||
|
||||
* `tuple`
|
||||
* `range`
|
||||
* Built-in sequence types are iterable types (implement required `__iter__()` method).
|
||||
|
||||
* Operations:
|
||||
|
||||
* <a href='https://docs.python.org/3/library/stdtypes.html#common-sequence-operations' target='_blank' rel='nofollow'>Common Sequence Operations</a>
|
||||
|
||||
* <a href='https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types' target='_blank' rel='nofollow'>Mutable Sequence Types</a>
|
||||
* <a href='https://docs.python.org/3/library/stdtypes.html#immutable-sequence-types' target='_blank' rel='nofollow'>Immutable Sequence Types</a>
|
35
client/src/pages/guide/english/python/set-types/index.md
Normal file
35
client/src/pages/guide/english/python/set-types/index.md
Normal file
@ -0,0 +1,35 @@
|
||||
---
|
||||
title: Python Set Types
|
||||
---
|
||||
A set object is an unordered collection of distinct hashable objects. Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference.
|
||||
|
||||
<a href='https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset' target='_blank' rel='nofollow'>Python Docs - Set Types Set Frozenset</a>
|
||||
|
||||
**TODO: Explain hash/hashable**
|
||||
A hash table is a contiguous vector of records, whose slots come in three
|
||||
flavors:
|
||||
|
||||
1. Slots with key+value pairs. Call these citizens.
|
||||
2. Not-yet-used slots. Call these virgins.
|
||||
3. Slots that were once citizens, but whose key got deleted, and where
|
||||
another key+value pair hasn't yet overwritten the slot. Call these
|
||||
turds (that's the technical term <0.9 wink>).
|
||||
|
||||
Python resizes the table when the number of virgins falls below a third of
|
||||
the total number of slots. In the usual case, Python doubles the table size
|
||||
(up to a current maximum of 1,073,741,824 slots). However, if many
|
||||
deletions leave behind many turds, it's possible for the number of virgins
|
||||
to get very low despite that few citizens remain; in that case, Python
|
||||
actually shrinks the table (down to a current minimum of 4 slots).
|
||||
|
||||
To avoid thrashing when a mix of additions and deletions are made when the
|
||||
table is near a resize threshold, Python doesn't actually check the # of
|
||||
virgins after a delete (in effect, it assumes you'll soon be replacing the
|
||||
turds with citizens again). So, curiously enough, deleting a key *never*
|
||||
shrinks the table. A long sequence of deletes followed by an add may shrink
|
||||
it, though. A way to force possible shrinkage without adding a key is:
|
||||
|
||||
dict = dict.copy()
|
||||
|
||||
dict.copy() always returns a turd-free dictionary, of the smallest
|
||||
power-of-2 size that leaves at least a third of the slots virgin.
|
@ -0,0 +1,32 @@
|
||||
---
|
||||
title: Setting Up Python Web Framework Django and Flask
|
||||
---
|
||||
In this article, we shall be discussing how to install <a href='https://www.djangoproject.com/' target='_blank' rel='nofollow'>Django</a> and <a href='http://flask.pocoo.org/' target='_blank' rel='nofollow'>Flask</a> - two popular web frameworks written in Python.
|
||||
|
||||
Perhaps you are already familiar with the widespread usage and community support for Python; in web-development. You might as well be aware as to what a web framework is; and the options available for Python.
|
||||
|
||||
In case these assumptions are untrue, you might want to take a look at this <a>wiki article</a>. If you are all caught up, let's go ahread with setting up Python web frameworks in your local development machine.
|
||||
|
||||
But it would be unfair if we completely ignore the <a href='http://docs.python-guide.org/en/latest/starting/which-python/#the-state-of-python-2-vs-3' target='_blank' rel='nofollow'>Python 2 vs Python 3</a> debate.
|
||||
|
||||
## Wrapping Up
|
||||
|
||||
If you have already installed `pip` then simply:
|
||||
```
|
||||
$ pip install django
|
||||
```
|
||||
After installation it's complete we can create a new project:
|
||||
```
|
||||
$ django-admin startproject myproject
|
||||
$ cd myproject
|
||||
$ python manage.py runserver
|
||||
```
|
||||
Go to `http://localhost:8000`! :rocket:
|
||||
|
||||
We have successfully installed the web-framework of our need. However, it's not yet complete. Most web applications are content and data driven - so we need a data storage. Or, a Database, if you will.
|
||||
|
||||
In next article, we would be discussing how to install PostgreSQL and use it with our Python web application.
|
||||
|
||||
A point to ponder - we have been using `pip` heavily, but we have barely said anything about it. Well, for now, it's just a package manager like `npm`. It has some differences with `npm`; but, you don't need to worry about that now. If you are interested, do check out the <a href='http://pip-python3.readthedocs.org/en/latest/index.html' target='_blank' rel='nofollow'>official `pip` documentation</a>.
|
||||
|
||||
_If you have suggestions or questions, come join us on <a href='https://gitter.im/FreeCodeCamp/FreeCodeCamp' target='_blank' rel='nofollow'>gitter</a>_.
|
@ -0,0 +1,19 @@
|
||||
---
|
||||
title: Share File Using Python SimpleHTTPserver
|
||||
---
|
||||
## The steps need to follow for sending the file.
|
||||
|
||||
1. Make sure both the computers connected through same network via LAN or WIFI.
|
||||
2. Open terminal in Ubuntu and make sure you have python installed in your PC.
|
||||
3. If not installed then install it by typing in terminal "sudo apt-get install python" without quotes.
|
||||
4. Goto the directory whose file you want to share by using cd(change directory) command.
|
||||
5. Type this command "python -m simpleHTTPserver" without quotes.
|
||||
6. Open new terminal and type ifconfig and find your IP address.
|
||||
|
||||
## Now in second computer
|
||||
|
||||
1. Open browser and type the ip address of first one.
|
||||
2. Don't forget to add port number at end of ip address..which by default is:8000
|
||||
|
||||
A page will open showing the Directory type structure and it will show all files from source pc.
|
||||
Now you can access all files.
|
@ -0,0 +1,21 @@
|
||||
---
|
||||
title: Sleep How Can I Make a Time Delay in Python
|
||||
---
|
||||
## Sleep How Can I Make a Time Delay in Python
|
||||
|
||||
The `time` module in the Python standard library contains the function `sleep()` which suspends a program for a given number of seconds.
|
||||
|
||||
Example:
|
||||
|
||||
```
|
||||
import time
|
||||
|
||||
for letter in 'hello, world!':
|
||||
print(letter)
|
||||
time.sleep(2) # sleep 2 seconds between each print
|
||||
```
|
||||
|
||||
Floating point numbers can be given as the argument to `sleep()` for more precise sleep times.
|
||||
|
||||
#### More Information:
|
||||
Time module <a href='https://docs.python.org/3/library/time.html#time.sleep' target='_blank' rel='nofollow'>documentation</a> on the sleep function.
|
@ -0,0 +1,48 @@
|
||||
---
|
||||
title: Python Slicestartstopstep
|
||||
---
|
||||
`slice(start:stop[:step])` is an object usually containing a portion of a sequence. A slice is created using the subscript notation, [] with colons between numbers when several are given, such as in variable_name[1:3:5].
|
||||
|
||||
## Arguments
|
||||
|
||||
This function can be used to slice tuples, arrays and lists.
|
||||
|
||||
The value of the `start` parameter (or None if not provided)
|
||||
|
||||
The value of the `stop` parameter (or last index of sequence)
|
||||
|
||||
The value of the `step` parameter (or None if not provided). It cannot be 0.
|
||||
|
||||
All three must be of integer type.
|
||||
|
||||
## Return
|
||||
|
||||
If only `stop` is provided, it generates portion of sequence from index `0` till `stop`.
|
||||
|
||||
If only `start` is provided, it generates portion of sequence after index `start` till last element.
|
||||
|
||||
If both `start` and `stop` are provided, it generates portion of sequence after index `start` till `stop`.
|
||||
|
||||
If all three `start`, `stop` and `step` are provided, it generates portion of sequence after index `start` till `stop` with increment of index `step`.
|
||||
|
||||
## Example
|
||||
|
||||
a = [1, 2, 3, 4, 5, 6, 7, 8]
|
||||
print(a[:5]) # prints [1, 2, 3, 4, 5]
|
||||
print(a[2:]) # prints [3, 4, 5, 6, 7, 8]
|
||||
print(a[2:5]) # prints [3, 4, 5]
|
||||
print(a[2:7:2]) # prints [3, 5, 7]
|
||||
|
||||
You can index the last index of a sequence by using `-1`:
|
||||
|
||||
a = [1, 2, 3, 4, 5, 6]
|
||||
print(a[-1]) # prints 6
|
||||
print(a[2:-1]) # prints [3, 4, 5]
|
||||
|
||||
You can flip a sequence by using the `[::-1]` slice notation:
|
||||
|
||||
a = [1, 2, 3, 4, 5, 6]
|
||||
print(a[::-1]) # prints [6, 5, 4, 3, 2, 1]
|
||||
|
||||
<a href='https://docs.python.org/3/library/functions.html#slice' target='_blank' rel='nofollow'>Official Documentation</a>
|
||||
 <a href='https://repl.it/CT5h' target='_blank' rel='nofollow'>Run Code</a>
|
@ -0,0 +1,31 @@
|
||||
---
|
||||
title: String Find Method
|
||||
---
|
||||
## String Find Method
|
||||
|
||||
There are two options for finding a substring within a string in Python, `find()` and `rfind()`.
|
||||
|
||||
Each will return the position that the substring is found at. The difference between the two is that `find()` returns the lowest position, and `rfind()` returns the highest position.
|
||||
|
||||
Optional start and end arguments can be provided to limit the search for the substring to within portions of the string.
|
||||
|
||||
Example:
|
||||
|
||||
```shell
|
||||
>>> string = "Don't you call me a mindless philosopher, you overweight glob of grease!"
|
||||
>>> string.find('you')
|
||||
6
|
||||
>>> string.rfind('you')
|
||||
42
|
||||
```
|
||||
If the substring is not found, -1 is returned.
|
||||
|
||||
```shell
|
||||
>>> string = "Don't you call me a mindless philosopher, you overweight glob of grease!"
|
||||
>>> string.find('you', 43) # find 'you' in string anywhere from position 43 to the end of the string
|
||||
-1
|
||||
```
|
||||
|
||||
More Information:
|
||||
|
||||
String methods <a href='https://docs.python.org/3/library/stdtypes.html#string-methods' target='_blank' rel='nofollow'>documentation</a>.
|
@ -0,0 +1,40 @@
|
||||
---
|
||||
title: String Join Method
|
||||
---
|
||||
## String Join Method
|
||||
|
||||
The `str.join(iterable)` method is used to join all elements in an `iterable` with a specified string ```str```.
|
||||
|
||||
`iterable`: All iterables of string. Could a list of strings, tuple of string or even a plain string.
|
||||
|
||||
#### Examples
|
||||
|
||||
1) Join a ist of strings with `":"`
|
||||
```python
|
||||
print ":".join(["freeCodeCamp", "is", "fun"])
|
||||
```
|
||||
Output
|
||||
```shell
|
||||
freeCodeCamp:is:fun
|
||||
```
|
||||
|
||||
2) Join a tuple of strings with `" and "`
|
||||
```python
|
||||
print " and ".join(["A", "B", "C"])
|
||||
```
|
||||
Output
|
||||
```shell
|
||||
A and B and C
|
||||
```
|
||||
|
||||
3) Insert a `" "` after every character in a string
|
||||
```python
|
||||
print " ".join("freeCodeCamp")
|
||||
```
|
||||
Output:
|
||||
```shell
|
||||
f r e e C o d e C a m p
|
||||
```
|
||||
|
||||
#### More Information:
|
||||
<a href='https://docs.python.org/2/library/stdtypes.html#str.join' target='_blank' rel='nofollow'>Python Documentation on String Join</a>
|
@ -0,0 +1,38 @@
|
||||
---
|
||||
title: String Replace Method
|
||||
---
|
||||
## String Replace Method
|
||||
|
||||
The `str.replace(old, new, max)` is used to replace the substring `old` with the string `new` for a total of `max` times. This method returns a new copy of the string with the replacement. The original string `str` is unchanged.
|
||||
|
||||
#### Examples
|
||||
|
||||
1. Replace all occurrences of `"is"` with `"WAS"`
|
||||
|
||||
```python
|
||||
string = "This is nice. This is good."
|
||||
newString = string.replace("is","WAS")
|
||||
print(newString)
|
||||
```
|
||||
|
||||
Output
|
||||
```python
|
||||
ThWAS WAS nice. ThWAS WAS good.
|
||||
```
|
||||
|
||||
2. Replace the first 2 occurrences of `"is"` with `"WAS"`
|
||||
|
||||
```python
|
||||
string = "This is nice. This is good."
|
||||
newString = string.replace("is","WAS", 2)
|
||||
print(newString)
|
||||
```
|
||||
|
||||
Output
|
||||
```python
|
||||
ThWAS WAS nice. This is good.
|
||||
```
|
||||
|
||||
#### More Information:
|
||||
Read more about string replacement in the <a href='https://docs.python.org/2/library/string.html#string.replace' target='_blank' rel='nofollow'>Python docs</a>
|
||||
|
@ -0,0 +1,71 @@
|
||||
---
|
||||
title: String Split Method
|
||||
---
|
||||
|
||||
The `split()` function is commonly used for string splitting in Python.
|
||||
|
||||
#### The `split()` method
|
||||
|
||||
Template: `string.split(separator, maxsplit)`
|
||||
|
||||
`separator`: The delimiter string. You split the string based on this character. For eg. it could be " ", ":", ";" etc
|
||||
|
||||
`maxsplit`: The number of times to split the string based on the `separator`. If not specified or -1, the string is split based on all occurrences of the `separator`
|
||||
|
||||
This method returns a list of substrings delimited by the `separator`
|
||||
|
||||
#### Examples
|
||||
|
||||
1) Split string on space: " "
|
||||
```python
|
||||
string = "freeCodeCamp is fun."
|
||||
print(string.split(" "))
|
||||
```
|
||||
Output:
|
||||
```python
|
||||
['freeCodeCamp', 'is', 'fun.']
|
||||
```
|
||||
|
||||
2) Split string on comma: ","
|
||||
```python
|
||||
string = "freeCodeCamp,is fun, and informative"
|
||||
print(string.split(","))
|
||||
```
|
||||
Output:
|
||||
```python
|
||||
['freeCodeCamp', 'is fun', ' and informative']
|
||||
```
|
||||
|
||||
3) No `separator` specified
|
||||
```python
|
||||
string = "freeCodeCamp is fun and informative"
|
||||
print(string.split())
|
||||
```
|
||||
Output:
|
||||
```python
|
||||
['freeCodeCamp', 'is', 'fun', 'and', 'informative']
|
||||
```
|
||||
Note: If no `separator` is specified, then the string is stripped of __all__ whitespace
|
||||
|
||||
```python
|
||||
string = "freeCodeCamp is fun and informative"
|
||||
print(string.split())
|
||||
```
|
||||
Output:
|
||||
```python
|
||||
['freeCodeCamp', 'is', 'fun', 'and', 'informative']
|
||||
```
|
||||
|
||||
3) Split string using `maxsplit`. Here we split the string on " " twice:
|
||||
```python
|
||||
string = "freeCodeCamp is fun and informative"
|
||||
print(string.split(" ", 2))
|
||||
```
|
||||
Output:
|
||||
```python
|
||||
['freeCodeCamp', 'is', 'fun and informative']
|
||||
```
|
||||
|
||||
#### More Information
|
||||
|
||||
Check out the <a href='https://docs.python.org/2/library/stdtypes.html#str.split' target='_blank' rel='nofollow'>Python docs on string splitting</a>
|
@ -0,0 +1,37 @@
|
||||
---
|
||||
title: String Strip Method
|
||||
---
|
||||
## String Strip Method
|
||||
|
||||
There are three options for stripping characters from a string in Python, `lstrip()`, `rstrip()` and `strip()`.
|
||||
|
||||
Each will return a copy of the string with characters removed, at from the beginning, the end or both beginning and end. If no arguments are given the default is to strip whitespace characters.
|
||||
|
||||
Example:
|
||||
|
||||
```py
|
||||
>>> string = ' Hello, World! '
|
||||
>>> strip_beginning = string.lstrip()
|
||||
>>> strip_beginning
|
||||
'Hello, World! '
|
||||
>>> strip_end = string.rstrip()
|
||||
>>> strip_end
|
||||
' Hello, World!'
|
||||
>>> strip_both = string.strip()
|
||||
>>> strip_both
|
||||
'Hello, World!'
|
||||
```
|
||||
|
||||
An optional argument can be provided as a string containing all characters you wish to strip.
|
||||
|
||||
```py
|
||||
>>> url = 'www.example.com/'
|
||||
>>> url.strip('w./')
|
||||
'example.com'
|
||||
```
|
||||
However, do notice that only the first `.` got stripped from the string. This is because the `strip` function only strips the argument characters that lie at the left or rightmost. Since w comes before the first `.` they get stripped together, whereas 'com' is present in the right end before the `.` after stripping `/`
|
||||
|
||||
#### More Information:
|
||||
<!-- Please add any articles you think might be helpful to read before writing the article -->
|
||||
|
||||
String methods <a href='https://docs.python.org/3/library/stdtypes.html#string-methods' target='_blank' rel='nofollow'>documentation</a>.
|
@ -0,0 +1,19 @@
|
||||
---
|
||||
title: Python Truth Value Testing
|
||||
---
|
||||
<a href='https://docs.python.org/3/library/stdtypes.html#truth-value-testing' target='_blank' rel='nofollow'>Python Docs - Truth Value Testing</a>
|
||||
|
||||
Any object can be tested for truth value, for use in an `if` or `while` condition or as operand of a Boolean operation like `and`, `or`, or `not`.
|
||||
|
||||
The following values are considered false:
|
||||
|
||||
* `None`
|
||||
* `False`
|
||||
* zero of any numeric type, for example, `0`, `0.0`, `0j`, `Decimal(0)`, `Fraction(0, 1)`.
|
||||
* any empty sequence, for example, `''`, `()`, `[]`, `set()`, `range(0)`.
|
||||
* any empty mapping, for example, `{}`.
|
||||
* instances of user-defined classes, if the class defines a `__bool__()` or `__len__()` method, when that method returns `False` or `0`.
|
||||
|
||||
All other values are considered true -- so objects of many types are always true.
|
||||
|
||||
Operations and built-in functions that have a Boolean result always return `0` or `False` for false and `1` or `True` for true, unless otherwise stated. (Important exception: the Boolean operations `or` and `and` always return one of their operands.)
|
36
client/src/pages/guide/english/python/using-pip/index.md
Normal file
36
client/src/pages/guide/english/python/using-pip/index.md
Normal file
@ -0,0 +1,36 @@
|
||||
---
|
||||
title: Python Using Pip
|
||||
---
|
||||
We have seen how to use `import` statements to `import` various modules and to use them in our programs. Python itself comes with several built-in modules, but the Python community has more to offer.
|
||||
|
||||
> It's the modules that makes python so powerful!
|
||||
|
||||
Third party modules add so much more functionality to Python. Now we would learn how to install these modules so that we can use those in our programs.
|
||||
|
||||
The simplest way is to use `pip`
|
||||
|
||||
pip install <module_name>
|
||||
|
||||
If you have used `npm`, then you can think of it as _npm_ of Python.
|
||||
|
||||
Side note: The difference is that with npm, `npm install` by default installs packages locally to a project, whereas `pip install` by default installs globally. To install modules locally, you need to create and activate what is called a [virtual environment](http://docs.python-guide.org/en/latest/dev/virtualenvs/), so `pip install` installs to the folder where that virtual environment is located, instead of globally (which may require administrator privileges).
|
||||
|
||||
Last time, in <a>`import-statements`</a> wiki we used `requests` module as an example. As it is a third party module we have to install it separately after installing python.
|
||||
|
||||
Installing it would be as simple as `pip install requests` . You can even pass various arguments along with it. The one that you'll come across more often is `--upgrade`. You can upgrade a python module by :
|
||||
|
||||
pip install <module_name> --upgrade
|
||||
|
||||
For example, to upgrade the requests module to its latest version would be as simple as `pip install requests --upgrade`.
|
||||
|
||||
Before using `pip`, you will need to install it (it's quite simple). You can install it from <a href='https://bootstrap.pypa.io/get-pip.py' target='_blank' rel='nofollow'>here</a>
|
||||
|
||||
Just click on the link. And save the file as`get-pip.py` _Please don't forget the `.py` extension._ And run it.
|
||||
|
||||
An alternative to using pip would be to try <a href='https://bootstrap.pypa.io/ez_setup.py' target='_blank' rel='nofollow'>`easy_install`</a>.
|
||||
|
||||
Using `easy_install` is also simple. The syntax is:
|
||||
|
||||
easy_install <module_name>
|
||||
|
||||
However, `pip` is more popular than using `easy_install`.
|
@ -0,0 +1,6 @@
|
||||
---
|
||||
title: Using Python for Web Development
|
||||
---
|
||||
Python is known for its beautiful syntax and ease of readability. This scripting language can be used for some quick-and-dirty prototyping of your idea of a web-app. It can also be used to build scalable and maintainable large web applications.
|
||||
|
||||
So let's get started with some web frameworks and learn how they help build web app on-hands. But before that, we would need to set-up the development environment by completing [installation of web frameworks in Python](https://guide.freecodecamp.org/python/setting-up-python-web-framework-django-and-flask).
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user