Pyhon Baisc: PYTHON FOR EVERYBODY
Table of contents:
- Chapter 1. Introduction
- Chapter 2. Variables
- Chapter 3. Conditional Execution
- Chapter 4. Functions
- Chapter 5. Iteration
- Chapter 6. Strings
- Chapter 7. Files
- Chapter 8. List
- Chapter 9. Dictionaries
- Chapter 10. Tuples
Introduction
Errors
In python, there are three general type of errors:
- Syntax errors
- Violated the “grammar” rules of python.
- Logic errors
- A mistake in the order of the statements.
- Semantic errors
- The program is perfectly correct but it does not do what you intended for it to do.
Debugging
- Reading
- Running
- Ruminating
- syntax
- runtime
- semantic
- retreating
Variables
Data Type
- String: str
- Integers: int
- Number with a decimal point: float
PS: Variable name cannot start with a number
Operation
-
Order of operations:
Python follows the order of operations, PEMDAS, (Parenthese, Exponentiation, Multiplication, Division, Addition, Substraction) -
Modulus Operator:
2
1
- String Operation:
100150
TestTestTest
Conditional Execution
Bools
- Boolean Expression: TRUE/FALSE
- Data Type: bool
Operation
- Logical Operator:
- and
- or
- not
Condition expression tables:
x != y | x is not equal to y |
x > y | x is greater than y |
x < y | x is less than y |
x >= y | x is greater than or equal to y |
x <= y | x is less than or equal to y |
x is y | x is the same as y |
x is not y | x is not the same as y |
x == y | x is equal to y |
Enter Fahrenhiet:123
50.55555555555556
Functions
A function is a named sequence of statements that performs a comptation.
Built-in function
- max: In a string, Z would be the largest one
- min: In a string, a space would be the smallest
- len: In a string, returns the # of characters
Conversion functions
- int
- Takes any value and converts it to an integer if it can
- It can convert floating-point values to integers but it does not round off
- It will chops off the fraction part
- float
- It converts integers and strings to floating-point numbers
- str
- It converts its argument to a string
Math functions
A ‘math’ module needs to be imported by using:
- A module contains the functions and variables defined in the module.
- To access one of the function, you have to specify the name of the module and the name of the function, separted by a dot
-3.010299956639812
0.644217687237691
0.7071067811865475
Random numbers
- random: (From random module)
- It returns a random float between 0.0 and 1.0 (including 0.0 but not 1.0)
- randint
- It takes the parameters ‘low’ and ‘high’ and returns an integer between ‘low’ and ‘high’
- choice
- It choose an element from a sequence at random
0.7305591062488854
0.8859907707980562
0.449918375542002
0.7643633082695483
0.42944509322878277
0.8951958910887714
0.3319489418362195
0.11402093233851263
0.7428676466169906
0.9881847290549769
8
7
3
1
The random module also provides functions to generate random values form continuous distributions inclusing “Gaussian”, “exponential”, “gamma” and a few more.
Define a new function
A function definition specifies the name of a new function and the sequence of statements that exceute when the function is called.
def
: It indicates that this is a function definition
I'm a lumberjack, and I am okay.
I sleep all night and I work all day.
- Defining a function also create a variable with the same name.
- The value of the function is a function object, which has type “function”
- Function can be used inside another function
- The statements inside the function do not get executed until the function is called
A function that can yeild a result is called fruitful functions; on the other hand, a function that can perform action but don’t return a value is called void functions.
- Void function might display something on the screen or have some other effects but they do not have a return value.
- If you try to assign the result from a void function to a variable, you will get a speial value called “None”
test
test
None
In order to return a result from a function, use “return
” statement.
8
Iteration
Loops
Python has three iteration/loops functions:
- if - looping with conditions
- for - looping through a know set of items
- while - loops until some condition becomes False
5
4
3
2
1
blast off
Endless Loop
The while True
statement creates an endless loops:
Strings
String literals in python are surrounded by either single quotation marks, or double quotation marks. 'hello'
is the same as "hello"
. Each string has its index. The expression in brackets is called an index. Index starts from 0 to n-1. n is the length of a string.
a
Getting the length of string using len()
:
6
a
Negative indices
Index can be expressed as a negative number:
'a'
'n'
Loops application
Use while loop to write a traversal:
0: b
1: a
2: n
3: a
4: n
5: a
Use for loop to write a traversal:
b
a
n
a
n
a
Use while loop to write a reverse traversal:
1: a
2: n
3: a
4: n
5: a
6: b
String slices
Selecting a slice is similar to selecting a character.
Monty
Python
The operator returns the part of the sting from the ‘n-th’ to ‘m-th’ character, including the first but excluding the last.
'ban'
'ana'
If the first index is greater than or equal to the second the result is an empty string.
''
The best you can do is create a new string that is a variation on the original:
Jello World!
Looping and counting
Using loop to count charactors:
1
2
3
The ‘in’ operator
True
False
String comparison
All right, bananas
String Methods
- There are string methods can be used
- dir: shows the available methods
- type: type of an object
str
['__add__',
'__class__',
'__contains__',
'__delattr__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getitem__',
'__getnewargs__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__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']
Help on method_descriptor:
capitalize(...)
S.capitalize() -> str
Return a capitalized version of S, i.e. make the first character
have upper case and the rest lower case.
Calling a method is similar to calling a function but the syntax is different:
- upper
- find
- strip
- lower
- startswith
- count
BANANA
2
4
'Here we go'
'have a nice day'
False
True
2
Parsing strings
this.is.test
Format operator
The format operator, %
, allows us to construct strings, replacing parts of the strings with the data stored in variables. %d
means that the second operand should be formatted as an integer:
'I have spotted 42 camels'
Other format operators, such as %g
is to format a floating-point number and %s
is to format a string:
'In 3 years, I have spotted 0.1 camels.'
Files
Use open()
Count each of the lines in a files:
If the file is relatively small compared to the size of your main memory, using the ‘read’ method on the file handle.
If the file is too large to fit in main memory, you should write your program to read the file in chunks using a for or while loop.
As the file processing programs get more complicated, you may want to structure your search loops using “continue”
- find() return -1 if the string was not found
- try/except for reading file program
writting files
To write a file, you have to open it with mode “w” as a second parameter:
<_io.TextIOWrapper name='output.txt' mode='w+' encoding='UTF-8'>
The ‘write’ method of the file handle object puts data into the file, returning the number of characters written.
18
This is test line
Close the file when writting is done.
Spaces, tabs, and newlines can be treated as a string by using ‘repr’
Without "repr":
1 2 3
4
With "repr":'1 2\t 3\n 4'
List
A list is a sequence of values (elements/items).
- In a string: values are characters
- In a list: values can be any type
- Example: [10, 20, 30, 40]
A list within another list is nested. A list that contains no elements is called an empty list.
Example:
- []
- [‘Spam’, 2.0, 5, [10,20]]
Here, 'Spam'
is string type; 2.0
is float type, 5
is integer; and [10,20]
is a list.
Functions can be used for list:
- len(): returns the number of elements in the list
- range(): returns a list of indices from 0 to n-1
Lists are mutable
['Cheddar', 'Edam', 'Gouda']
List operation
[1, 2, 3, 4, 5, 6]
[0, 0, 0, 0]
[1, 2, 3, 1, 2, 3, 1, 2, 3]
True
1
2
3
3
List slices
['b', 'c']
['a', 'b', 'c', 'd']
['a', 'b', 'c', 'd', 'e', 'f']
'f'
['a', 'b', 'c', 'd', 'e']
['a', 'x', 'y', 'd', 'e', 'f']
List methods
- append
- extend
- sort
['a', 'b', 'c', ['d', 'e']]
['a', 'b', 'c', 'd', 'e']
['a', 'b', 'c', 'd', 'e', 'f']
DONT USE t=t.sort()
! It will return “NONE” !!
Deleting elements
- pop - can save the deleted value
- del - Don’t need the removed value and know index
- remove - know elem,ent but not index
t: ['a', 'c']
x: b
['a']
['a', 'c']
sum()
can only be used when the elements are numbersmax()
,len()
, etc, can be used with lists of strings and other types
Enter a number:10
Average: 10.0
Enter a number:85
Average: 47.5
Enter a number:2
Average: 32.333333333333336
Enter a number:done
Lists and strings
Convert a string to a list of char:
- list
- split
['s', 'p', 'a', 'm']
['printing', 'for', 'the', 'frog']
frog
['spam', 'spam', 'spam']
Take a list of strings and concatenates the elements:
- join
'printing for the frog'
'printingforthefrog'
Parsing lines
- If two list are equivalent, they are not necessarily identical.
- If two list are identical, they are also equivalent.
Aliasing
True
Now, b is refering a. When b is changed, a is also changed.
[17, 2, 3]
In general, it is safter to avoid aliasing when you are working withmutable objects.
Dictionaries
- A dictionary is like a list
- The indices of a dictionary can be any type
- Dictionary: A mapping between a set of indices (which are called keys) and a set of values
- Key-value pair: the associationi of a key and a value
{}
The curly breakets, {}, represent an empty dictionary.
To add items to the dictionary, use square brackets:
The order of items in a dictionary isunpredictable.
{'one': 'uno', 'two': 'dos', 'three': 'tres', 'a': 'wha'}
Look up the corresponding values by keys:
wha
The len function works on dictionaries; it returns the number of key value pairs:
4
The “in” operator works on dictionaries; it tells you whether something appears as a key in the dictionary:
True
False
Use ‘values’ to see whether somehing appears as a value in a dictionary:
True
Dictionary as a set of counters
{'b': 1, 'r': 2, 'o': 2, 'n': 1, 't': 1, 's': 2, 'a': 1, 'u': 2}
Get
It takes a key and a default value. If the key appears in the dictionary. ‘get’ returns the corresponding value; otherwise it returns the default value.
100
None
Write a histogram loop
{'b': 1, 'r': 2, 'o': 2, 'n': 1, 't': 1, 's': 2, 'a': 1, 'u': 2}
Dictionaries and files
Looping and dictionaries
chuck 1
annie 42
jan 100
Using pattern
annie 42
jan 100
Make the keys in alphabetical order
['chuck', 'annie', 'jan']
annie 42
chuck 1
jan 100
Advanced text parsing (with punctuation)
- string method:
- lower
- punctuation
- translate
- fromstr
- replace the characters
- tostr
- with the character in the same position
- deletstr
- delete all charactors
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
To remove punctuation of a text:
Tuples
A tuple is a sequence of values much like a list. THe values stored in a tuple can be any type and they are indexed by integers.
- tuples are immutable
- tuples are also comparable and hashable
- tuples can be sorted and be used as key alues in Python dictionaries
- tuple is a comma-separated list of values
('a', 'b', 'c', 'd', 'e')
('a', 'b', 'c', 'd', 'e')
To create a tuple with a single element, a final comma must be included. Otherwise, python will treats (‘a’) as an expression with a string:
tuple
()
If the argument is a sequence (string, list, or tuple), the result of the call to tuple is a tuple with the elements of the swquence:
('l', 'u', 'p', 'i', 'n', 's')
Tuple cannot be modified:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-144-2cabaacd7cc5> in <module>()
----> 1 t[0]='A'
TypeError: 'tuple' object does not support item assignment
But tuple can be replaced by other tuple:
('A', 'u', 'p', 'i', 'n', 's')
Comparing tuples
- Decorate
- Sort
- Undercorate Sort a list of words from longest to shortest:
sorted on alphabet: ['yonder', 'window', 'what', 'soft', 'light', 'in', 'but', 'breaks']
sorted on length: [(6, 'yonder'), (6, 'window'), (6, 'breaks'), (5, 'light'), (4, 'what'), (4, 'soft'), (3, 'but'), (2, 'in')]
['yonder', 'window', 'breaks', 'light', 'what', 'soft', 'but', 'in']
Tuple assignment
It can be assigned to more than one variable at a time when the left side is a sequence
have
fun
have
fun
have
fun
Swap the values of two variables in a single statement:
before:
1
2
after:
2
1
Split an email address into a name&domain:
monty
python.org
Dictionaries have a method called “items
” that returns a list of tuples, where each tuple is akey-value pair:
[('a', 10), ('c', 22), ('b', 1)]
It can be sorted after using .items()
:
[('a', 10), ('b', 1), ('c', 22)]
Mutiple assignment with dictionaries:
key:a value:10
key:c value:22
key:b value: 1
- Lists are more common than tuples
- There are a few cases you might prefer tuples
- “return” statement
- it is sytactically simpler to create a tuple than a list
- use a sequence as a dictionary key
- you have to use an immutable type like a tuple or string
- passing a sequence as an argement to a function, using tuples reduces the potential for unexpected behavior
‘sort’, ‘sorted’, ‘reverse’, ‘reversed’ do work on tuples