Showing posts with label python code. Show all posts

Programs in a file, and variables Using Python

Introduction

Well, we can make one-liner programs. So What? You want to send programs to other people, so that they can use them, without knowing how to write them.

Editing in Notepad

Writing programs in python to a file is VERY easy. Python programs are simply text documents - you can open them up in notepad, and have a look at them, just like that. So, go and open notepad. Type the following:
Code Example 1 - mary.py
#A simple program.
print "Mary had a little lamb,"
print "it's fleece was white as snow;"
print "and everywhere that Mary went",
print "her lamb was sure to go."
Keep this exactly the same, down to where the commas are placed. Save the file as 'mary.py' - and make sure notepad doesn't add .txt to the end of the filename - You will have to tell it to save as any file, to avoid this. Turn off 'Hide known file extensions' in Windows Explorer, if it makes it easier.

Using the IDLE Environment

Now, open up the Python IDLE program (should be in your start menu). Click 'File > Open' and find mary.py and open it. if you cant find mary.py, set the open dialogue to 'Files of type: All Files (*)'. A new window will open, showing the program you just wrote. To run your program, click 'Run>Run Module' (or just press F5). Your program will now run in the main Python screen (Titled *Python Shell*) and will look like this:
Code Example 2 - mary.py output
Mary had a little lamb,
it's fleece was white as snow;
and everywhere that Mary went her lamb was sure to go.
You can also use IDLE to create Python programs, like what you did in notepad. Simply click 'File > New'. We will be writing all of our programs now in the python IDLE program - the notepad thing is just a demonstration to tell you that a .py file is just a simple text file, which anyone can see.
There are a couple of things to notice here:
  • First of all, the comment wasn't shown. That is good, because remember - comments aren't compiled. (try compiling it after removing the # - it comes out messy)
  • Second, is that the 3rd and 4th line got joined. This is because there is a comma just outside the inverted commas that surround the text. In the 'print' command, this stops the program from starting a new line on the screen when showing text.
  • You can also run the program from your command line program (e.g. MSDOS) - Open the prompt up, type 'cd path\to\your\file' then type 'python mary.py'. Your program will now execute in the command line.

Variables

Now lets start introducing variables. Variables store a value, that can be looked at or changed at a later time. Let's make a program that uses variables. Open up IDLE, click 'File>New Window' - a new window now appears, and it is easy to type in programs. Type the following (or just copy and paste - just read very carefully, and compare the code to the output that the program will make):
Code Example 3 - Variables
#variables demonstrated
print "This program is a demo of variables"
v = 1
print "The value of v is now", v
v = v + 1
print "v now equals itself plus one, making it worth", v
v = 51
print "v can store any numerical value, to be used elsewhere."
print "for example, in a sentence. v is now worth", v
print "v times 5 equals", v*5
print "but v still only remains", v
print "to make v five times bigger, you would have to type v = v * 5"
v = v * 5
print "there you go, now v equals", v, "and not", v / 5

Strings

As you can see, variables store values, for use at a later time. You can change them at any time. You can put in more than numbers, though. Variables can hold things like text. A variable that holds text is called a string. Try this program:
Code Example 4 - Strings
#giving variables text, and adding text.
word1 = "Good"
word2 = "Morning"
word3 = "to you too!"
print word1, word2
sentence = word1 + " " + word2 + " " +word3
print sentence
The output will be:
Code Example 5 - String output
Good Morning
Good Morning to you too!
As you see, the variables above were holding text. Variable names can also be longer than one letter - here, we had word1, word2, and word3. As you can also see, strings can be added together to make longer words or sentences. However, it doesn't add spaces in between the words - hence me putting in the " " things (there is one space between those).

Conclusion

Well done! We now understand longer programs, and know the use of variables. Next lesson, we look at functions, what they are, and how to use them.
Thanks to all,

Using Requests in Python


What is Requests?

Requests is an Apache2 Licensed HTTP library, written in Python, for human beings

Requests allow you to send HTTP/1.1 requests. 

You can add headers, form data, multipart files, and parameters with simple
Python dictionaries, and access the response data in the same way.

Install Requests

There are a few ways to install Requests. Either use pip, easy_install,
or get the tarball.

You can also get the code through GitHub, if you prefer that. 

To see the full list of options, please consult the install documentation here.

We are using pip to install, simply type in: 
pip install requests

Importing the module

To import the Requests module, put this command at the beginning of your script.
import requests

Making a request

Note, I will sometimes use http://httpbin.org/ throughout this article. 

It supports most of the common HTTP verbs and mostly return the variables you
send in, which is sometimes very useful when you are writing a (HTTP) script. 
# Get a webpage, this creates a Response object called "r"

r = requests.get('https://github.com/timeline.json')

Response Code

We can check the response status code, and do a status code lookup with the
dictionary look-up object. 
r = requests.get('https://github.com/timeline.json')
r.status_code
>>200

r.status_code == requests.codes.ok
>>> True

requests.codes['temporary_redirect']
>>> 307

requests.codes.teapot
>>> 418

requests.codes['\o/']
>>> 200


Get the content

Get the content of the server's response.
import requests
r = requests.get('https://github.com/timeline.json')
print r.text

# Requests also comes with a builtin JSON decoder, 
# in case you’re dealing with JSON data
import requests
r = requests.get('https://github.com/timeline.json')
print r.json

Headers

We can view the server’s response headers using a Python dictionary, and we can 
access the headers using any capitalization we want.

If a header doesn't exist in the Response, its value defaults to None
r.headers
{
    'status': '200 OK',
    'content-encoding': 'gzip',
    'transfer-encoding': 'chunked',
    'connection': 'close',
    'server': 'nginx/1.0.4',
    'x-runtime': '148ms',
    'etag': '"e1ca502697e5c9317743dc078f67693f"',
    'content-type': 'application/json; charset=utf-8'
}

r.headers['Content-Type']
>>>'application/json; charset=utf-8'

r.headers.get('content-type')
>>>'application/json; charset=utf-8'

r.headers['X-Random']
>>>None

# Get the headers of a given URL
resp = requests.head("http://www.google.com")
print resp.status_code, resp.text, resp.headers

Encoding

Requests will automatically decode content from the server. 

Most Unicode charsets are seamlessly decoded.

When you make a request, Requests makes educated guesses about the encoding
of the response based on the HTTP headers.

The text encoding guessed by Requests is used when you access r.text.

You can find out what encoding Requests is using, and change it, using the
r.encoding property:

If you change the encoding, Requests will use the new value of r.encoding
whenever you call r.text.
print r.encoding
>> utf-8

>>> r.encoding = 'ISO-8859-1'

Custom Headers

If you’d like to add HTTP headers to a request, simply pass in a dict to the
headers parameter.
import json
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
headers = {'content-type': 'application/json'}

r = requests.post(url, data=json.dumps(payload), headers=headers)

Redirection and History

Requests will automatically perform location redirection while using the GET
and OPTIONS verbs.

GitHub redirects all HTTP requests to HTTPS. 

We can use the history method of the Response object to track redirection. 

r = requests.get('http://github.com')
r.url
>>> 'https://github.com/'

r.status_code
>>> 200

r.history
>>> []

Make a HTTP Post request

With Requests you can of course also do post requests.
r = requests.post("http://httpbin.org/post")
You can use other HTTP requests types as well (PUT, DELETE, HEAD and OPTIONS)
r = requests.put("http://httpbin.org/put")
r = requests.delete("http://httpbin.org/delete")
r = requests.head("http://httpbin.org/get")
r = requests.options("http://httpbin.org/get")
# This small script creates a Github repo.
import requests, json

github_url = "https://api.github.com/user/repos"
data = json.dumps({'name':'test', 'description':'some test repo'}) 
r = requests.post(github_url, data, auth=('user', '*****'))

print r.json

Errors and Exceptions

In the event of a network problem (e.g. DNS failure, refused connection, etc),
Requests will raise a ConnectionError exception.

In the event of the rare invalid HTTP response, Requests will raise an HTTPError
exception.

If a request times out, a Timeout exception is raised.

If a request exceeds the configured number of maximum redirections, a
TooManyRedirects exception is raised.

All exceptions that Requests explicitly raises inherit from
requests.exceptions.RequestException.

Python Basic Operators


Operators are the constructs which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator.

Types of Operator

Python language supports the following types of operators.
  • Arithmetic Operators
  • Comparison (Relational) Operators
  • Assignment Operators
  • Logical Operators
  • Bitwise Operators
  • Membership Operators
  • Identity Operators
Let us have a look on all operators one by one.

Python Arithmetic Operators

Assume variable a holds 10 and variable b holds 20, then −
OperatorDescriptionExample
+ AdditionAdds values on either side of the operator.a + b = 30
- SubtractionSubtracts right hand operand from left hand operand.a – b = -10
* MultiplicationMultiplies values on either side of the operatora * b = 200
/ DivisionDivides left hand operand by right hand operandb / a = 2
% ModulusDivides left hand operand by right hand operand and returns remainderb % a = 0
** ExponentPerforms exponential (power) calculation on operatorsa**b =10 to the power 20
//Floor Division - The division of operands where the result is the quotient in which the digits after the decimal point are removed.9//2 = 4 and 9.0//2.0 = 4.0

Python Comparison Operators

These operators compare the values on either sides of them and decide the relation among them. They are also called Relational operators.
Assume variable a holds 10 and variable b holds 20, then −
OperatorDescriptionExample
==If the values of two operands are equal, then the condition becomes true.(a == b) is not true.
!=If values of two operands are not equal, then condition becomes true.
<>If values of two operands are not equal, then condition becomes true.(a <> b) is true. This is similar to != operator.
>If the value of left operand is greater than the value of right operand, then condition becomes true.(a > b) is not true.
<If the value of left operand is less than the value of right operand, then condition becomes true.(a < b) is true.
>=If the value of left operand is greater than or equal to the value of right operand, then condition becomes true.(a >= b) is not true.
<=If the value of left operand is less than or equal to the value of right operand, then condition becomes true.(a <= b) is true.

Python Assignment Operators

Assume variable a holds 10 and variable b holds 20, then −
OperatorDescriptionExample
=Assigns values from right side operands to left side operandc = a + b assigns value of a + b into c
+= Add ANDIt adds right operand to the left operand and assign the result to left operandc += a is equivalent to c = c + a
-= Subtract ANDIt subtracts right operand from the left operand and assign the result to left operandc -= a is equivalent to c = c - a
*= Multiply ANDIt multiplies right operand with the left operand and assign the result to left operandc *= a is equivalent to c = c * a
/= Divide ANDIt divides left operand with the right operand and assign the result to left operandc /= a is equivalent to c = c / ac /= a is equivalent to c = c / a
%= Modulus ANDIt takes modulus using two operands and assign the result to left operandc %= a is equivalent to c = c % a
**= Exponent ANDPerforms exponential (power) calculation on operators and assign value to the left operandc **= a is equivalent to c = c ** a
//= Floor DivisionIt performs floor division on operators and assign value to the left operandc //= a is equivalent to c = c // a

Python Bitwise Operators

Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b = 13; Now in binary format they will be as follows −
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a  = 1100 0011
There are following Bitwise operators supported by Python language

OperatorDescriptionExample
& Binary ANDOperator copies a bit to the result if it exists in both operands(a & b) (means 0000 1100)
| Binary ORIt copies a bit if it exists in either operand.(a | b) = 61 (means 0011 1101)
^ Binary XORIt copies the bit if it is set in one operand but not both.(a ^ b) = 49 (means 0011 0001)
~ Binary Ones ComplementIt is unary and has the effect of 'flipping' bits.(~a ) = -61 (means 1100 0011 in 2's complement form due to a signed binary number.
<< Binary Left ShiftThe left operands value is moved left by the number of bits specified by the right operand.a << = 240 (means 1111 0000)
>> Binary Right ShiftThe left operands value is moved right by the number of bits specified by the right operand.a >> = 15 (means 0000 1111)

Python Logical Operators

There are following logical operators supported by Python language. Assume variable a holds 10 and variable b holds 20 then
Used to reverse the logical state of its operand.

Python Membership Operators

Python’s membership operators test for membership in a sequence, such as strings, lists, or tuples. There are two membership operators as explained below
OperatorDescriptionExample
isEvaluates to true if the variables on either side of the operator point to the same object and false otherwise.x is y, here is results in 1 if id(x) equals id(y).
is notEvaluates to false if the variables on either side of the operator point to the same object and true otherwise.x is not y, here is not results in 1 if id(x) is not equal to id(y).

Python Identity Operators

Identity operators compare the memory locations of two objects. There are two Identity operators explained below:

OperatorDescriptionExample
isEvaluates to true if the variables on either side of the operator point to the same object and false otherwise.x is y, here is results in 1 if id(x) equals id(y).
is notEvaluates to false if the variables on either side of the operator point to the same object and true otherwise.x is not y, here is not results in 1 if id(x) is not equal to id(y).

Python Operators Precedence

The following table lists all operators from highest precedence to lowest.
OperatorDescription
**Exponentiation (raise to the power)
~ + -Ccomplement, unary plus and minus (method names for the last two are +@ and -@)
* / % //Multiply, divide, modulo and floor division
+ -Addition and subtraction
>> <<Right and left bitwise shift
&Bitwise 'AND'td>
^ |Bitwise exclusive `OR' and regular `OR'
<= < > >=Comparison operators
<> == !=Equality operators
= %= /= //= -= += *= **=Assignment operators
is is notIdentity operators
in not inMembership operators
not or andLogical operators