zoukankan      html  css  js  c++  java
  • Python体验(01)变量、函数和基本控制语句

    今天安装了Debian5,没想到基础安装的情况下居然会有python,于是安装试试这个传说中的语言。

    下面通过一系列简单示例来体验,代码可以直接粘贴保存,都通过测试。

    我参照pdf学习的,大家可以从这个地址下载pdf文件.

    案例1:

    #用于注释,但第一行#!也给程序指出本代码是靠/usr/bin/python执行的,所以文件名可以不是py
    如果你乐意,你可以给helloworld.py 增加属性X,这样你可以把它改成任意的文件名直接执行,如hello。

    #!/usr/bin/python
    #filename:helloworld.py
    print '\n\tHello World! That\'s Python!\n'
    #if you want the .py file to be executable:chmod a+x helloworld.py


     案例2:

    变量不用声明可以直接赋值;if/elif/else语句不用包括判断语句且以:结尾;

    代码
    #!/usr/bin/python
    #filename:raw_input.py

    number = 23 #here no ; but you can add ; either
    guess = int(raw_input("Enter an Integer:")); #string,can use ' or "

    if guess == number: #notice: no () and there's a :
            print 'Congratulations, you guessed it.'
            
    print '(but you do not win any prizes!)'
    elif guess < number:
            
    print "No, It's a little higher than what you input."
    else:
            
    print 'No,It\'s a little lower than what you input.'

    print "Done!";


     案例3:猜数字游戏,5次猜不对就退出

    while循环,break跳出;省去了类似C语言的{}而改用对齐来决定语句块

    代码
    #!/usr/bin/python
    #filename:while.py

    number = 23
    Hitting = False
    loop = 5

    while not Hitting:
            guess = int(raw_input("Guess what(" + str(loop) +" times left):"))
            loop = loop -1 ;
            
    if loop == 0:
                    
    print "\tToo stupid, you lost!"
                    
    break;
            
    if guess > number :
                    
    print "\tYour number is bigger than that."
            
    elif guess < number:
                    
    print "\tYour number is littler than that."
            
    else:
                    Hitting = True;
                    
    print "\tYou WIN, Excellent Baby!"
    print "\t--===--[DONE]--===--"
    #the Done statement is line to while, so running out of while then "Done" execute.


     示例4:函数,默认参数,有返回值;DocString

    代码
    #!/usr/bin/python
    #filename:function.py

    def value(num = 3): #there's default parameter.
            '''Coded by Phoenix :

            RET(X) = X^X''' #DocStrings
            ret = 1;
            
    for i in range(0,num): #notice, there is :
                    ret = ret * num
            
    return ret

    number = int(raw_input("Input a number:"))
    print value()
    print number**number
    print value(number) #output the x^x, by the way, you can use: x**x
    print value.__doc__ #output DocStrings


  • 相关阅读:
    Python 远程开机
    Python 爬虫利器 Selenium
    Python爬虫——Python 岗位分析报告
    Python 爬虫入门(二)——爬取妹子图
    Python 爬虫入门(一)——爬取糗百
    边缘计算—你了解吗?
    关于图片适配不同尺寸的image View(实战)
    HTML页面转换为Sharepoint母版页(实战)
    SharePoint中你不知道的图片库(实战)
    Sharepoint 2013搜索服务配置总结(实战)
  • 原文地址:https://www.cnblogs.com/flaaash/p/1882735.html
Copyright © 2011-2022 走看看