Python: Difference between revisions

From Halfface
Jump to navigation Jump to search
 
(18 intermediate revisions by the same user not shown)
Line 1: Line 1:
=links=
=version=
  http://docs.python.org/tutorial
Show python version
Reference
  python -V
  http://docs.python.org/ref/ref.html
=make an http request=
http://docs.python.org/library/
  import requests
 
  r =requests.get('https://halfface.se')
=basics=
  print(r.text)
 
print "Hello, World!"
command called print followed by one argument,which is "Hello, World!". (referred to as a string of characters, or string) Command and its arguments are collectively referred to as a statement,
 
print "2 + 2 is", 2 + 2
The first argument is the string "2 + 2 is" and the second argument is the mathematical expression 2 + 2, which is commonly referred to as an expression. each of the arguments separated by a comma
 
Print without spaces. flush buffers.
import sys
sys.stdout.write(character)
sys.stdout.flush()
 
sys.argv  arguments are passed to the script in the variable sys.argv
#          is used to start a comment
 
=Enable swedish keys åäö=
#!/usr/bin/python
# -*- coding: utf-8 -*-
 
=operations for numbers=
{| class="wikitable"
! Operation
! Symbol
! Example
|-
|Power (exponentiation)
| <code>**</code>
| <code>5 ** 2 == 25</code>
|-
|Multiplication
| <code>*</code>
|<code>2 * 3 == 6</code>
|-
|Division
| <code>/</code>
| <code>14 / 3 == 4</code>
|-
|Remainder (modulo)
| <code>%</code>
| <code>14 % 3 == 2</code>
|-
|Addition
| <code>+</code>
| <code>1 + 2 == 3</code>
|-
|Subtraction
| <code>-</code>
| <code>4 - 3 == 1</code>
|}
 
=userinput=
raw_input (returns a string)
user_reply = raw_input("Who goes there? ")
 
input (returns digits)
number = input("Type in a number: ")
type(number) (tells what a variable is.)
print "number is a", type(number)
=while loop=
print number interval. finish while loop with a ':' The while statement only affects the lines that are indented with whitespace.
start = input("Start number? ")
stop = input("Stop number? ")
a = start
while a < stop:
    print a
    a = a + 1
{| class="wikitable"
!operator
!function
|-
|<code><</code>
|less than
|-
|<code><=</code>
|less than or equal to
|-
|<code>></code>
|greater than
|-
|<code>>=</code>
|greater than or equal to
|-
|<code>==</code>
|equal
|-
|<code>!=</code>
|not equal
|-
|<code><></code>
|another way to say not equal (old style, not recommended)
|}
 
=if statment=
  if a > 5: 
    print a, ">", 5
  elif a <= 7:
    print a, "<=", 7
  else:
    print "Neither test was true"
 
# This Program Demonstrates the use of the == operator  # using numbers
print 5 == 6
false
=strings=
strings are impossible to change
 
<pre><nowiki>strings can be surrounded in a pair of matching triple-quotes: """ or '''. No newlines will be created.</nowiki></pre>
 
If we make the string literal a “raw” string, \n sequences are not converted to newlines,
raw = r"Hello\nWhat \
is happening"
print raw
Unicode strings
text = u'Hej på dig'
To convert a Unicode string into an 8-bit string
u"äöü".encode('utf-8')
Multi asignment
a, b = 0, 1
  print a, b
  0 1
 
=functions=
The key feature of this program is the def statement. def (short for define) starts a function definition. def is followed by the name of the function absolute_value. Next comes a '(' followed by the parameter n (n is passed from the program into the function when the function is called). The statements after the ':' are executed when the function is used. The statements continue until either the indented statements end or a return is encountered. The return statement returns a value back to the place where the function was called.
def absolute_value(n):
  if n < 0:
    n = -n
  return n
*The first statement of the function body can optionally be a string literal; this string literal is the function’s documentation string, or docstring. If there are more lines in the documentation string, the second line should be blank, visually separating the summary from the rest of the description.
*Print documentation. print function.__doc__
*The return statement returns with a value from a function.
* *name which receives a tuple containing the positional arguments beyond the formal parameter list.  (*name must occur before **name.)
* **name options to function, it receives a dictionary
Unpack argument list.
args = [3, 6]
range(*args)            # call with arguments unpacked from a list
[3, 4, 5]
Unpack argument dictionary.
d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
parrot(**d) # dictionaries can deliver keyword arguments with the **-operator:
 
 
=list=
list with more than one value.
which_one = input("What month (1-12)? ")
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
if 1 <= which_one <= 12:
  print "The month is", months[which_one - 1]
 
Print a whole list.
demolist = ["life", 42, "the universe", 6, "and", 7]
print "demolist = ",demolist
demolist =  ['life', 42, 'the universe', 6, 'and', 7]
 
b = a
makes b a reference to a.
b = a * 1
b = a[:]
copies b to a.
==list as stacks==
Last in First out.
stack = [3, 4, 5]
stack.append(6)
stack.pop()
==lists as queus==
from collections import deque
queue = deque(["Eric", "John", "Michael"])
queue.append("Terry")          # Terry arrives
queue.popleft()                # The first to arrive now leaves
==map==
 
map(function, sequence) calls function(item) for each of the sequence’s items and returns a list of the return values.
 
def cube(x): return x*x*x
map(cube, range(1, 11))
 
=list methods=
list.append(x) Add an item to the end of the list.
list.extend(L) Extend the list by appending all the items in the given list.
list.insert(i, x) Insert an item at a given position.  The first argument is the index of the element before which to insert.
list.remove(x) Remove the first item from the list whose value is x.
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.
list.index(x) Return the index in the list of the first item whose value is x.
list.count(x) Return the number of times x appears in the list.
list.sort() Sort the items of the list, in place.
list.reverse() Reverse the elements of the list.
 
=List comprehensions=
List comprehensions provide a concise way to create lists without resorting to use of map(), filter() and/or lambda. The resulting list definition tends often to be clearer than lists built using those constructs. Each list comprehension consists of an expression followed by a for clause, then zero or more for or if clauses.  The result will be a list resulting from evaluating the expression in the context of the for and if clauses which follow it.  If the expression would evaluate to a tuple, it must be parenthesized.
vec1 = [2, 4, 6]
vec2 = [4, 3, -9]
[x*y for x in vec1 for y in vec2]
 
Same things can be done with zip()
mat = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
zip(*mat)
 
=list=
 
{| class="wikitable"
!example
!explanation
|-
|<code>demolist[2]</code>
|accesses the element at index 2
|-
|<code>demolist[2] = 3</code>
|sets the element at index 2 to be 3
|-
|<code>del demolist[2]</code>
|removes the element at index 2
|-
|<code>len(demolist)</code>
|returns the length of <code>demolist</code>
|-
|<code>"value" in demolist</code>
|is ''True'' if <tt>"value"</tt> is an element in <code>demolist</code>
|-
|<code>"value" not in demolist</code>
|is ''True'' if <code>"value"</code> is not an element in <code>demolist</code>
|-
|<code>demolist.sort()</code>
|sorts <code>demolist</code>
|-
|itarable.sorted()
|sorts any itarble
|-
|<code>demolist.index("value")</code>
|returns the index of the first place that <code>"value"</code> occurs
|-
|<code>demolist.append("value")</code>
|adds an element <code>"value"</code> at the end of the list
|-
|<code>demolist.remove("value")</code>
|removes the first occurrence of value from <code>demolist</code> (same as <code>del demolist[demolist.index("value")]</code>)
|-
|<code>onetoten = range(1, 11)</code>
|-
|list[-1]
|Returns the last index
|-
|list[-2]
|Returns the second last index
|-
|things[4:7]
|Pick slice of list
|}
sum(sequence) Summarize a sequence
 
=functions=
ord()        Returns a character as a number.
chr(15)      Return number to character
repr()      Convert a integer to a string
int()        Convert a string to an integer.
float()      Convert a string to a float
eval()      Takes a string and returns type that python thinks it found
text.split(",")    converts a string into a list of strings. The string is split by whitespace by default or by the optional argument You can also add another argument that tells split() how many times the separator will be used to split the text.
round(_, 2)  Make the floating point into two decimals.
reversed()  Reverse contents.
 
=for loop=
in keyword. This tests whether or not a sequence contains a certain value.
demolist = ['life', 42, 'the universe', 6, 'and', 9, 'everything']
for item in demolist:
    print item
 
=break and continue Statements, and else Clauses on Loops=
break statement breaks out of the smallest enclosing for or while loop
continue statement continues with the next iteration of the loop.
else Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement.
=looping techniques=
Key and corresponding value can be retrieved at the same time
knights = {'gallahad': 'the pure', 'robin': 'the brave'}
  for k, v in knights.iteritems():
      print k, v
gallahad the pure
robin the brave
 
 
 
=looping trough sequence=
 
When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate() function.
for i, v in enumerate(['tic', 'tac', 'toe']):
    print i, v
0 tic
1 tac
2 toe
 
=dictionary=
=dictionary=
Add an empty dictonary called words
  dictionary = {"a": 99, "hello": "world"}
  words = {}
Create a list of keys in dictionary.
for x in words.keys():


Grabs the words in a dictionary.
=import=
Print meaning of word
Import functions.
print words[x]
  import $module
If name exist in dictionary, remove it.
=try:=
if name in words:
Exception handling. Example will fail because x is unset.
  del words[name]
 
=File IO=
# Write a file
out_file = open("test.txt", "w")
  out_file.write("This Text is going to out file\nLook at it and see!")
out_file.close()
# Read a file
in_file = open("test.txt", "r")
text = in_file.read()
in_file.close()
# Read file if it exists.
import os
filename = os.environ.get('PYTHONSTARTUP')
if filename and os.path.isfile(filename):
  execfile(filename)
 
=error handling=
  try:
  try:
number = int(raw_input("Enter a number: "))
  print(x)
  print "You entered:", number
  except:
  except ValueError:
  print("An exception occurred")
  print "That was not a number."
=sys.exit()=
 
exits and no stack traceback is printed.
Try handles error handling. If you didn't get a number ask for one.
=re=
 
Regular expression searching
=python configuration=
  ip = re.findall(r'[0-9]+(?:\.[0-9]+){3}', config_info)
How to configure python. Where should I put config file.
=join elements in list for other output=
import site
  print(', '.join(configured_ip_addresses))
site.getusersitepackages()
=for loop=
/home/user/.local/lib/python3.2/site-packages'
  fruits = ["apple", "banana", "cherry"]
 
  for x in fruits:
/home/user/.local/lib/python3.2/site-packages/usercustomize.py
  print(x)
/home/user/.local/lib/python3.2/site-packages/sitecustomize works in the
=range=
 
  for i in range(0,Loops,1):
=pass=
    print("Value")
The pass statement does nothing.
=reduce()=
reduce(function, sequence) returns a single value constructed by calling the binary function function on the first two items of the sequence, then on the result and the next item, and so on. For example, to compute the sum of the numbers
def add(x,y):
  print "x, y", x, y
  print "x+y ", x+y
  return x+y
reduce(add, range(1, 3))
x, y 1 2
x+y  3
x, y 3 3
x+y  6
6
=tuple,array=
  # Tuples may be nested: t = (1, 2, 3, 4, 5)
=set=
Python also includes a data type for sets. A set is an unordered collection with no duplicate elements.
print set('abracadabra')
set(['a', 'r', 'b', 'c', 'd'])
=operators=
a = set('abracadabra')
b = set('alacazam')
a                                  # unique letters in a
a - b                              # letters in a but not in b
a | b                              # letters in either a or b
a & b                              # letters in both a and b
a ^ b                              # letters in a or b but not both
=zip()=
To loop over two or more sequences at the same time, the entries can be paired with the zip() function.
format() exchange q and a with {0} and {1}
 
questions = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']
for q, a in zip(questions, answers):
    print 'What is your {0}?  It is {1}.'.format(q, a)
 
=modules=
A module is a file containing Python definitions and statements.
The file name is the module name with the suffix .py appended.
Within a module, the module’s name (as a string) is available as the value of the global variable __name__.
import fibo # import fibo.
This does not enter the names of the functions defined in fibo  directly in the current symbol table; it only enters the module name fibo there. Using the module name you can access the functions:
fibo.fib(1000)
If you intend to use a function often you can assign it to a local name:
fib = fibo.fib
A module can contain executable statements as well as function definitions. These statements are intended to initialize the module. Each module has its own private symbol table, which is used as the global symbol table by all functions defined in the module. Thus, the author of a module can use global variables in the module without worrying about accidental clashes with a user’s global variables. On the other hand, if you know what you are doing you can touch a module’s global variables with the same notation used to refer to its functions,
 
modname.itemname.
 
There is a variant of the import statement that imports names from a module directly into the importing module’s symbol table.  For example:
from fibo import fib, fib2  fib(500)
 
==The dir() Function==
 
The built-in function dir() is used to find out which names a module defines. It returns a sorted list of strings:
 
import fibo, sys
dir(fibo)
['__name__', 'fib', 'fib2']
lists all types of names: variables, modules, functions, etc.
dir()
dir() does not list the names of built-in functions and variables.  If you want a list of those, they are defined in the standard module __builtin__
dir(__builtin__)
 
=module examples=
command import loads a module
==Sleep==
  import time
time.sleep(secs)
==random==
import random
number = random.randrange(1, 100, 1)
==deepcopy==
To copy lists that contain lists use deepcopy
  import copy
c = copy.deepcopy(a)
=packages=
*Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name A.B designates a submodule named B in a package named A.
*The __init__.py files are required to make Python treat the directories as containing packages.
*When importing the package, Python searches through the directories on sys.path looking for the package subdirectory.
*__init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable
import sound.effects.echo
 
This loads the submodule sound.effects.echo.  It must be referenced with its full name.
 
from sound.effects import echo
 
An alternative way of importing the submodule. This also loads the submodule echo, and makes it available without its package prefix, so it can be used as follows:
echo.echofilter(input, output, delay=0.7, atten=4)
=import=
 
Importing * From a Package
=output formatting=


str() function is meant to return representations of values which are fairly human-readable.
=input=
  repr() is meant to generate representations which can be read by the interpreter
Read a value from prompt into variable number.
  str.rjust() method which right-justifies a string in a field of a given width by padding it with spaces on the left.
  number=int(input("Please give me a number? "))
str.ljust() left justify
=append=
str.center() center
Append values to grades
str(hello).zfill(5), which pads a numeric string on the left with zeros.
  grades.append(int(input("Please give me the grade? ")))
=format=
=format=
print '{} and {}'.format('spam', 'eggs') # replace first and second braces with respective word.
Use variable i input question string.
  print '{1} and {0}'.format('spam', 'eggs') # replace braces with word with new possition.
  sales = float(input("Please enter your sales from day {}".format(x)))
print pi with 48 decimals after ..
=round, number of decimals=
import math
  print(round(AverageGrades),1)
  print '{0:.48f}.'.format(math.pi)
=debug/trace=
formatting
  python -m trace --trace script.py
  {0:10} Passing an integer after the ':' will cause that field to be a minimum number of characters wide.
=hej=

Latest revision as of 09:18, 8 June 2023

version

Show python version

python -V

make an http request

import requests
r =requests.get('https://halfface.se')
print(r.text)

dictionary

dictionary = {"a": 99, "hello": "world"}

import

Import functions.

import $module

try:

Exception handling. Example will fail because x is unset.

try:
  print(x)
except:
  print("An exception occurred")

sys.exit()

exits and no stack traceback is printed.

re

Regular expression searching

ip = re.findall(r'[0-9]+(?:\.[0-9]+){3}', config_info)

join elements in list for other output

print(', '.join(configured_ip_addresses))

for loop

fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)

range

for i in range(0,Loops,1):
    print("Value")

input

Read a value from prompt into variable number.

number=int(input("Please give me a number? "))

append

Append values to grades

grades.append(int(input("Please give me the grade? ")))

format

Use variable i input question string.

sales = float(input("Please enter your sales from day {}".format(x)))

round, number of decimals

print(round(AverageGrades),1)

debug/trace

python -m trace --trace script.py