Python入门&题目的思考

来源:互联网 发布:淘宝商城墙纸 编辑:程序博客网 时间:2024/06/05 19:33

序言:

作为一个新手,记忆并不是必须的,对于概念,太多了容易混杂,应用于实践才是王道。

勤用F1,多看帮助文档,不需要自己亲自记忆关于语法的内容。

(就如同使用Python IDLE 中,使用Help->Python Docs 查看 Python 文档一样

思考是编程的核心(个人观点),解决一个问题,思维最重要,怎么解?解的过程。思维方式可以复制运用到很多地方,然而一道题记住答案并不能解更多的题。

以下题目均为原创思考过后的代码,网上大神的代码精彩纷呈,照搬照抄并没有实际意义。

仅作为自我总结和知识点提示。


我是新手

基本上,除了windows 需要下载安装 Python 外,Linux 以及 Macintosh 系统都已经预先安装好了 Python 了。


1. 求余运算 (%)真的很有用:

判断奇偶 —— (x%2) == 0,每十分钟做某事—— x%10 == 0


2. import 引入模块:(以下三者效果相同)

模块.函数  形式使用函数

import mathprint math.floor(5.9)
变量存储函数
import mathfloor = math.floor # notice there is no ()print floor(5.9)
直接引入函数(最好不用这种方式,可能会造成命名冲突)
from math import floorprint floor(5.9)
以上 floor 为实验对象,使用 int() 更愉悦

那么前面说到可能会造成命名冲突,怎么解决呢?提供两种方法

a. 使用 module.methond() 形式调用相应的方法

b. 重命名方法:

from math import sqrt as foobarprint foobar(4)

3. Windows环境下我想双击程序让他停留时间更长一些:

raw_input("Press any key :")


4. 单双引号的相互扶持

print "let's go"print 'let\'s go'print 'let\'s say "hello world"'


5. 使用 ‘+’ 就要时刻注意

temp = 42print "String and",tempprint "String and " + "temp" print "String and " + `temp` # it's better to use repr()print "String and " + repr(temp) # repr() create one string,for pythonprint "String and " + str(temp) # for user easy to readprint "String and" + temp # "+" must concatenate same type

6. 字符串里包含特殊字符怎么办?

原始字符串让你明白:r 和 raw_input() 

</pre><pre name="code" class="python">print r'hello \n world'#print r'let's go' # quotation issueprint r'let\'s go' # \ will be printedprint r"let's go"#cannot use \ in r#print r'this is no correct\'print r'this is correct\\'  # all \ will print outprint r'don print double :''\\' # just print one \temp  = raw_input("Enter:")# input: hello \n worldprint temp


7. Python 的惯例:

(起始索引,结束索引) 以这种形式出现的,一般不包含结束索引位置,即到结束索引-1 的位置


8. 使用字符串代替int表示一些具有特殊含义的数字:

例如电话号码

tel = 0106print tel

* reference & inspiration:网易云课程第二周


1. 判断用户输入的数是偶数?奇数?——偶数为True,奇数为False

解:

print not bool( int( raw_input() ) % 2 )
首先,使用 raw_input() 函数之后得到的用户的数据类型是 String类型,要与int类型的2进行求余运算,可以考虑——这是需要类型转换的

其次,能被2整除的是(余数则是0)偶数,0——>False,所以需要进行的是取非

以下为错误的程序:

print not bool(raw_input() % 2)

很显然,String是没有办法和int类型进行运算的,“Traceback!!!!”

raw_input() 得到的是 String,String不能直接与数字类型进行运算

偶数 % 2 == 0 ,  0代表boolean中的False

 来看一个典型的由 raw_input() 引起的错误:

此题意在解决在素数之内查找x

def prime(n):    lst = []    for i in range(2, n):        for j in range(2, i):            if i % j == 0:                break        else:            lst.append(i)    return lstn = 10lst = prime(n)x = raw_input("Enter num: ")def bi_search(x, low, high):    guess = (low + high) / 2    print lst[guess], x    if (x == lst[guess]):        return guess    elif low > high:        return -1    elif lst[guess] > x:        print 'lst[guess] > x'        return bi_search(x, low, guess -1)    elif lst[guess] < x:        return bi_search(x, guess + 1, high)        print bi_search(x, 0, len(lst)-1 )  
enter 数字 7,你会发现return 的值并不是你想要的。

使用 单步调试 帮助定位问题,很容易就可以知道到底哪出了错了。


2. 运算T

假设你每年初往银行账户中1000元钱,银行的年利率为4.7%。
一年后,你的账户余额为:
1000 * ( 1 + 0.047) = 1047 元
第二年初你又存入1000元,则两年后账户余额为:
(1047 + 1000) * ( 1 + 0.047) = 2143.209 元
以此类推,第10年年末,你的账户上有多少余额?
                                                                                        注:结果保留2位小数(四舍五入)。

解:

每年存入1000,每年利率为0.047(本息则是1+0.047)——为不变的量

10年为累计量,使用for循环前开后闭,0~9 == (0,10) 括号内的10并不计入

函数 format(variable, '.2f')  保留两位小数

sum = 0for i in range (0,10):    sum += 1000    sum *= (1 + 0.047)print format(sum, '.2f')

总结:

for后面一定要加 冒号:,冒号:后面是缩进,Python没有任何标示代码块的东西,也就只有冒号:和缩进能够标示


3. 接收用户输入的一个秒数(非负整数),折合成小时、分钟和秒输出

解:

时分秒之间的转换,大的最先除,越除越小

sec = int( raw_input("Enter time second:") )hour = sec / 3600mins =  (sec % 3600) / 60sec = (sec % 3600) % 60print hour, mins, sec
总结:

raw_input()  —— String,String并不能与数字类型相运算

“,”会插入一个空格


* reference & inspiration:An Introduction to Interactive Programming in Python (Part 1)

1.


2.

In Python 2 (the version of Python that we are learning), what is the value of -9 / 4?  

在Python2中,-9/4的值是多少

the answer is : -3  

答案是:-3

Python 2 always return the next lowest integer after you do the exact division, in another word, the result is always the minor integer than you get in the real world (If both operands are ints, the answer is an int (rounded down))

Python 2 总是返回在你进行准确除法之后向下取整的结果,换句话来说,在Python 2中你总是会得到比你实际所除的结果小的整数(如果两个操作数都是int类型,结果也会是int——想下取整)


3. 认识一个新的操作符://

/ 都很熟悉——常常用于除法

// 也是用于除法,只取整,浮点数也取整

两者的用法不同 


4. 负数的余数?

首先来看一组程序:

width = 800position = 797move = 5position = (position + move) % widthprint 'now the position is:',positionwidth = 800position = 2move = -5#print position + moveposition = (position + move) % widthprint 'now the position is:',position

-3 % 800的结果是什么?如果是 3 % 800 则余数是3

-3 % 800 =797( 因为 -3 =  -800 *1 + 797 )

正如视频中所说,这组程序可以用于screen wrapping in your games

我们以+800作为右,-800作为左,分别来添加一个屏幕。

那么上述一组程序就可以这么来看:797向右位移5,多出的部分向+800屏幕移动(以+800取余),就会移动到新屏幕的+2位置;

                                                               在+2的位置上反向移动-5,超过的部分向-800屏幕移动(以-800取余),就会移动到原位置;

移动过去,移动回来。reminder works in both directions

0 0
原创粉丝点击