针对初学者的《python 核心编程第二章习题答案》——半详解

来源:互联网 发布:极有家 知乎 编辑:程序博客网 时间:2024/05/17 01:23
在上一篇中已经说过了在哪里下载以及安装对应的 python 编码环境,有需要学习的初学者宝宝去上篇瞅瞅。
本篇着重讲《Python 核心编程》的第二章习题哦~  我从一个初学者的角度来讲哈(我自己也是初学者啦)
这个是最简单的输出 hello world ,话说有个笑话是以为退休的程序员百无聊赖想着得学点什么,最后选择了书法,拿起毛笔,举笔良久不知该写什么,最后毅然落下“hello world”2333
print 语法在不同的 python 版本里会有些许偏差,还有一种是不带括号的写法
#print("hello world!")
注释语法
单行注释时在句首加一个 # 号即可
多行注释时,在行首和行尾分别添加 ''' 即可
另一个必用的简单函数,初学者一定会用到的等待用户输入。#等待用户输入内容函数: input, 3.x 以后 Input 等效于之前版本的 raw_input#input_name = input("enter your name:")#print(input_name)#python 核心编程第二章习题 2-7    #while 循环'''string1 = input("enter a string please:")i = len(string1)                           # 或者用户输入的 string 长度, len 是自带函数j = 0while j < i:                               # while 循环的语法跟其他语言类似,不往细了说咯    print(string1[j])    j += 1    #for 循环string1 = input("enter a string please:")    for item in string1:                       # 这个是 for 循环跟其他语言不太一样,需要理解一下,这里相当于把每个字母当成一个 item 去输出    print(item)'''#while 循环实现 2-8'''atuple = (1,2,3,4,5)tulength = len(atuple)i = amount = 0while i<tulength:    amount += atuple[i]    i+=1print(amount)i = 0amount = 0list_for_user = []while i<5:    j = int(input("enter a number:"))    list_for_user.append(j)    amount += list_for_user[i]    i += 1print(list_for_user)print(amount)'''#for 循环实现2-8'''alist = []                  #创建一个空的列表i = 0amount = 0for i in range(5):    j = int(input("enter a number:"))    alist.append(j)                       #由于列表是空的,所以不能使用[1]这种序号来查询,只能用 append 函数在列表尾部添加元素    amount += alist[i]print(alist)print(amount)'''#2-9atuple = (1,2,3,5,7)i=0len_of_atuple = len(atuple)for item in atuple:    i += itemprint(i/len_of_atuple)#2-10'''num = int(input("enter a number between 1 to 100:"))        #我这个用户默认输入的是 string 不进行 int 转换的话会报错i = 1while i != 0:    if 1 <= num <= 100:        print("succeed")        i = 0;    else:        num = int(input("you shoule enter a num between 1 to 100:"))'''#2-11'''print("1 means get amount of five nums, 2 means get average of five nums, X means ending ")flag = 1amount = 0condition = "c"while condition != "X":    while condition != "X":        while flag == 1:            j = input("enter your choose:")            if j == "1" or j == "2" or j == "X":                flag = 2            else:                print("selece your choice from 1,2,X")        if j == "1":            for i in range(5):                amount += int(input("enter a num:"))            print(amount)            flag = 1        elif j == "2":            for i in range(5):                amount += int(input("enter a num:"))            print(amount / 5)            flag = 1        else:            condition = "X"'''#2-12#print(dir.__doc__)
阅读全文
0 0
原创粉丝点击