Wednesday, 8 January 2014

Operators and operands

Operators are special symbols that represent computations like addition and multiplication. The values the operator is applied to are called operands. The operators +, -, *, / and ** perform addition, subtraction, multiplication, division and exponen-tiation, as in the following examples:

20+32 hour-1 hour*60+minute minute/60 5**2 (5+9)*(15-7)

In some other languages, ˆ is used for exponentiation, but in Python it is a bitwise operator called XOR. I won’t cover bitwise operators in this book, but you can read about them at wiki.python. org/moin/BitwiseOperators. The division operator might not do what you expect:

>>> minute = 59
>>> minute/60
0

The value of minute is 59, and in conventional arithmetic 59 divided by 60 is 0.98333, not 0. The reason for the discrepancy is that Python is performing floor division When both of the operands are integers, the result is also an integer; floor division chops off the fraction part, so in this example it rounds down to zero. If either of the operands is a floating-point number, Python performs floating-point division, and the result is a float:

>>> minute/60.0
0.98333333333333328

Arithmetic Expressions

An arithmetic expressionconsists of operands and operators combined in a man-ner that is already familiar to you from learning algebra. Table  shows several arithmetic operators and gives examples of how you might use them in Python code.


In algebra, you are probably used to indicating multiplication like this: ab. However, in Python, we must indicate multiplication explicitly, using the multi-plication operator (*), like this: a * b. Binary operators are placed between their operands (a * b, for example), whereas unary operators are placed before their
operands (-a, for example).


Program Comments and Docstrings

In Python we double quotation (") or single quotation mark for Docstrings  and pound sign(#) for single line comment.

"""
This is a python comment
This is a python comment
This is a python comment
"""

# Assign a value to radius
#this is also python comment
radius = 20# radius is now 20 radius 20

# Compute area
area = radius * radius * 3.14159

# Display results
print("The area for the circle of radius", radius, "is", area)

String Concatenation in python

You can join two or more strings to form a new string using the concatenation operator +. Here is an example:

>>> "sony" + " biswas" + " nitol"
'sony biswas nitol'

plus (+) sign use for concatenate two or more string

Drawing the Olympic Rings Logo in python

Here we Have just use simple graphical programming for make some fun, There are many ways to write graphics programs in Python. A simple way to start graphics programming is to use Python’s built-in turtlemodule. Later in the book, we will introduce Tkinterfor developing comprehensive graphical user interface applications.

1 import turtle
2
3 turtle.color("blue")
4 turtle.penup()
5 turtle.goto(-110, -25)
6 turtle.pendown()
7 turtle.circle(45)
8
9 turtle.color("black")
10 turtle.penup()
11 turtle.goto(0, -25)
12 turtle.pendown()
13 turtle.circle(45)
14
15 turtle.color("red")
16 turtle.penup()
17 turtle.goto(110, -25)
18 turtle.pendown()
19 turtle.circle(45)
20
21 turtle.color("yellow")
22 turtle.penup()
23 turtle.goto(-55, -75)
24 turtle.pendown()
25 turtle.circle(45)
26
27 turtle.color("green")
28 turtle.penup()
29 turtle.goto(55, -75)
30 turtle.pendown()
31 turtle.circle(45)
32
33 turtle.done()

Programming error in python

There are Three types of Error in Python Programming .Those are :

1) Syntax Errors
2) Runtime Errors
3) Logic Errors


1) Syntax Errors

The most common erroryou will encounter are syntax errors. Like any programming lan-guage, Python has its own syntax, and you need to write code that obeys the syntax rules. If your program violates the rules—for example, if a quotation mark is missing or a word is misspelled—Python will report syntax errors.

Syntax errorsresult from errors in code construction, such as mistyping a statement, incor-rect indentation, omitting some necessary punctuation, or using an opening parenthesis with-out a corresponding closing parenthesis. These errors are usually easy to detect, because Python tells you where they are and what caused them. For example, the following print statement has a syntax error:




2) Runtime Errors

Runtime errorsare errors that cause a program to terminate abnormally. They occur while aprogram is running if the Python interpreter detects an operation that is impossible to carry out. Input mistakes typically cause runtime errors. Aninput error occurs when the user enters a value that the program cannot handle. For instance, if the program expects to read in a number, but instead the user enters a string of text, this causes data-type errors to occur in the program.

Another common source of runtime errors is division by zero. This happens when the divi-sor is zero for integer divisions. For example, the expression 1 / 0in the following statement would cause a runtime error.



3) Logic Errors :

Logic errorsoccur when a program does not perform the way it was intended to. Errors of this kind occur for many different reasons. For example, suppose you wrote the program in Listing 1.4 to convert a temperature (35 degrees) from Fahrenheit to Celsius.


You will get Celsius –12.55degrees, which is wrong. It should be 1.66. To get the correct result, you need to use 5 / 9 * (35 – 32)rather than 5 / 9 * 35 – 32in the expression. That is, you need to add parentheses around (35 – 32)so Python will calculate that expression first before doing the division.




Variable names and keywords in python

Programmers generally choose names for their variables that are meaningful—they document what the variable is used for.

Variable names can be arbitrarily long. They can contain both letters and numbers, but they have to begin with a letter. It is legal to use uppercase letters, but it is a good idea to begin variable names with a lowercase letter.

The underscore character (_) can appear in a name. It is often used in names with multiple words, such as my_name or airspeed_of_unladen_swallow.

If you give a variable an illegal name, you get a syntax error:
>>> 76trombones = 'big parade'
SyntaxError: invalid syntax
>>> more@ = 1000000
SyntaxError: invalid syntax
>>> class = 'Advanced Theoretical Zymurgy'
SyntaxError: invalid syntax

76trombones is illegal because it does not begin with a letter. more@ is illegal because it contains an illegal character, @. But what’s wrong with class?

It turns out that class is one of Python’s keywords. The interpreter uses keywords to recognize the structure of the program, and they cannot be used as variable names.


You might want to keep this list handy. If the interpreter complains about one of your variable names and you don’t know why, see if it is on this list

Using Python to Perform Mathematical Computations

Python programs can perform all sorts of mathematical computations and display the result. To display the addition, subtraction, multiplication, and division of two numbers, xand y, use the following code:
print(x + y)
print(x – y)
print(x * y)
print(x / y)

1 # Compute expression
>>> print((150-3.5) + (542-6))
682.5

>>> print((150-3.5) - (542-6))
-389.5

>>> print((150-3.5) * (542-6))
78524.0

>>> print((150-3.5) / (542-6))
0.2733208955223881
>>>



Values and types in python

A value is one of the basic things a program works with, like a letter or a number. The values we have seen so far are 1, 2, and 'Hello, World!'.

These values belong to different types: 2 is an integer, and 'Hello, World!' is a string, so-called because it contains a “string” of letters. You (and the interpreter) can identify strings because they are enclosed in quotation marks.

The print statement also works for integers.
>>> print(4)
4

If you are not sure what type a value has, the interpreter can tell you.
>>> type('hello, world')
<class 'str'>
>>> type (4)
<class 'int'>
>>> type ('17')
<class 'str'>

Not surprisingly, strings belong to the type str and integers belong to the type int. Less obviously, numbers with a decimal point belong to a type called float, because these numbers are represented in a format called floating-point.
>>> type(3.2)
<class 'float'>

What about values like '17' and '3.2'? They look like numbers, but they are in quotation marks
like strings.
>>> type('17')
<class 'str'>
>>> type('3.2')
<class 'str'>
They’re strings.

When you type a large integer, you might be tempted to use commas between groups of three digits, as in 1,000,000. This is not a legal integer in Python, but it is legal:
>>> print (1,000,000)
1 0 0

Well, that’s not what we expected at all! Python interprets 1,000,000 as a comma-separated se-quence of integers, which it prints with spaces between. This is the first example we have seen of a semantic error: the code runs without producing an error message, but it doesn’t do the “right” thing.

The first program with explanation

Traditionally, the first program you write in a new language is called “Hello, World!” because all it does is display the words, “Hello, World!” In Python, it looks like this:

>>>print ("python is fun")
python is fun

This is an example of a print statement, which doesn’t actually print anything on paper. It displays
a value on the screen. In this case, the result is the words

python is fun

The quotation marks in the program mark the beginning and end of the text to be displayed; they don’t appear in the result. Some people judge the quality of a programming language by the simplicity of the “python is fun!” program. By this standard, Python does about as well as possible.

Tuesday, 7 January 2014

Behind the Scenes: How Python Works

Whether you are running Python code as a script or interactively in a shell, the Python interpreter does a great deal of work to carry out the instructions in your program. This work can be broken into a series of steps, as shown in Figure.


1 The interpreter reads a Python expression or statement, also called the source code, and verifies that it is well formed. In this step, the inter-preter behaves like a strict English teacher who rejects any sentence that
does not adhere to the grammar rules, or syntax,of the language. As soon as the interpreter encounters such an error, it halts translation with an error message.

2. If a Python expression is well formed, the interpreter then translates it to an equivalent form in a low-level language called byte code. When the interpreter runs a script, it completely translates it to byte code.

3. This byte code is next sent to another software component, called the Python virtual machine (PVM), where it is executed. If another error occurs during this step, execution also halts with an error message.

Write some code in Python

We are going to write our first program in python, before we write our we have to know some thing, first of all we need a python software or python shell or python IDE. Click Here to download python shell.

Install it like other software .do the following stuff

1.Go to start menu
2.All program
3.clickpython 3.3
4.Then click python Idle.

There write the following Code

>>>3+4
7
>>>3
3
>>>“Python is really cool!”
'Python is really cool!'
>>> name = “Ken Lambert”
>>> name
'Ken Lambert'
>>> “Hi there “ + name
'Hi there Ken Lambert'
>>> print 'Hi there'
Hi there
>>> print “Hi there”, name
Hi there Ken Lambert

We will Discuss all those thing later. To quit the Python shell, you can either select the window’s close box or press the Control+D key combination.

What Can I Do with Python?

In addition to being a well-designed programming language, Python is useful for ac-complishing real-world tasks—the sorts of things developers do day in and day out. It’s commonly used in a variety of domains, as a tool for scripting other components and implementing standalone programs. In fact, as a general-purpose language, Python’s roles are virtually unlimited: you can use it for everything from website de-velopment and gaming to robotics and spacecraft control. However, the most common Python roles currently seem to fall into a few broad cat-egories. The next few sections describe some of Python’s most common applications
today, as well as tools used in each domain. We won’t be able to explore the tools mentioned here in any depth—if you are interested in any of these topics, see the Python website or other resources for more details.

Systems Programming

Python’s  built-in interfaces to operating-system services make it ideal for writing portable, maintainable system-administration tools and utilities (sometimes called  shell tools). Python programs can search files and directory trees, launch other programs, do parallel processing with processes and threads, and so on. Python’s standard library comes with POSIX bindings and so on.

GUIs

Python’s simplicity and rapid turnaround also make it a good match for graphical user interface programming on the desktop. Python comes with a standard object-oriented interface to the Tk GUI API called  tkinter(Tkinterin 2.X) that allows Python programs to implement portable GUIs with a native look and feel. Python/tkinter GUIs run un-changed on Microsoft Windows, X Windows (on Unix and Linux), and the Mac OS (both Classic and OS X). A free extension package, PMW, adds advanced widgets to
the tkinter toolkit. In addition, the wxPythonGUI API, based on a C++ library, offers an alternative toolkit for constructing portable GUIs in Python.

Internet Scripting

Python comes with standard Internet modules that allow Python programs to perform a wide variety of networking tasks, in client and server modes. Scripts can communicate over sockets; extract form information sent to server-side CGI scripts; transfer files by FTP; parse and generate XML and JSON documents; send, receive, compose, and parse email; fetch web pages by URLs; parse the HTML of fetched web pages; communicate over XML-RPC, SOAP, and Telnet; and more. Python’s libraries make these tasks re-markably simple.

Who Uses Python Today?

Now a day Python is used by many well Known Companies For instance, among the generally known
Python user base:

*Googlemakes extensive use of Python in its web search systems.

• The popular YouTubevideo sharing service is largely written in Python.

• The Dropboxstorage service codes both its server and desktop client software pri-marily in Python.

• The Raspberry Pisingle-board computer promotes Python as its educational lan-guage.

• EVE Online, a massively multiplayer online game (MMOG) by CCP Games, uses
Python broadly.

• The widespread  BitTorrentpeer-to-peer file sharing system began its life as a
Python program.

• Industrial Light & Magic,  Pixar, and others use Python in the production of ani-mated movies.

• ESRIuses Python as an end-user customization tool for its popular GIS mapping
products.

• Google’s App Engineweb development framework uses Python as an application
language.

Is Python a “Scripting Language”?

Python is a general-purpose programming language that is often applied in scripting roles. It is commonly defined as an  object-oriented scripting language—a definition that blends support for OOP with an overall orientation toward scripting roles. If pressed for a one-liner, I’d say that Python is probably better known as
a general-purpose pro- gramming language that blends procedural, functional, and object-oriented paradigms—a statement that captures the richness and scope of today’s Python.

Still, the term “scripting” seems to have stuck to Python like glue, perhaps as a contrast with larger programming effort required by some other tools. For example, people often use the word “script” instead of “program” to describe a Python code file. In keeping with this tradition, this book uses the terms “script” and “program” interchangeably, with a slight preference for “script” to describe a simpler top-level file and “program” to refer to a more sophisticated multifile application.

Because the term “scripting language” has so many different meanings to different observers, though, some would prefer that it not be applied to Python at all. In fact, people tend to make three very different associations, some of which are more useful than others, when they hear Python labeled as such:

Shell tools

Sometimes when people hear Python described as a scripting language, they think it means that Python is a tool for coding operating-system-oriented scripts. Such programs are often launched from console command lines and perform tasks such as processing text files and launching other programs. Python programs can and do serve such roles, but this is just one of dozens of common Python application domains. It is not just a better shell-script language.

Control language

To others, scripting refers to a “glue” layer used to control and direct (i.e., script) other application components. Python programs are indeed often deployed in the context of larger applications. For instance, to test hardware devices, Python pro-grams may call out to components that give low-level access to a device. Similarly, programs may run bits of Python code at strategic points to support end-user
product customization without the need to ship and recompile the entire system’s

Why Do People Use Python?

The first question on your mind that why use python not other. Because there are many programming languages available today, this is the usual first question of newcomers. Given that there are roughly 1 million Python users out there at the moment, there really is no way to answer this question with complete accuracy;
the choice of development tools is sometimes based on unique constraints or personal preference.

But after teaching Python to roughly 260 groups and over 4,000 students during the
last 16 years, I have seen some common themes emerge. The primary factors cited by
Python users seem to be these:


Software quality

For many, Python’s focus on readability, coherence, and software quality in general
sets it apart from other tools in the scripting world. Python code is designed to be
readable, and hence reusable and maintainable—much more so than traditional
scripting languages. The uniformity of Python code makes it easy to understand,
even if you did not write it. In addition, Python has deep support for more advanced
software reusemechanisms, such as object-oriented (OO) and function program-ming.


Developer productivity

Python boosts developer productivity many times beyond compiled or statically
typed languages such as C, C++, and Java. Python code is typically  one-third to
one-fifththe size of equivalent C++ or Java code. That means there is less to type,
less to debug, and less to maintain after the fact. Python programs also run imme-diately, without the lengthy compile and link steps required by some other tools,
further boosting programmer speed.


Program portability

Most Python programs run unchanged on all major computer platforms. Porting
Python code between Linux and Windows, for example, is usually just a matter of
copying a script’s code between machines. Moreover, Python offers multiple op-tions for coding portable graphical user interfaces, database access programs, web-based systems, and more. Even operating system interfaces, including program launches and directory processing, are as portable in Python as they can possibly be.