Python控制结构

1. Python控制结构简介

2. 定义函数 

<1>. Python控制结构 

 1.1 if

print("#############if statement###############");
x = int(input("Enter an integer :"));
if x < 0 :
    x = 0;
    print("Negative changed to zero .");
elif x == 0 :
    print("Zero");
elif x == 1 :
    print("Single");
else :

    print("None"); 

1.2 for

############################for statement
print("#############for statement###############");
a = ['cat', 'window',  'defenestrate'];
for x in a :
    print(x, len(x));
    
print("#############range function###############");
for i in range(5) :
    print(i);
a = ['Mary', 'had', 'a', 'little', 'lamb'];
for i in range(len(a)) :

    print(i, a[i]); 

1.3 break and continue

print("#############break and continue###############");
for n in range(2, 10) :     # 2 - 9
    for x in range(2, n):
        if n % x == 0 :
            print(n, 'equals', x,  '+', n // x);
            break;
        else :
            print(n);

1.4 pass

# ########################pass action test ##############
if False :
    pass;   ''' do nothing '''

<2>. 定义函数 

 2.1 定义函数基础

# define the function
def fib(n):
    # print the Fibonacci series up to n.
    a, b = 0, 1;
    while  a < n :
        print a;

        a, b = b, a +b; 

2.2 函数默认参数 

'''  
    default arguments
'''
def ask_ok(prompt, retries = 4, complaint = 'Yes or no, please') :
    while True:
        ok = raw_input(prompt);
        if ok in ['y', 'Y', 'yes'] :
            return True;
        if ok in ['n', 'no', 'nop'] :
            return False;
        retries = retries - 1;
        if retries < 0:
            raise IOError('refusenik user');

        print complaint; 

2.3 不定参数

'''
    Arbitrary arguments function
'''
def arbitraryArgsFunc(arg1, *args):
    
    # just print the arbitrary arguments 
    for i in range(0, len(args)):
        print(args[i]);
        

arbitraryArgsFunc('arg1', 'arg2', 'arg3'); 

2.4 Lambda表达式

'''
    lamba function, just like the function  template
'''
def make_incrementor(n):
    return lambda x:x + n;
f = f = make_incrementor(42);

print(f(0)); 

posted @   qiang.xu  阅读(1324)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示