转载请注明出处:http://blog.csdn.net/cxsydjn/article/details/71302863
The note summaries conditionals, control flow and a game implemented by Python.
Python notes of open courses @Codecademy.
Conditional Statement Syntax: If, Else and Elif
if: is a conditional statement that executes some specified code after checking if its expression is True. if some_function(): 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. Note the colons at the end of the if statement. else: 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.”Elif: is short for “else if.” It means that “otherwise, if the following expression is true, do this!”
# Example for `If`, `Else` and `Elif` 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."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. Input raw_input(): accepts a string, prints it, and then waits for the user to type something and press Enter (or Return). This string can also be stored in a variable, e.g., name = raw_input("What's your name?").isalpha(): which returns False since the string contains non-letter characters.Output
String[1:4]: accesses a slice of “String”, i.e., returns everything from the letter at position 1 up till position 4 (note not including the position 4).
# Example for PygLatin print 'Welcome to the Pig Latin Translator!' 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 new_word = new_word[1:len(new_word)] print new_word else: print 'empty'