Q1: week2-3, Ex-guess my number

在做week2练习:guess my number时遇到一个小问题。
代码已经写好,结果也和给出的答案一样,但是格式有一点不同,如下:
# 这是我的output
Please think of a number between 0 and 100!
Is your secret number 50?
Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.
l
# 这是答案expected output
Please think of a number between 0 and 100!
Is your secret number 50?
Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. l

可以发现区别在于答案的输入l是在“Enter ‘h’ to indicate the guess is too high. Enter ‘l’ to indicate the guess is too low. Enter ‘c’ to indicate I guessed correctly.”的同一行,而我的有一个换行,调整了半天也不知道如何让他们处于同一行,故请教大大们。我的代码如下,比较丑陋…

i = 50
low = 0
high = 99
print('Please think of a number between 0 and 100!')
print('Is your secret number: 50?')
while True: print("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.")a = input() # 问题出在这里,如何能将input和上面的print内容显示在一行里if a != 'h' or 'l' or 'c':print('Sorry, I did not understand your input.')print('Is your secret number:' + str(i) + '?')print("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.")a = input()elif a == 'l':low = ii = int((i+high)/2)print('Is your secret number:' + str(i))elif a == 'h':high = ii = int((low+i)/2)print('Is your secret number:' + str(i))else:print('Game over. Your secret number was:' + str(i))

lmz:

a = input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.")

此外你的代码如果输入的字符不是‘h,l,c’中的一个,你有没发现,他会要求你输入2次input?
具体实现我倒是做了笔记

bigjing:

你的代码除了在input处存在问题外,运行逻辑上存在一些小问题,在不改变你整体框架的前提下,现做如下修改

第9行 if a !='h' or 'l' or 'c'应改为:a != 'h' and a != 'l' and a !='c'
第13行 a = input() 改为 continue
第22行 else: 后需要加 break,否则循环无法终止

修改后完整代码:

i = 50
low = 0
high = 99
print('Please think of a number between 0 and 100!')
print('Is your secret number: 50?')
while True: a = input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.") # 问题出在这里,如何能将input和上面的print内容显示在一行里if a != 'h' and a != 'l' and a !='c':print('Sorry, I did not understand your input.')print('Is your secret number:' + str(i) + '?')continueelif a == 'l':low = ii = int((i+high)/2)print('Is your secret number:' + str(i))elif a == 'h':high = ii = int((low+i)/2)print('Is your secret number:' + str(i))else:print('Game over. Your secret number was:' + str(i))break

根据对题目理解,我重新写了一个,供参考

low = 0
high = 100
guess = 50
print('Please think of a number between 0 and 100!')
print('Is your secret number:{}?'.format(guess))
while True: a = input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.") if a == 'c':print('Game over. Your secret number was:{}'.format(guess) )breakelif a in ['l','h']:if a == 'l':low = guesselse:high = guessguess = (high+low)//2print('Is your secret number:{}'.format(guess))continueelse:print('Sorry, I did not understand your input.')  continue

lmz:

# week2-3 Exercise: guess my numberprint('Please think of a number between 0 and 100!')
low = 0
high = 100def guess_wrong_ans(ans):global high, lowif ans == 'c':print('Game over. Your secret number was: %s' % mid)return False elif ans == 'h':high = midelif ans == 'l':low = midelse:print('Sorry, I did not understand your input.')return Truestatus = True
while status:mid = (low + high)//2   print('Is your secret number %s?' % mid)ans = input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. ")status = guess_wrong_ans(ans)

Q2: 程序运行方法

程序运行方法有三种,比如说print(‘hello world’):
1. 在命令行直接运行;
2. 编写一个 Python 文件,将 print hello world 封装为一个函数,通过 main 函数调用它来运行;
3. 编写一个 class,将 print hello world 封装为一个 method,通过 main 函数创建 class 实例来运行 method。
后两种方式怎样实现,能举个例子么?

SY:

我的理解是第一个是直接运行,第二个是通过函数,第三个是通过类的方法。

lmz:

# 2.hello.py
def hello():print("hello world")if __name__ == '__main__':hello()
# 3.hello.py
class hello(object):def helloworld(self):print("hello world")def main():       text = hello()     # 初始化实例text.helloworld()  # 调用类的方法if __name__ == '__main__':main()

bigjing:

能解释下python编程中的if __name__ == 'main': 的作用和原理么?

lmz:

if __name__ == '__main__' 的意思是说,只有直接运行python hello.py时,该if条件下的语句才会执行,可以参考廖雪峰的网站链接。
当我们在命令行运行hello模块文件时,Python解释器把一个特殊变量__name__置为__main__,而如果在其他地方导入该hello模块时,if判断将失败,因此,这种if测试可以让一个模块通过命令行运行时执行一些额外的代码,最常见的就是运行测试。

bigjing:

凡星的解释已经很完整了,附另一个解释比较好的连接,供大家学习

Q3: 数组转换

经常能看到对数组进行reshape(-1,1)操作
我们知道reshape(2,3)是转成2行3列。
那reshape(-1,1)这个操作实现的功能是什么?
虽然从结果上来看好像是转成多行一列,-1的存在是固定写法么?

lmz:

Parameters: a : array_like, Array to be reshaped.newshape : int or tuple of ints
The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.

案例的话,知乎

c = np.array([[1,2,3],[4,5,6]])
# python2代码
print '改成2行3列:'
print c.reshape(2,3)
print '改成3行2列:'
print c.reshape(3,2)
print '我也不知道几行,反正是1列:'
print c.reshape(-1,1)
print '我也不知道几列,反正是1行:'
print c.reshape(1,-1)
print '不分行列,改成1串'
print c.reshape(-1)
输出为:改成2行3列:
[[1 2 3]
[4 5 6]]
改成3行2列:
[[1 2]
[3 4]
[5 6]]
我也不知道几行,反正是1列:
[[1]
[2]
[3]
[4]
[5]
[6]]
我也不知道几列,反正是1行:
[[1 2 3 4 5 6]]
不分行列,改成1串
[1 2 3 4 5 6]

Q4.函数参数

P33:关键字参数与默认参数的区别?

bigjing:

首先一个观点:关键字参数是包含默认参数范畴的
当关键字参数作为形参的时候,就是默认参数
当关键字参数作为实参的时候,可以实现不按位置赋值参数的作用

Q5. 入栈顺序(函数运行空间)

P35:入栈顺序,为什么第1列中x在f之后,第2列中h在g之后入栈?

bigjing:

拓展一下问题:
什么是栈
什么是栈帧
栈和栈帧有什么区别
函数调用栈帧的过程

lmz:

我就不从概念上去解释了,而是按照我的理解解释:

  1. 栈(stack)——一种FILO(先进后出)的数据结构,python里运行函数就是用的这种结构
  2. python执行函数时,会新开一个局部空间(也就是书中的stack frame, 中译文栈帧),函数执行完后,除了返回的数据,该局部空间也就销毁了(即: 你不能再访问该局部空间里的变量了)
  3. 由于python每次执行函数,都是先跳到函数内部执行完毕后,再返回原空间继续,所以说这是一种FILO(或LIFO)的执行顺序,然后中间涉及的变量储存就是对应的栈结构了。

书中对应的内容,讲的就是python执行代码过程中,变量的产生和销毁的顺序。

PYTHON编程导论群问题汇总(三)相关推荐

  1. PYTHON编程导论群问题汇总(一)

    问题1 [Jane] 课程视频用的是python 2.7并推荐了一个软件 可是书上用的是python 3 所以是安装视频推荐的软件来学习 还是用自己的python 3好呢 Bigjing 推荐pyth ...

  2. PYTHON编程导论群问题汇总(二)

    问题1 [lmz] 为什么说计算机储存整数(int)是精确的 而储存小数(float)则是不精确的? Aris 我举2个例子, 还原计算机如何表示 0.625, 0.1 问题2 [lmz] Guess ...

  3. PYTHON编程导论群问题汇总(四)

    Q6. 函数局部变量赋值问题 P37:"print语句后面的赋值语句使x成为函数g中的局部变量 执行print语句时还没有被赋值."报错的原因不是很理解~ bigjing: 在回答 ...

  4. PYTHON编程导论群问题汇总(五)

    Q15.改变对象与绑定 P54:Univs和Univs1被绑定到不同的对象的原理不是很清楚. bigjing: Univs = [Techs, Ivys] Univs1 = [['MIT', 'Cal ...

  5. PYTHON编程导论群【提问与解惑】数据统计

    第一周 # 第一周 import matplotlib.pyplot as plt import seaborn as sns plt.rcParams['font.family'] = ['SimH ...

  6. python交互式程序设计导论答案第五周_学堂在线_计算机科学与Python编程导论_章节测试答案...

    学堂在线_计算机科学与Python编程导论_章节测试答案 更多相关问题 素描的三种表现形式是:(). 运行下列程序:Private Sub form_Click()For i = 1 To 2x = ...

  7. 计算机编程导论python程序设计答案-学堂在线_计算机科学与Python编程导论_作业课后答案...

    学堂在线_计算机科学与Python编程导论_作业课后答案 答案: 更多相关问题 近代中国完全沦为半殖民地半封建社会的标志是:A.<马关条约>B.<辛丑条约>C.<凡尔赛和 ...

  8. Python 编程导论 Chapter 4 —— 函数、作用域与抽象

    typora-copy-images-to: Risk Management and Financial Institution typora-copy-images-to: Python 编程导论 ...

  9. 计算机编程导论python程序设计答案-学堂云_计算机科学与Python编程导论_作业课后答案...

    学堂云_计算机科学与Python编程导论_作业课后答案 答案: 更多相关问题 保本基金参与股指期货交易,应当根据风险管理的原则,以套期保值为目的.() 基金经理主要依据股票投资价值报告来决定实际的投资 ...

最新文章

  1. 湖南大学让晶体管小至3纳米,沟道长度仅一层原子 | Nature子刊
  2. 没学过编程可以自学python吗-我以前从没学过编程,学Python看什么书?
  3. 打开深蓝医生的国庆大礼包!
  4. vue中通过数据双向绑定给video标签的src赋值,只有第一次有效,怎么解决?
  5. python app服务器_Python应用02 Python服务器进化
  6. cuda-Block和Grid设定
  7. QML-关于Qt.rgba()颜色无法正常显示问题
  8. C# 10 新特性 —— Lambda 优化
  9. Spring IO platform
  10. 【python】filter()
  11. 如何快速安装kafka-manager
  12. 【Flink】Flink yarn 下报错ClassNotFoundException: org.apache.hadoop.yarn.api.ApplicationConstants$Environ
  13. 程序员找工作黑名单:除了 996.ICU,程序员还将如何自救?
  14. Julia : Some, something, Nothing
  15. 爬虫入门-爬取有道在线翻译结果(1)
  16. HSV颜色空间中颜色(红、黄、绿、 青、蓝、紫、 粉红、 砖红、 品红)对应的灰度范围
  17. matplotlib保存图片去除白边
  18. 西门子200SMART(六)数据块
  19. 重磅!网页版 VSCode 来了!
  20. (二十三)Kotlin简单易学 基础语法-什么是函数式编程

热门文章

  1. iOS 自定义UITabBar
  2. Elasticsearch——Rest API中的常用用法
  3. CSS 布局:40个教程、技巧、例子和最佳实践
  4. POJ-1185 炮兵阵地 动态规划+状态压缩
  5. PHP Session中保存Object
  6. 神州6号发射成功了--庆祝一下
  7. 【青少年编程】马雷越:商品价格竞猜
  8. 技术图文:Matlab VS. Numpy 常见矩阵
  9. 【ACM】杭电OJ 2040
  10. KNN 分类算法原理代码解析