2. String and Console Output
len() 输出长度(包括空格)
parrot = "Norwegian Blue"
print len(parrot)
lower() 全变小写parrot = "Norwegian Blue"
print "Norwegian Blue".lower()
upper() 全变大写parrot = "norwegian blue"
print "norwegian blue".upper()
str()
pi = 3.14
print str(pi) #turns non-strings into strings
dot notation only work with strings. len() and str()
can work on other data types.
String concatenation
print "Spam " + "and " + "eggs"
Explicit string conversion
print "The value of pi is around " + str(3.14)
String formatting with %
print "Let's not go to %s. 'Tis a silly %s." % (string_1, string_2) #Let's not go to Camelot. 'Tis a silly place.
Remember, we used the % operator to replace the %s placeholders with the variables in parentheses.
The datetime library
from datetime import datetime
now = datetime.now()
print now #2017-09-04 02:39
print now.year #2017
print now.month #9
print now.day #4
print '%s/%s/%s' % (now.month, now.day, now.year #9/4/2017
print '%s:%s:%s' % (now.hour, now.minute, now.second) #2:43:52
3. Conditions and Control Flow
Go with the flow
def clinic():
print "You've just entered the clinic!"
print "Do you take the door on the left or the right?"
answer = raw_input("Type left or right and hit 'Enter'.").lower()
if answer == "left" or answer == "l":
print "This is the Verbal Abuse Room, you heap of parrot droppings!"
elif answer == "right" or answer == "r":
print "Of course this is the Argument Room, I've told you that already!"
else:
print "You didn't pick left or right! Try again."
clinic()
clinic()
Compare operators
"not" is evaluated first, "and" is evaluated next, "or" is evaluated last.
eg: not not True or False and not True. result is True.
# Make me false!
bool_one = (2 <= 2) and "Alpha" == "Bravo" # We did this one for you!
# Make me true!
bool_two = "use" != "hh" and not False or False
# Make me false!
bool_three = 3<2 or False and not False
# Make me true!
bool_four = 3>2 or False and not False
# Make me true!
bool_five = not False or (2>3) and not True
elif
def greater_less_equal_5(answer):
if answer>5:
return 1
elif answer<5:
return -1
else:
return 0
Pyglatin Game
word = raw_input ("please enter a word in English: ")
first = word[0]
pyg = "ay"
new_word = word + pyg
if len(word) >0 and word.isalpha():
new_word = word[1:] + pyg
print new_word
else:
print "empty"