Python 基本语法

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"



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值