⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 python for newbies.htm

📁 1000 HOWTOs for various needs [WINDOWS]
💻 HTM
📖 第 1 页 / 共 4 页
字号:
  <LI>\ - Prints a backslash 

  <LI>r - Prints a carriage return. Use newline unless you know what you're 

  doing. </LI></UL>Of course there are more, but you won't use them too often. 

<P></P>

<P>With strings, you can also concatenate them (stick them together) with the + 

operator. If you have two literal strings (i.e. not functions that return a 

string), you don't even need an operator: <PRE>&gt;&gt;&gt; 'holy' + 'grail'

'holygrail'

&gt;&gt;&gt; 'BS' 'RF'

BSRF

</PRE>Next come lists. Lists are called arrays in some languages, but it's all 

the same (well, not quite...). A list is a bunch of values grouped together in 

brackets []. Lists can contain any number of other variables, even strings and 

numbers in the same list, but no tuples or nested lists. Assigning lists is 

simple: <PRE>&gt;&gt;&gt; a = [1, "thin", "mint", 0]

&gt;&gt;&gt; a

[1, 'thin', 'mint', 0]

</PRE>Lists can be accessed simply by name, but you can access any variable in a 

list with its index by putting the index number in brackets right after the 

name. Note that index numbering starts at 0: <PRE>&gt;&gt;&gt; a[0]

1

</PRE>You can also use negative index numbers to start counting from the end of 

the list: <PRE>&gt;&gt;&gt; a[-1]

0

</PRE>That's all for indexes for now, but in the Intermediate string section we 

get to learn about fun things like slice indexes to access more than one element 

in a list. You can also use your masterful index-calling knowledge in strings. 

Characters in a string act just like elements in a list: <PRE>&gt;&gt;&gt; a = "BSRF"

&gt;&gt;&gt; a[1]

S

</PRE>Be warned though: You can replace individual elements in a list, but not 

in a string: <PRE>&gt;&gt;&gt; a = [1, "thin", "mint", 0]

&gt;&gt;&gt; b = "BSRF"

&gt;&gt;&gt; a[3] = 4

&gt;&gt;&gt; a

[1, 'thin', 'mint', 4]

&gt;&gt;&gt; b[1] = "M"

Traceback (innermost last):

  File "&lt;stdin&gt;Traceback (innermost last):

  File "&lt;stdin&gt;", line 1, in ?

TypeError: object doesn't support item assignment", line 1, in ?

</PRE>

<P></P>

<P>That's all folks! For data types at least... </P>

<P><FONT size=-2><A 

href="#top">Back 

to top</A></FONT></P>

<HR>



<H3 align=center><A name=math>Math and Operators</A></H3><BR>

<P>There are a few basic math operators in Python: +, -, *, /, **, and %. If you 

went to any school at all you know what +, -, *, and / do. That leaves ** and %. 

** is your exponentiatingneniating operator: <PRE>&gt;&gt;&gt; 2 ** 6

64

</PRE>Likewise % is your standard modulus operator. Modulus? Yeah. In case you 

don't know, the % operator divides the first number by the second number and 

gives the remainder. Observe: <PRE>&gt;&gt;&gt; 4 % 2

0

&gt;&gt;&gt; 10 % 3

1

&gt;&gt;&gt; 21 % 6

3

</PRE>You may have noticed in the course of trying out some of this stuff that 

if you divide, say, 1 by 3, you get 0. This is because Python always rounds down 

when working with integers. To work in floating-point numbers, just put a . 

(decimal point) in your expression somewhere: <PRE>&gt;&gt;&gt; #Bad

... 1/3

0

&gt;&gt;&gt; #Good

... 1./3

0.333333333333

&gt;&gt;&gt; #Good also

... 1/3.

0.333333333333

</PRE>In addition to your basic math operators, there are comparison operators 

in Python as well (what did you expect?). In the a couple more sections we'll 

learn how to use them in context, but here they are anyway: 

<UL>

  <LI>a == b checks if two a is equal to b (a and b can be any data type, not 

  just numbers) 

  <LI>a &gt; b checks if a is greater than b (see parentheses above) 

  <LI>a &lt; b checks if a is less than b (etc.) 

  <LI>a &gt;= b checks if a is greater than or equal to b 

  <LI>a &lt;= b checks if a is less than or equal to b 

  <LI>a != b checks if a isn't equal to b </LI></UL>You probably got nothing 

useful out of that except that even things like strings and lists can be 

compared. In fact, lists (or strings) don't even have to be of the same size to 

be compared: <PRE>&gt;&gt;&gt; #A return value of 1 means true, 0 means false

... [1, 2, 3, 4] &gt; [1, 2, 3]

1

&gt;&gt;&gt; [1, 2, 4] &gt; [1, 2, 3]

1

&gt;&gt;&gt; [1, 2, 3] &lt; [1, 3, 2]

1

&gt;&gt;&gt; [1, 2, -1] &gt; [1, 2]

1

</PRE>Also notice how list comparison is performed. The first values are 

compared. If they're equal, the next values are compared. If those two are 

equal, the next values are compared. This continues until the value in one is 

not equal to the value in the other (if all are equal then the lists are equal). 

Look at the third example: even though the 3rd value (index 2, remember) of the 

first list (3) is greater than the third of the second (2), the second list is 

still greater than the first because the interpreter never got that far; it 

found that the second number in the second list (3) was greater than in the 

first list (2), so it stopped (confused? That's Ok). If the interpreter gets to 

a null value (i.e. there are no items left in the list), then the longer list is 

greater (see 4th example above). 

<P></P>

<P>Last thing on operators: logical operators. and, or, not (there's no xor, 

unlike perl). and returns the last value encountered if true, 0 if false. or is 

the same, but it's true if only one of the arguments is non-zero (or non-null 

for strings). Finally, not returns 1 if the single argument is zero (null) or 0 

if the argument is non-zero. Observe: <PRE>&gt;&gt;&gt; 1 and 4

4

&gt;&gt;&gt; 2 or 0

2

&gt;&gt;&gt; 'monty' and 'python'

'python'

&gt;&gt;&gt; not 0

1

&gt;&gt;&gt; not ''

1

</PRE>

<P></P>

<P><FONT size=-2><A 

href="#top">Back 

to top</A></FONT></P>

<HR>



<H2 align=center><A name=io>Input/Output</A></H2>

<H3 align=center><A name=print>Printing information</A></H3>In our Hello, World! 

example above, we already saw one way of printing output, namely the 

(self-explanatory) print statement. print works pretty much like it does in 

perl, printing a string or any sort of variable or expression out on the screen. 

Anything you enter with print automatically has a newline, "\n", appended to it. 

<PRE>&gt;&gt;&gt; print "She's a witch!"

She's a witch!

&gt;&gt;&gt; print 5 + 3

8

&gt;&gt;&gt; a = "Burn her!"

&gt;&gt;&gt; print a

Burn her!

<A name=slice></A>&gt;&gt;&gt; #Don't worry if you don't know what this does; it's covered in the Intermediate section

... print "Yeah, b" + a[1:]

Yeah, burn her!

</PRE>If you don't want a newline appended, as is sometimes the case, simply add 

a ',' to the end of the line with your print statement. Note that this only 

works in non-interactive mode, so you need to make a new file.py or something. 

Try this on for size: <PRE>#!/usr/bin/python

a = 5

print "The value of a is",

print a,

print "!"

</PRE>Output: <PRE>The value of a is 5 !

</PRE>There's a few more ways you can put (non-string) variables in a print 

statement. You can use a comma, which will put a space around the variable. The 

final main way is to convert your variable to a string first, which is done 

simply by putting it in some backwards quotes (``). Then just append this to 

your string like you would any other string variable or value (see above). Check 

out these examples: <PRE>&gt;&gt;&gt; a=5

&gt;&gt;&gt; #Note the spacing around the number

... print "A duck costs $", a, "."

A duck costs $ 5 .

&gt;&gt;&gt; #Same thing, different way of putting it in

... print "A duck costs $" + `a` + "."

A duck costs $5.

</PRE>For those of you who know what stderr is (or stdout and stdin for that 

matter), yes, you can access it directly in Python. This does however use a bit 

more of an advanced technique, so to really understand what's going on here you 

should read <A 

href="#fileio">File 

I/O</A> and <A 

href="#mod">Modules</A>. 

Anyway, try out this script: <PRE>#!/usr/bin/python



import sys #Didn't I tell you to read about modules?

sys.stderr.write( "This is some error text\n" ) #You do need a \n here since

#you're writing directly to the file descriptor (READ FILE I/O)

</PRE>Run it, it looks more or less normal, just prints "This is some error 

text". Now try running it as "python test.py &gt; /dev/null" (Unix) or "test.py 

&gt; nul" (Dos/Win). What's this? The output is still there, even though you 

redirected it to /dev/null or nul, the wastebasket of output. Instead of writing 

to the standard output (stdout), which is what print does, here you wrote to the 

standard error (stderr), which is separate from stdout (even though they appear 

on the same screen) and informs you of any errors your program might encounter. 

<P></P>

<P><FONT size=-2><A 

href="#top">Back 

to top</A></FONT></P>

<HR>



<H3 align=center><A name=user>Interacting with the User</H3>

<P>Alright, I admit it, this title is a bit too broad. In this section I'm just 

covering how to input variables from the user, not like catching keypresses or 

anything. Anyway, inputting from the, er, standard input is done with two simple 

functions in Python: input and raw_input. I'll discuss raw_input first 'cause 

it's simpler to use. </P>

<P>raw_input takes one argument, which is the prompt that'll come up while it 

waits for the user to type something. It returns the string that is typed, so it 

is most useful in assignments. A simple example: <PRE>&gt;&gt;&gt; a = raw_input( "Type something: " )

Type something: Dave

&gt;&gt;&gt; a

'Dave'

</PRE>Don't be too confused. I typed in 'Dave', and raw_input assigned it to the 

variable a. "That's all well and good," you say, "but what if I don't want to 

input a string? What if I want a number or list?" Well, there are really about 3 

ways. First and simplest is the input function, which you'll see if you just 

scroll down a bit. Another is string.atoi, which although a bit more advanced, 

adds some flexibility to the input process, although it only changes strings to 

ints (Subliminal message: <A 

href="#mod">Modules</A>). 

I won't go into too much detail, but here's a simple example of atoi: <PRE>&gt;&gt;&gt; from string import atoi

&gt;&gt;&gt; a = "5"

&gt;&gt;&gt; a

'5'

&gt;&gt;&gt; a = atoi(a)

&gt;&gt;&gt; a

5

&gt;&gt;&gt; #If you have Python 2.0 or higher, just do this

... a = "5"

&gt;&gt;&gt; a = int(a)

&gt;&gt;&gt; a

5

</PRE>Wow, a was converted from '5' to 5. Now let's move on. If you want to 

input any type of variable at all, like I said before, you want to use input. 

Input works just like raw_input, except Python interprets the variables as 

whatever is typed in. If that didn't make much sense, think of it this way: If 

you have a straight-up number, it's stored as a number. If you have some values 

in [] brackets, it's stored as a list. You can even put something in quotes to 

have a string. Check it out: <PRE>&gt;&gt;&gt; a = input( "Enter something: " )

Enter something: 5

&gt;&gt;&gt; a

5

&gt;&gt;&gt; a = input( "Enter something: " )

Enter something: [3, 6, 'Hello']

&gt;&gt;&gt; a

[3, 6, 'Hello']

&gt;&gt;&gt; a = input( "Enter something: " )

Enter something: Hello

Traceback (most recent call last):

  File "&lt;stdin&gt;", line 1, in ?

  File "&lt;string&gt;", line 0, in ?

NameError: There is no variable named 'Hello'

</PRE>Uh oh! What happened there? Well, the one pitfall of input is that it 

looks at everything as some sort of variable; it thought Hello was the name of a 

variable, so it screwed up when it found out there was no Hello. There are a few 

ways to get around this, like exception catching, but that's beyond the scope of 

this tutorial. For now, you'll have to trust your user to input the type of 

variable you want (I know, I know, you usually shouldn't trust your users, 

but...). Onward, onward. 

<P></P>

<P><FONT size=-2><A 

href="#top">Back 

to top</A></FONT></P>

<HR>



<H2 align=center><A name=control>Program Control</A></H2>

<H3 align=center><A name=if>What If...</A></H3>

<P>If you've <I>ever</I> programmed before, in something from Basic to Flash, 

you've seen if blocks. Hell, I don't even know why I devoted a whole section to 

them, since all I have to do is show you the structure, right? Alright, remember 

those comparison operators you used before? Good. Take a gander at this example 

code: <PRE>&gt;&gt;&gt; name = raw_input( "What's your name? " )

What's your name? David

&gt;&gt;&gt; if name &lt; "Dave":

...     print "Your name comes before mine." #That's a tab there

... elif name &gt; "Dave":

...     print "Your name comes after mine."

... else:

...     print "Hey, we have the same name!"

...

Your name comes after mine.

</PRE>Lame example, I know, but it gets the point across. Get over it. Now here 

you might notice a few things different than other languages you know (you might 

not, what can I say). We'll try to keep it in some sort of order too. First, you 

see the if, then a conditional statement. The conditional statement is just like 

we saw earlier, one expression and an operator and another expression. You could 

also just have an expression, and if'll see it as true if the expression 

evaluates to non-zero. But anyway. Next comes a colon, then a newline. You need 

this newline. On the next line or two or three or however many, the code is 

indented. One space, four spaces, eight spaces, it doesn't matter, it just has 

to be indented. Depending on how messy you generally code, this may be a 

convenient, code=beautifying feature or the code block from hell. I personally 

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -