python例题

2018-02-10  本文已影响0人  小爷很飘

for循环、if 、乘方 、continue 、除法

for i in range(100,1000):
    a = i//100 # 取百分位
    b = i//10%10 # 取十分位
    c = i%100%10 # 取个位数
    if i == a**3 +b**3 + c**3:
        print(i)
    else:
        continue

输入输出、while循环

import sys
n = int(input("input number:\n"))
print("n = %d" % n)
for i in range(2,n+1):
    while n != i:
        if n % i == 0:
            sys.stdout.write(str(i))
            sys.stdout.write("*")
            n = n//i
        else:
            break
        print("%d" %n)

日期操作

import datetime
# 输出今日日期,格式为 yyyy/mm/dd。更多选项可以查看 strftime() 方法
print(datetime.date.today().strftime("%Y-%m-%d"))
print(datetime.datetime.now().strftime("%d/%m/%Y %H:%M:%S"))
# 创建日期对象
miyazakiBirthDate = datetime.date(2015,5,31)
print(miyazakiBirthDate.strftime("%d/%m/%Y"))
miyazakiBirthNextDay = miyazakiBirthDate + datetime.timedelta(days=2)
print(miyazakiBirthNextDay)

批量打印

from sys import stdout

for i in range(4):
    stdout.write("*")
print()

函数定义,递归

# 阶层计算
def fact(j):
    if j == 0:
        sum = 1
    else:
        sum = j * fact(j-1)
    return sum
for i in range(6):
    print("%d!=%d"%(i,fact(i)))

字符串操作

from sys import stdout
s = input("Input a string:")
l = len(s)
stdout.write(s[l-1])
print(l)

数组foreach

def geArr(i):
    h = [];
    for j in range(i):
        h.append(j)
    return  h;
l = geArr(10);
for each in l:
    print(each)

if elif

m = 2;
if 1>m :
  print(1)
elif  3>m:
  print(2)
上一篇下一篇

猜你喜欢

热点阅读