Basic python tutorial-grammar chapter-one hour getting started with python

Source: Internet
Author: User

Overview: All program content in this document is edited under Vim in linux, and then run in interpreter
#! /Usr/bin/python
# The following is code
......
# The end

1. Hello world! -- How to print output
Print "hello world"
2. Calculated area -- Statement separator + variable definition + numerical operation
1 #! /Usr/bin/python
2 wide = 10
3 length = 20
4 area = wide * length
5 print "hello world"

6 print area

3. Input and dynamic Functions
1 #! /Usr/bin/python
2 wide = 10
3 length = input ("the length of something ")
4 area = wide * length
5 print "hello world"
6 print area
Foo = input

Foo ("I can input now ")

4. Branch, loop, jump
4.1 Branch
1 #! /Usr/bin/python
2 tem = input ("input a num ")
3 if tem> 50:
4 print "more than 50"
5 else:
6 print "no more then 50"
Note: No parentheses. Add a colon.
# Area calculation program
Print "Welcome to the Area calculation program"
Print "---------------------------------------"
Print
# Print out the menu:
Print "Please select a shape :"
Print "1 Rectangle"
Print "2 Circle"
# Get the user's choice:
Shape = input ("> ;")
# Calculate the area:
If shape = 1:
Height = input ("Please enter the height :")
Width = input ("Please enter the width :")
Area = height * width
Print "The area is", area
Else:
Radius = input ("Please enter the radius :")
Area = 3.14 * (radius ** 2)
Print "The area is", area
1. Only print itself will print a blank line
2. = check whether the two values are equal. Different from =, the latter assigns the value on the right of the expression to the variable on the left. This is a very important difference!
3. ** is the power operator of python-therefore, the square of the radius is written as radius ** 2
4. print can print more than one thing. You only need to use commas to separate them. (They are separated by a single space in the output .)

4.2for Loop
For food in "spam", "eggs", "tomatoes ":
Print "I love", food
Array:
For number in range (1,100 ):
Print "Hello, world! "
Print "Just", 100-number, "more to go ..."
Sleep in the time module:
# Spam-cooking program
# Fetch the function sleep
From time import sleep
Print "Please start cooking the spam. (I'll be back in 3 minutes .)"
# Wait for 3 minutes (that is, 3*60 seconds )...
Sleep (180)
Print "I'm baaack :)"
# How hot is hot enough?
Hot_enough = 50
Temperature = input ("How hot is the spam? ")
While temperature Print "Not hot enough... Cook it a bit more ..."
Sleep (30)
Temperature = input ("OK, How hot is it now? ")
Print "It's hot enough-You're done! "

4.3while Loop
Def floor (number): // note that the colon in this place
Result = 0
While result <= number:
Result = result + 1
Result = result-1
Return result
Function Definition and while loop. Use strict indentation instead of parentheses to convey the hierarchical relationship.
Two variables can be assigned together as follows: x, y = y, y + 1


5. complex data structures
#! /Usr/bin/python
2 # Calculate all the primes below 1000
3 import math // class include statement
4 result = [2]
5 for test in range (3,1000 ):
6 bound = (int) (math. sqrt (test) // reference and numeric type conversion
7 for I in range (2, bound + 2 ):
8 if test % I = 0:
9 break
10 if I = bound + 1:
11 result. append (test)
12 print result

The built-in function range actually returns a list, which can be used as all other lists. (It includes the first number, but does not include the last number .)
The list can be used as a logical variable. If it is not empty, it is true; otherwise, it is false. Therefore, while candidates means "when the while list name is candidates is not empty" or simply says "while there is candidates ".
You can use if someElement in somelist to check whether an element is in the list.
You can use someList. remove (someElement) to delete someElement in someList.
You can use someList. append (something) to add elements to a list. In fact, you can also use "+" (like someList = someList + [something]). However, the efficiency is not too high.
You can add a number enclosed in parentheses after the list name to indicate the position of an element (it is strange that the position of the 1st elements in the list is 0) to obtain an element of the list. Therefore, someList [3] is the fourth element in the someList list (and so on ).
You can use the keyword del to delete a variable. It can also be used to delete elements in the list (just like here ). Therefore, del someList [0] deletes the first element in the someList list. If the list is [1, 2, 3] before deletion, it is changed to [2, 3] after deletion.

6. Continue abstraction-object and Object-Oriented Programming


Class Oven:
Def insertSpam (self, spam ):
Self. spam = spam
Def getSpam (self ):
Return self. spam
The class of the object is defined by the keyword class.
The name of a class generally starts with an uppercase letter, while the name of a function and variable (and its attributes and methods) starts with a lowercase letter.
The definition of methods (that is, to let objects know how to do functions and operations) is not special, but must be included in the definition of classes.
The first parameter that all object methods should have is self (or similar ......) The reason will soon be clear.
The attributes and methods of the object can be accessed as follows: mySpam. temperature = 2 or dilbert. be_nice ().
I can guess that you still don't know something in the above example. For example, what is self? Also, now we have an object Recipe (that is, a class). How do we actually construct an object?

Let's reverse the order first. The object is created by referencing the class name like a function reference:

MyOven = Oven ()

MyOven contains an Oven object, usually called an instance of the Oven class. If we have constructed a Spam class, we can do this as follows:
MySpam = Spam ()
MyOven. insertSpam (mySpam)

MyOven. spam will now contain mySpam. What's going on? Because when we call a method of an object, the first parameter, usually called self, always contains the object itself. (Clever, haha !) In this way, the row self. spam = spam sets the spam attribute value of the current Oven object as the parameter spam. Note that they are two different things, even though they are called spam in this example.

 


7. Comparison between python and C
7.1 logical operations

Python uses or and not for logical operations, while C uses ~

 

 

 


 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.