Python: Difference between revisions

From Halfface
Jump to navigation Jump to search
 
(85 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)
 
=dictionary=
  print "Hello, World!"
  dictionary = {"a": 99, "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
=import=
=import=
command import loads a module
Import functions.
==Sleep==
import $module
import time
=try:=
time.sleep(secs)
Exception handling. Example will fail because x is unset.
==random==
  try:
  import random
  print(x)
number = random.randrange(1, 100, 1)
  except:
==deepcopy==
  print("An exception occurred")
To copy lists that contain lists use deepcopy
=sys.exit()=
  import copy
  exits and no stack traceback is printed.
c = copy.deepcopy(a)
=re=
 
Regular expression searching
=list=
  ip = re.findall(r'[0-9]+(?:\.[0-9]+){3}', config_info)
list with more than one value.
=join elements in list for other output=
which_one = input("What month (1-12)? ")
  print(', '.join(configured_ip_addresses))
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.
 
=operations=
 
{| 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>
|-
|<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
|}
=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.
 
=for loop=
=for loop=
  demolist = ['life', 42, 'the universe', 6, 'and', 9, 'everything']
  fruits = ["apple", "banana", "cherry"]
  for item in demolist:
  for x in fruits:
    print item
  print(x)
 
=range=
=break and continue Statements, and else Clauses on Loops=
  for i in range(0,Loops,1):
break statement breaks out of the smallest enclosing for or while loop
    print("Value")
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.
 
=dictionary=
Add an empty dictonary called words
words = {}
Create a list of keys in dictionary.
  for x in words.keys():
 
Grabs the words in a dictionary.
Print meaning of word
print words[x]
If name exist in dictionary, remove it.
if name in words:
  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:
number = int(raw_input("Enter a number: "))
  print "You entered:", number
except ValueError:
  print "That was not a number."
 
Try handles error handling. If you didn't get a number ask for one.
 
=python configuration=
How to configure python. Where should I put config file.
import site
site.getusersitepackages()
/home/user/.local/lib/python3.2/site-packages'
 
/home/user/.local/lib/python3.2/site-packages/usercustomize.py
/home/user/.local/lib/python3.2/site-packages/sitecustomize works in the


=pass=
=input=
The pass statement does nothing.
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

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