For interactive use:
>>> user = raw_input (' Enter login ' name: ')
Enter Login Name:root
>>> Print User
Root
Interactive use, convert the output digital type to shaping, and replace by%
Note:%s is represented by a string substitution, and%d is replaced by an integer%f replaced by a floating-point number
>>> num = raw_input (' Now enter a number: ')
Now enter a number:1024
>>> print ' Doubling your number:%d '% (int (num) * 2)
Doubling your number:2048
>>>
You can see the use of the corresponding words function by calling the built-in function help
Help (Raw_input)
The pound sign is the comment section.
##### #ffffffffffffffff
Operator
+ - * / // % **
:(used for floating point division, rounding out the results)
Variables and assignment operations.
>>> counter=0 # # # #整数
>>> miles = 1000.0 # #浮点数
>>> name = ' Bob ' # # # # # #字符串
>>> counter = Counter +1 # # # #对1个整数加1
>>> kilometers = 1.609 * Miles # # #浮点数乘法赋值
>>> print "%f miles is the same as%s miles"% (miles,kilometers)
1000.000000 miles is the same as 1609.0 km
>>>
Number type:
int (signed integer)
Long (length integer)
BOOL (boolean value)
Float (floating point value)
Complex (negative)
[:] can intercept string contents
>>>pystr = ' Python '
>>> Pystr
' Python '
>>> Pystr[2:5]
' Tho '
>>>
[: 2] string truncated from 0 to the second string (not containing the second string, s)
>>> Iscool = ' is cool! '
>>> Iscool[:2]
' Is '
>>>
[3:] string is truncated from 3 to last (not including: three strings, s)
>>> Iscool[3:]
' cool! '
>>>
[-1] intercept the last string
>>> Iscool[-1]
‘!‘
>>>
You can add spaces
>>> pystr + ' +iscool
' Python is cool! '
>>>
String *
>>> PYSTR * 2
' Pythonpython '
>>>
*20 a special character
>>> '-' * 20
‘--------------------‘
>>>
Add a carriage return character
>>> pystr = "' Python
... is cool ""
>>> Pystr
' Python\nis cool '
>>> Print Pystr
Python
Is cool
>>>
Lists and slices
>>> alist = [1,2,3,4]
>>> alist
[1, 2, 3, 4]
>>> Alist[0]
1
>>> alist[2:]
[3, 4]
>>> Alist[1] = 5 # # # #将分片1替换成 5
[1, 5, 3, 4]
>>> atuple = (' robots ', the ', ', ' try ')
>>> Atuple
(' Robots ', the ', ', ' try ')
>>> Atuple[:3]
(' Robots ', 77, 93)
>>>
A dictionary consisting of key-value pairs, with a dictionary element wrapped in curly braces
>>> adict = {' Host ': ' Earth '}
>>> adict[' port '] = 80
>>> adict
{' Host ': ' Earth ', ' Port ': 80}
>>>
>>> Adict.keys () # # # # #将字典的键值对取出
[' Host ', ' Port ']
>>>
>>> adict[' host '] # # #可以取出字典对应的键值对.
' Earth '
>>> adict
{' Host ': ' Earth ', ' Port ': ' # # # # #可以取出字典对应的键值对.
>>> adict[' Port ']
80
>>>
While applet
>>> counter = 0
>>> While counter < 3:
... print ' Loop #%d '% (counter)
... counter + = 1
...
Loop #0
Loop #1
Loop #2
For applet, the for in Python accepts an iterator object as its argument, one iteration at a time
(shown in the following code: print By default adds a newline character to each line)
>>> print ' I like to use the Internet for: '
The Internet for:
>>> for item in [' E-mail ', ' net-surfing ', ' homework ', ' chat ']:
.... Print item
...
E-Mail
Net-surfing
Homework
Chat
>>>
Small example
>>> for Eachnum in range (3):
... print Eachnum
...
0
1
2
>>>
The range () function is used with the Len () function to display each element and its indexed value
>>> for I in range (len (foo)):
... print foo[i], ' (%d) '% i
...
A (0)
B (1)
C (2)
>>>
Loops generally have a constraint, either looping the index, or looping the elements, enumerate at the same time 2 points
>>> for I, ch in enumerate (foo):
... print ch, ' (%d) '% i
...
A (0)
B (1)
C (2)
>>>
List parsing: Use a For loop to place all values in the list, such as range (4) When you get the 0,1,2,3 loop
>>> squared = [x * * 2 for X in range (4)]
>>> for i in squared:
... print I
...
0
1
4
9
List parsing, more complex operations, the matching values are picked out to put in the list: for example if not X% 2 will not divide the remainder divisible by 2, the remaining number in X * * 2
>>> Sqdevens = [x * * 2 for X in range (8) if not x% 2]
>>> for I in Sqdevens:
... print I
...
0
4
16
36
>>>
#!/usr/bin/env python
filename = raw_input (' Enter file name: ')
fobj = open (filename, ' r ') Select the file name to open, R for Read, W for write, and a for add
For I in Fobj:
Print I, plus, commas are meant to suppress line breaks in text because the text has its own newline character
Fobj.close ()
Add error detection machine exception handling to your code, encapsulating them in try-except
#!/usr/bin/env python
Try
filename = raw_input (' Enter file name: ')
fobj = open (filename, ' R ')
For I in Fobj:
Print I,
Fobj.close ()
Except IOError, E:
Print "Eeeee", E
Error exception after executing script, stating that A.T text was not found
[Email protected] zby]#./open_bak.py
Enter file NAME:A.T
Eeeee [Errno 2] No such file or directory: ' A.T '
Functions in Python are called with parentheses (), and functions must be defined before they are called, and the None object is automatically returned if there is no return statement in the function.
Here is a small example of how to define
>>> def function_name (arguments):
... "Optional documentation string"
... function_suite
...
>>>
How to do next, please watch patiently, how to call the function,
What this function does is add my work to my value, he accepts an object and adds its value to itself, and then returns and.
Python calls functions like other high-level languages, with function names plus function operators, and a pair of parentheses.
>>> def addme2me (x):
... ' Apply + operation to argument '
... return (x + x)
...
>>> Addme2me (4.25)
8.5
>>> Addme2me (10)
20
>>> Addme2me (102)
204
>>> Addme2me (Python)
Traceback (most recent):
File "<stdin>", line 1, in <module>
Nameerror:name ' python ' is not defined
>>> addme2me (' python ')
' Pythonpython '
>>>
A module can contain executable code, functions and classes, or a combination of these things,
Once a module is created, it can be imported from another module using the import statement.
Then look down, how to import the module
>>> Import Sys
>>> sys.stdout.write (' Hello, world!\n ')
Hello, world!.
>>> Sys.platform
' Linux2 '
>>> sys.version
' 2.6.6 (r266:84292, Jan, 09:42:36) \n[gcc 4.4.7 20120313 (Red Hat 4.4.7-4)] '
Exercises:
Using the while statement and the for statement, output a number from 0 to 10, making sure that it is 0 to 10 instead of 0 to 9 or 1 to 10
>>> i = 0
>>> while I < 11:
... print I must be printed first, in step 1
... i + = 1
...
0
1
2
3
4
5
6
7
8
9
10
>>>
For loop
>>> for N in range (11):
... print N
...
0
1
2
3
4
5
6
7
8
9
10
Conditional judgment, determine whether 1 numbers are integers or negative numbers, or equal to 0, start with a fixed value, and then modify the code support, user input values to judge.
>>> n = Int (raw_input (' Nihao '))
Nihao123
>>> if n < 0:
... print ' negative '
... elif n > 0:
... print ' positive '
.. else:
... print ' zero '
...
Positive
>>>
Python learns to start from scratch