Python

Python

https://www.codecademy.com/learn/python


Python Syntax

Welcome!

Python is an easy to learn programming language. You can use it to create web apps, games, even a search engine!

Ready to learn Python? Click Save & Submit Code to continue!

Variables

Creating web apps, games, and search engines all involve storing and working with different types of data. They do so using variables. A variable stores a piece of data, and gives it a specific name.

For example:

spam = 5

The variable spam now stores the number 5.

Booleans

Great! You just stored a number in a variable. Numbers are one data type we use in programming. A second data type is called a boolean.

A boolean is like a light switch. It can only have two values. Just like a light switch can only be on or off, a boolean can only be True or False.

You can use variables to store booleans like this:

a = True
b = False

You've Been Reassigned

Now you know how to use variables to store values.

Say my_int = 7. You can change the value of a variable by "reassigning" it, like this:

my_int = 3

# my_int is set to 7 below. What do you think
# will happen if we reset it to 3 and print the result?

my_int = 7

# Change the value of my_int to 3 on line 8!

my_int = 3

# Here's some code that will print my_int to the console:
# The print keyword will be covered in detail soon!

print my_int

Whitespace

In Python, whitespace is used to structure code. Whitespace is important, so you have to be careful with how you use it.

Whitespace Means Right Space

Now let's examine the error from the last lesson:

IndentationError: expected an indented block
You'll get this error whenever your whitespace is off.

A Matter of Interpretation

The window in the top right corner of the page is called the interpreter. The interpreter runs your code line by line, and checks for any errors.

cats = 3

In the above example, we create a variable cats and assign it the value of 3.

Single Line Comments

You probably saw us use the # sign a few times in earlier exercises. The # sign is for comments. A comment is a line of text that Python won't try to run as code. It's just for humans to read.

Comments make your program easier to understand. When you look back at your code or others want to collaborate with you, they can read your comments and easily figure out what your code does.

Multi-Line Comments

The # sign will only comment out a single line. While you could write a multi-line comment, starting each line with #, that can be a pain.

Instead, for multi-line comments, you can include the whole block in a set of triple quotation marks:

"""Sipping from your cup 'til it runneth over,
Holy Grail.
"""

Math

Great! Now let's do some math. You can add, subtract, multiply, divide numbers like this

addition = 72 + 23
subtraction = 108 - 204
multiplication = 108 * 0.5
division = 108 / 9

Exponentiation

All that math can be done on a calculator, so why use Python? Because you can combine math with other data types (e.g. booleans) and commands to create useful programs. Calculators just stick to numbers.

Now let's work with exponents.

eight = 2 ** 3

In the above example, we create a new variable called eight and set it to 8, or the result of 2 to the power to 3 (2^3).

Notice that we use ** instead of * or the multiplication operator.

Modulo

Our final operator is modulo. Modulo returns the remainder from a division. So, if you type 3 % 2, it will return 1, because 2 goes into 3 evenly once, with 1 left over.

Bringing It All Together

Nice work! So far, you've learned about:

Variables, which store values for later use
Data types, such as numbers and booleans
Whitespace, which separates statements
Comments, which make your code easier to read
Arithmetic operations, including +, -, *, /, **, and %


Tip Calculator

Now that you've completed the lesson on Python syntax, let's see if you can put your newfound skills to use. In this lesson, you'll create a simple calculator that determines the price of a meal after tax and tip.

Tip Calculator

  • The Meal
    Now let's apply the concepts from the previous section to a real world example.

You've finished eating at a restaurant, and received this bill:

— Cost of meal: $44.50
— Restaurant tax: 6.75%
— Tip: 15%
You'll apply the tip to the overall cost of the meal (including tax).

  • The Tax
    Good! Now let's create a variable for the tax percentage.

The tax on your receipt is 6.75%. You'll have to divide 6.75 by 100 in order to get the decimal form of the percentage. (See the Hint if you would like further explanation.)

  • The Tip
    Nice work! You received good service, so you'd like to leave a 15% tip on top of the cost of the meal, including tax.

Before we compute the tip for your bill, let's set a variable for the tip. Again, we need to get the decimal form of the tip, so we divide 15.0 by 100.

  • Reassign in a Single Line
    Okay! We've got the three variables we need to perform our calculation, and we know some arithmetic operators that can help us out.

We saw in Lesson 1 that we can reassign variables. For example, we could say spam = 7, then later change our minds and say spam = 3.

  • The Total
    Now that meal has the cost of the food plus tax, let's introduce on line 8 a new variable, total, equal to the new meal + meal * tip.

The code on line 10 formats and prints to the console the value of total with exactly two numbers after the decimal. (We'll learn about string formatting, the console, and print in Unit 2!)

# Reassign meal on line 7!

meal = 44.50
tax = 0.0675
tip = 0.15



Strings & Console Output

This lesson will introduce you to strings and console output in Python, including creating string literals, calling a variety of string methods, and using the "print" keyword.

Strings

Another useful data type is the string. A string can contain letters, numbers, and symbols.

name = "Ryan"
age = "19"
food = "cheese"

In the above example, we create a variable name and set it to the string value ”Ryan”.
We also set age to ”19” and food to ”cheese”.
Strings need to be within quotes.

Practice

Excellent! Let's get a little practice in with strings.

Escaping characters

There are some characters that cause problems. For example:

'There's a snake in my boot!'

This code breaks because Python thinks the apostrophe in 'There's' ends the string. We can use the backslash to fix the problem, like this:

'There\'s a snake in my boot!'

Access by Index

Great work!

Each character in a string is assigned a number. This number is called the index. Check out the diagram in the editor.

c = "cats"[0]
n = "Ryan"[3]

In the above example, we create a new variable called c and set it to ”c”, the character at index zero of the string ”cats”.
Next, we create a new variable called n and set it to ”n”, the character at index three of the string ”Ryan”.
In Python, we start counting the index from zero instead of one.

"""
The string "PYTHON" has six characters,
numbered 0 to 5, as shown below:

+---+---+---+---+---+---+
| P | Y | T | H | O | N |
+---+---+---+---+---+---+
  0   1   2   3   4   5

So if you wanted "Y", you could just type
"PYTHON"[1] (always start counting from 0!)
"""
fifth_letter = "MONTY"[4]

print fifth_letter

String methods

Great work! Now that we know how to store strings, let's see how we can change them using string methods.

String methods let you perform specific tasks for strings.

We'll focus on four string methods:

len()
lower()
upper()
str()

Let's start with len(), which gets the length (the number of characters) of a string!

parrot = "Norwegian Blue"

print len(parrot)

lower()

Well done!

You can use the lower() method to get rid of all the capitalization in your strings. You call lower() like so:

"Ryan".lower()

which will return ”ryan”.

parrot = "Norwegian Blue"

print parrot.lower()

upper()

Now your string is 100% lower case! A similar method exists to make a string completely upper case.

parrot = "norwegian blue"

print parrot.upper()

str()

Now let's look at str(), which is a little less straightforward. The str() method turns non-strings into strings! For example:

str(2)

would turn 2 into ”2”.

"""Declare and assign your variable on line 4,
then call your method on line 5!"""
pi = 3.14

print str(pi)

Dot Notation

Let's take a closer look at why you use len(string) and str(object), but dot notation (such as ”String".upper()) for the rest.

lion = "roar"
len(lion)
lion.upper()

Methods that use dot notation only work with strings.

On the other hand, len() and str() can work on other data types.

ministry = "The Ministry of Silly Walks"

print len(ministry)
print ministry.upper()

Printing Strings

The area where we've been writing our code is called the editor.

The console (the window in the upper right) is where the results of your code is shown.

print simply displays your code in the console.

"""Tell Python to print "Monty Python"
to the console on line 4!"""

print "Monty Python"

Printing Variables

Great! Now that we've printed strings, let's print variables

String Concatenation

You know about strings, and you know about arithmetic operators. Now let's combine the two!

print "Life " + "of " + "Brian"

This will print out the phrase Life of Brian.

The + operator between strings will 'add' them together, one after the other. Notice that there are spaces inside the quotation marks after Life and of so that we can make the combined string look like 3 words.

Combining strings together like this is called concatenation. Let's try concatenating a few strings together now!

Explicit String Conversion

Sometimes you need to combine a string with something that isn't a string. In order to do that, you have to convert the non-string into a string.

print "I have " + str(2) + " coconuts!"

This will print I have 2 coconuts!.

The str() method converts non-strings into strings. In the above example, you convert the number 2 into a string and then you concatenate the strings together just like in the previous exercise.

Now try it yourself!

String Formatting with %, Part 1

When you want to print a variable with a string, there is a better method than concatenating strings together.

name = "Mike"
print "Hello %s" % (name)

The % operator after a string is used to combine a string with variables. The % operator will replace a %s in the string with the string variable that comes after it.

string_1 = "Camelot"
string_2 = "place"

print "Let's not go to %s. 'Tis a silly %s." % (string_1, string_2)

String Formatting with %, Part 2

Remember, we used the % operator to replace the %s placeholders with the variables in parentheses.

name = "Mike"
print "Hello %s" % (name)

You need the same number of %s terms in a string as the number of variables in parentheses:

print "The %s who %s %s!" % ("Knights", "say", "Ni")
# This will print "The Knights who say Ni!"
name = raw_input("What is your name?")
quest = raw_input("What is your quest?")
color = raw_input("What is your favorite color?")

print "Ah, so your name is %s, your quest is %s, " \
"and your favorite color is %s." % (name, quest, color)

And Now, For Something Completely Familiar

Great job! You've learned a lot in this unit, including:

Three ways to create strings

'Alpha'
"Bravo"
str(3)

String methods

len("Charlie")
"Delta".upper()
"Echo".lower()

Printing a string

print "Foxtrot"

Advanced printing techniques

g = "Golf"
h = "Hotel"
print "%s, %s" % (g, h)

Date and Time

This lesson is a follow up to Unit 2: Strings and Console input and will give you practice with the concepts introduced in that lesson.

The datetime Library

A lot of times you want to keep track of when something happened. We can do so in Python using datetime.

Here we'll use datetime to print the date and time in a nice format.

Getting the Current Date and Time

We can use a function called datetime.now() to retrieve the current date and time.

from datetime import datetime

print datetime.now()

The first line imports the datetime library so that we can use it.

The second line will print out the current date and time.

Extracting Information

Notice how the output looks like 2013-11-25 23:45:14.317454. What if you don't want the entire date and time?

from datetime import datetime
now = datetime.now()

current_year = now.year
current_month = now.month
current_day = now.day

You already have the first two lines.

In the third line, we take the year (and only the year) from the variable now and store it in current_year.

In the fourth and fifth lines, we store the month and day from `now.

Hot Date

What if we want to print today's date in the following format? mm/dd/yyyy. Let's use string substitution again!

from datetime import datetime
now = datetime.now()

print '%s-%s-%s' % (now.year, now.month, now.day)
# will print: 2014-02-19

Remember that the % operator will fill the %s placeholders in the string on the left with the strings in the parentheses on the right.

In the above example, we print 2014-02-19 (if today is February 19th, 2014), but you are going to print out 02/19/2014.

Pretty Time

Nice work! Let's do the same for the hour, minute, and second.

from datetime import datetime
now = datetime.now()

print now.hour
print now.minute
print now.second

In the above example, we just printed the current hour, then the current minute, then the current second.

We can again use the variable now to print the time.

Grand Finale

We've managed to print the date and time separately in a very pretty fashion. Let's combine the two!

from datetime import datetime
now = datetime.now()

print '%s/%s/%s' % (now.month, now.day, now.year)
print '%s:%s:%s' % (now.hour, now.minute, now.second)

The example above will print out the date, then on a separate line it will print the time.

Let's print them all on the same line in a single print statement!


Conditionals & Control Flow

In this lesson, we'll learn how to create programs that generate different outcomes based on user input!

Go With the Flow

Just like in real life, sometimes we'd like our code to be able to make decisions.

The Python programs we've written so far have had one-track minds: they can add two numbers or print something, but they don't have the ability to pick one of these outcomes over the other.

Control flow gives us this ability to choose among outcomes based off what else is happening in the program.

Go With the Flow

Just like in real life, sometimes we'd like our code to be able to make decisions.

The Python programs we've written so far have had one-track minds: they can add two numbers or print something, but they don't have the ability to pick one of these outcomes over the other.

Control flow gives us this ability to choose among outcomes based off what else is happening in the program.

Compare Closely!

Let's start with the simplest aspect of control flow: comparators. There are six:

Equal to (==)
Not equal to (!=)
Less than (<)
Less than or equal to (<=)
Greater than (>)
Greater than or equal to (>=)

Comparators check if a value is (or is not) equal to, greater than (or equal to), or less than (or equal to) another value.

Note that == compares whether two things are equal, and = assigns a value to a variable.

Compare... Closelier!

Excellent! It looks like you're comfortable with basic expressions and comparators.

But what about extreme expressions and comparators?

How the Tables Have Turned

Comparisons result in either True or False, which are booleans as we learned before in this exercise.

# Make me true!
bool_one = 3 < 5

Let's switch it up: we'll give the boolean, and you'll write the expression, just like the example above.

To Be and/or Not to Be

Boolean operators compare statements and result in boolean values. There are three boolean operators:

and, which checks if both the statements are True;
or, which checks if at least one of the statements is True;
not, which gives the opposite of the statement.
We'll go through the operators one by one.

"""
     Boolean Operators
------------------------      
True and True is True
True and False is False
False and True is False
False and False is False

True or True is True
True or False is True
False or True is True
False or False is False

Not True is False
Not False is True

"""

And

The boolean operator and returns True when the expressions on both sides of and are true. For instance:

1 < 2 and 2 < 3 is True;
1 < 2 and 2 > 3 is False.

Or

The boolean operator or returns True when at least one expression on either side of or is true. For example:

1 < 2 or 2 > 3 is True;
1 > 2 or 2 > 3 is False.

Not

The boolean operator not returns True for false statements and False for true statements.

For example:

not False will evaluate to True, while not 41 > 40 will return False.

This and That (or This, But Not That!)

Boolean operators aren't just evaluated from left to right. Just like with arithmetic operators, there's an order of operations for boolean operators:

not is evaluated first;
and is evaluated next;
or is evaluated last.
For example, True or not False and False returns True. If this isn't clear, look at the Hint.

Parentheses () ensure your expressions are evaluated in the order you want. Anything in parentheses is evaluated as its own unit.

Mix 'n' Match

Great work! We're almost done with boolean operators.

# Make me false
bool_one = (2 <= 2) and "Alpha" == "Bravo"

Conditional Statement Syntax

if is a conditional statement that executes some specified code after checking if its expression is True.

Here's an example of if statement syntax:

if 8 < 9:
    print "Eight is less than nine!"

In this example, 8 < 9 is the checked expression and print "Eight is less than nine!" is the specified code.

If You're Having...

Let's get some practice with if statements. Remember, the syntax looks like this:

if some_function():
    # block line one
    # block line two
    # et cetera

Looking at the example above, in the event that some_function() returns True, then the indented block of code after it will be executed. In the event that it returns False, then the indented block will be skipped.

Also, make sure you notice the colons at the end of the if statement. We've added them for you, but they're important.

Else Problems, I Feel Bad for You, Son...

The else statement complements the if statement. An if/else pair says: "If this expression is true, run this indented code block; otherwise, run this code after the else statement."

Unlike if, else doesn't depend on an expression. For example:

if 8 > 9:
    print "I don't printed!"
else:
    print "I get printed!"

I Got 99 Problems, But a Switch Ain't One

"Elif" is short for "else if." It means exactly what it sounds like: "otherwise, if the following expression is true, do this!"

if 8 > 9:
    print "I don't get printed!"
elif 8 < 9:
    print "I get printed!"
else:
    print "I also don't get printed!"

In the example above, the elif statement is only checked if the original if statement if False.

The Big If

Really great work! Here's what you've learned in this unit:

Comparators

3 < 4
5 >= 5
10 == 10
12 != 13

Boolean operators

True or False 
(3 < 4) and (5 >= 5)
this() and not that()

Conditional statements

if this_might_be_true():
    print "This really is true."
elif that_might_be_true():
    print "That is true."
else:
    print "None of the above."

Let's get to the grand finale.


PygLatin

In this lesson we'll put together all of the Python skills we've learned so far including string manipulation and branching. We'll be building a Pyg Latin translator. (That's Pig Latin for Python Programmers!)

Break It Down

Now let's take what we've learned so far and write a Pig Latin translator.

Pig Latin is a language game, where you move the first letter of the word to the end and add "ay." So "Python" becomes "ythonpay." To write a Pig Latin translator in Python, here are the steps we'll need to take:

Ask the user to input a word in English.
Make sure the user entered a valid word.
Convert the word from English to Pig Latin.
Display the translation result.

Ahoy! (or Should I Say Ahoyay!)

Let's warm up by printing a welcome message for our translator users.

Input!

Next, we need to ask the user for input.

name = raw_input("What's your name?")
print name

In the above example, raw_input() accepts a string, prints it, and then waits for the user to type something and press Enter (or Return).

In the interpreter, Python will ask:

What's your name? >

Once you type in your name and hit Enter, it will be stored in name.

Check Yourself!

Next we need to ensure that the user actually typed something.

empty_string = ""
if len(empty_string) > 0:
    # Run this block.
    # Maybe print something?
else:
    # That string must have been empty.

We can check that the user's string actually has characters!

Check Yourself... Some More

Now we know we have a non-empty string. Let's be even more thorough.

x = "J123"
x.isalpha()  # False

In the first line, we create a string with letters and numbers.

The second line then runs the function isalpha() which returns False since the string contains non-letter characters.

Let's make sure the word the user enters contains only alphabetical characters. You can use isalpha() to check this! For example:

print 'Welcome to the Pig Latin Translator!'

# Start coding here!
original = raw_input("Enter a word:")

if len(original) > 0 and original.isalpha():
    print original
else:
    print "empty"

Pop Quiz!

When you finish one part of your program, it's important to test it multiple times, using a variety of inputs.

Ay B C

Now we can get ready to start translating to Pig Latin! Let's review the rules for translation:

You move the first letter of the word to the end and then append the suffix 'ay'.
Example: python -> ythonpay

Let's create a variable to hold our translation suffix.

Word Up

Let's simplify things by making the letters in our word lowercase.

the_string = "Hello"
the_string = the_string.lower()

The .lower() function does not modify the string itself, it simply returns a lowercase-version. In the example above, we store the result back into the same variable.

We also need to grab the first letter of the word.

first_letter  = the_string[0]
second_letter = the_string[1]
third_letter  = the_string[2]

Remember that we start counting from zero, not one, so we access the first letter by asking for [0].

Move it on Back

Now that we have the first letter stored, we need to add both the letter and the string stored in pyg to the end of the original string.

Remember how to concatenate (i.e. add) strings together?

greeting = "Hello "
name = "D. Y."
welcome = greeting + name

Ending Up

Well done! However, now we have the first letter showing up both at the beginning and near the end.

s = "Charlie"

print s[0]
# will print "C"

print s[1:4]
# will print "har"

First we create a variable s and give it the string "Charlie"
Next we access the first letter of "Charlie" using s[0]. Remember letter positions start at 0.
Then we access a slice of "Charlie" using s[1:4]. This returns everything from the letter at position 1 up till position 4.
We are going to slice the string just like in the 3rd example above.

Testing, Testing, is This Thing On?

Yay! You should have a fully functioning Pig Latin translator. Test your code thorougly to be sure everything is working smoothly.

You'll also want to take out any print statements you were using to help debug intermediate steps of your code. Now might be a good time to add some comments too! Making sure your code is clean, commented, and fully functional is just as important as writing it in the first place.

pyg = 'ay'

original = raw_input('Enter a word:')

if len(original) > 0 and original.isalpha():
    word = original.lower()
    first = word[0]
    new_word = (word + first + pyg)[1:len(new_word)]
    print new_word
else:
    print 'empty'

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,214评论 6 481
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,307评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 152,543评论 0 341
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,221评论 1 279
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,224评论 5 371
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,007评论 1 284
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,313评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,956评论 0 259
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,441评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,925评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,018评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,685评论 4 322
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,234评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,240评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,464评论 1 261
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,467评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,762评论 2 345

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,389评论 0 23
  • 早上醒来,面对杂乱无章的衣柜,不知道穿哪件好。看着嗷嗷待哺的孩子,感觉要做的事还太多。还不容易收拾完家里的一地鸡毛...
    linna_6304阅读 500评论 1 2
  • 最近很喜欢把要做的事已确定目标的内容,用导图或其他的方式画出完整的内容来(如图),看到这样的图是不是有一种不明觉厉...
    靈素阅读 410评论 0 3
  • 妹妹生了小宝宝~~哇塞塞~~只能说出这句话,别的只求他们一切安好,事实也是这样的,所以我还是只能哇塞塞~~ 没有相...
    青蛇君阅读 475评论 0 0
  • 好朋友天儿上个月考研结束后,离开了北京,去三亚发展了。虽然都不情愿,但我们还是默默的祝福着。天儿不仅是我生活中的好...
    陈颢阅读 974评论 0 2