鱼C论坛

 找回密码
 立即注册

python学习小菜笔记——第四课(改进我们的小游戏)

已有 1522 次阅读2014-8-7 14:43 |个人分类:Python学习

1.改进我们的小游戏

 

    改进方法:

猜错的时候程序应该给点提示,例如告诉用户输入的值是大了还是小了。

每运行一次程序只能猜一次,应该提供多次机会给用户猜测。

每次运行程序,答案可以是随机的。因为程序答案固定,容易导致答案外泄。

 

2.条件分支

 

     第一个改进要求:猜错的时候程序提示用户当前的输入比答案大了还是小了。

Python的比较操作符

       Python的比较操作符

 

3.Python的条件分支语法:

Python条件分支语法

 Python条件分支语法

 print('---------I love fishc-------')

temp = input("Let's guess some number")
guess = int(temp)
if guess==8:
print("yes,you are right!")
print("you are intelligent~~~")
else:
if guess> 8:
print("It's too big")
else:
print("It's too small")
print("game over")


4.while循环

 

第二个改进要求:程序应该提供多次机会给用户猜测,专业点来讲就是程序需要重复运行某些代码。

 

Python的While循环语法:
Python while循环语法

Python while循环语法

 

print('---------I love fishc-------')
temp = input("Let's guess some number")
guess = int(temp)
while guess != 8:
temp = input("Let's guess some number again")
guess = int(temp)
if guess==8:
print("yes,you are right!")
print("you are intelligent~~~")
else:
if guess> 8:
print("It's too big")
else:
print("It's too small")
print("game over")

5.这里我们给大家的提示是:使用and逻辑操作符

Python的and逻辑操作符可以将任意表达式连接在一起,并得到一个布尔类型的值。

 

6.引入外援

 

第三个改进要求:每次运行程序产生的答案是随机的。

我们需要引入外援:random(随即)模块

 

这个random模块里边有一个函数叫做:randint(),Ta会返回一个随机的整数。

我们可以利用这个函数来改造我们的游戏!

import random
secret = random.randint(1,10)
print('---------I love fishc-------')
temp = input("Let's guess some number")
guess = int(temp)
while guess != secret:
    temp = input("Let's guess some number again")
    guess = int(temp)
    if guess == secret:
        print("yes,you are right!")
        print("you are intelligent~~~")
    else:
        if guess> secret:
            print("It's too big")
        else:
            print("It's too small")
print("game over")


课堂作业:

0. 请问以下代码会打印多少次“我爱鱼C!”

  1. while 'C':
  2.     print('我爱鱼C!')
复制代码

  1次吧。感觉“C”和“我爱鱼C”不一样吧!

  试了一下,貌似不管while'x'都会一直打印“我爱鱼C”

死循环,会一直打印“我爱鱼C!”(嗯,这也算是永远支持鱼C的方法之一),直到崩溃或者用户按下快捷键 CTRL + C(强制结束)
造成死循环的原因是 while 后边的条件永远为真(True),在 Python 看来,只有以下内容会被看作假(注意冒号括号里边啥都没有,连空格都不要有!):False None 0 "" '' () [] {}
其他一切都被解释为真!
不妨试试:

  1. while '':
  2.     print('进入循环')
  3. print('退出循环')
复制代码


或者

  1. while Flase:
  2.     print('进入循环')
  3. print('退出循环')
复制代码


或者

  1. while 0:
  2.     print('进入循环')
  3. print('退出循环')   
复制代码


1. 请问以下代码会打印多少次“我爱鱼C!”

  1. i = 10
  2. while i:
  3.     print('我爱鱼C!')
  4.     i = i - 1

     10次9,8,7,6,5,4,3,2,1,0

会打印 10 次


2. 请写出与 10 < cost < 50 等价的表达式

    cost >10 and cost < 50
(10 < cost) and (cost < 50)


3. Python3 中,一行可以书写多个语句吗?

    ok.当一行中出现多行语句时用分号(;)隔开。

可以,语句之间用分号隔开即可,不妨试试:
>>> print('I love fishc');print('very much!')


4. Python3 中,一个语句可以分成多行书写吗?

     ok. 如果一条语句横跨多行,你只需用一对 括号,方括号,大括号 括起来就行了。

可以,一行过长的语句可以使用反斜杠或者括号分解成几行,不妨试试:

  1. >>> 3 > 4 and \
  2.   1 < 2
复制代码

或者

  1. >>> ( 3 > 4 and 
  2.   1 < 2 )
复制代码


5. 请问Python的 and 操作符 和C语言的 && 操作符 有何不同?【该题针对有C或C++基础的朋友】

    小C是谁?

有图有真相(C\C++ VS Python):


 

VS

 



6. 听说过“短路逻辑(short-circuit logic)”吗?

     表达式x and y需要两个变量都为真时才为真,所以如果x为假,表达式就会立刻返回false,而不管y的值(事实上各个语言都有这个特性)。实际上,如果x为假,表达式会返回x得值----否则它就返回y的值。这种行为被称为短路逻辑(short-circuit logic)或惰性求值(lazy evaluaion)
  表达式x and y需要两个变量都为真时才为真,所以如果x为假,表达式就会立刻返回false,而不管y的值。

逻辑操作符有个有趣的特性:在不需要求值的时候不进行操作。这么说可能比较“高深”,举个例子,表达式 x and y,需要 x 和 y 两个变量同时为真(True)的时候,结果才为真。因此,如果当 x 变量得知是假(False)的时候,表达式就会立刻返回 False,而不用去管 y 变量的值。

这种行为被称为短路逻辑(short-circuit logic)或者惰性求值(lazy evaluation),这种行为同样也应用与 or 操作符,这个后边的课程小甲鱼会讲到,不急。

实际上,Python 的做法是如果 x 为假,表达式会返回 x 的值(0),否则它就会返回 y 的值(例子参考楼上那题)。



动动手:

0. 完善第二个改进要求(为用户提供三次机会尝试,机会用完或者用户猜中答案均退出循环)并改进视频中小甲鱼的代码。
改进要求

1.只有3次猜测机会.2.第一次程序结束时没有结束语3.第一次猜错没有提示

import random

secret = random.randint(1,5)

print('---------I love fishc-------')

time = 0

temp = input("Let's guess some number")

guess = int(temp)

if guess == secret:

    print("yes,you are right!")

    print("you are intelligent~~~")

else:

    if guess > secret:

        print("It's too big")

    else:

        print("It's too small")

while guess != secret and time < 2:

    time = time + 1

    temp = input("please try again")

    guess = int(temp)

    if guess == secret:

        print("yes,you are right!")

        print("you are intelligent~~~")

    else:

        if guess> secret :

            print("It's too big")

        else:

            print("It's too small")

time=3

print("no chance!")

print("Game over")


(尼玛坑爹玩意儿,把time打成tine。想了半小时搞不清楚哪错了,为了避免中英文标点错误写成英文,结果英文还有拼写错误。郁闷死了。写的太繁琐了)

  1. import random
  2. times = 3
  3. secret = random.randint(1,10)
  4. print('------------------我爱鱼C工作室------------------')
  5. # 这里先给guess赋值(赋一个绝对不等于secret的值)
  6. guess = 0
  7. # print()默认是打印完字符串会自动添加一个换行符,end=" "参数告诉print()用空格代替换行
  8. # 嗯,小甲鱼觉得富有创意的你应该会尝试用 end="JJ"?
  9. print("不妨猜一下小甲鱼现在心里想的是哪个数字:", end=" ")
  10. while (guess != secret) and (times > 0):
  11.     temp = input()
  12.     guess = int(temp)
  13.     times = times - 1 # 用户每输入一次,可用机会就-1
  14.     if guess == secret:
  15.         print("我草,你是小甲鱼心里的蛔虫吗?!")
  16.         print("哼,猜中了也没有奖励!")
  17.     else:
  18.         if guess > secret:
  19.             print("哥,大了大了~~~")
  20.         else:
  21.             print("嘿,小了,小了~~~")
  22.         if times > 0:
  23.             print("再试一次吧:", end=" ")
  24.         else:
  25.             print("机会用光咯T_T")
  26. print("游戏结束,不玩啦^_^")

复制代码


1. 尝试写代码实现以下截图功能

 

print('---------I love fishc--------')

temp = input("Please input a integer:")

num = int (temp)

i = num

num = num - (num-1)

print(num)

while num<i:

    num = num + 1

    print(num)


  1. temp = input('请输入一个整数:')
  2. number = int(temp)
  3. i = 1
  4. while number:
  5.     print(i)
  6.     i = i + 1
  7.     number = number - 1

2. 尝试写代码实现以下截图功能:

 

temp = input("please input a integer:")

num = int(temp)

print(" " *num + "*" * num )

while num > 1:

    num =num -1

    i = num - 1

    print(" " * i + "*" * num )


  1. temp = input('请输入一个整数:')
  2. number = int(temp)
  3. while number:
  4.     i = number - 1
  5.     while i:
  6.         print(' ', end = '')
  7.         i = i - 1
  8.     j = number
  9.     while j:
  10.         print('*', end = '')
  11.         j = j - 1
  12.     print()
  13.     number = number - 1


课后补充:


1.Python While循环语句

Python 编程中 while 语句用于循环执行程序,即在某条件下,循环执行某段程序,以处理需要重复处理的相同任务。其基本形式为:

while 判断条件: 执行语句……

执行语句可以是单个语句或语句块。判断条件可以是任何表达式,任何非零、或非空(null)的值均为true。

当判断条件假false时,循环结束。

执行流程图如下:

python_while_loop

实例:

#!/usr/bin/python count = 0 while (count < 9): print 'The count is:', count count = count + 1 print "Good bye!"

以上代码执行输出结果:

The count is: 0 The count is: 1 The count is: 2 The count is: 3 The count is: 4 The count is: 5 The count is: 6 The count is: 7 The count is: 8 Good bye!

while 语句时还有另外两个重要的命令 continue,break 来跳过循环,continue 用于跳过该次循环,break 则是用于退出循环,此外"判断条件"还可以是个常值,表示循环必定成立,具体用法如下:

# continue 和 break 用法 i = 1 while i < 10: i += 1 if i%2 > 0: # 非双数时跳过输出 continue print i # 输出双数2、4、6、8、10 i = 1 while 1: # 循环条件为1必定成立 print i # 输出1~10 i += 1 if i > 10: # 当i大于10时跳出循环 break


无限循环

如果条件判断语句永远为 true,循环将会无限的执行下去,如下实例:

#!/usr/bin/python var = 1 while var == 1 : # 该条件永远为true,循环将无限执行下去 num = raw_input("Enter a number :") print "You entered: ", num print "Good bye!"

以上实例输出结果:

Enter a number :20 You entered: 20 Enter a number :29 You entered: 29 Enter a number :3 You entered: 3 Enter a number between :Traceback (most recent call last): File "test.py", line 5, in <module> num = raw_input("Enter a number :") KeyboardInterrupt

注意:以上的无限循环你可以使用 CTRL+C 来中断循环。


循环使用 else 语句

在 python 中,for … else 表示这样的意思,for 中的语句和普通的没有区别,else 中的语句会在循环正常执行完(即 for 不是通过 break 跳出而中断的)的情况下执行,while … else 也是一样。

#!/usr/bin/python count = 0 while count < 5: print count, " is less than 5" count = count + 1 else: print count, " is not less than 5"

以上实例输出结果为:

0 is less than 5 1 is less than 5 2 is less than 5 3 is less than 5 4 is less than 5 5 is not less than 5


简单语句组

类似if语句的语法,如果你的while循环体中只有一条语句,你可以将该语句与while写在同一行中, 如下所示:

#!/usr/bin/python flag = 1 while (flag): print 'Given flag is really true!' print "Good bye!"

注意:以上的无限循环你可以使用 CTRL+C 来中断循环。

http://www.w3cschool.cc/python/python-while-loop.html




2.python语句简介

l  Python中新的语法成分是冒号(:)

l  一行的结束会自动终止现在该行的语句

l  缩进的结束就是代码块的结束。

l  当一行中出现多行语句时用分号(;)隔开。

l  如果一条语句横跨多行,你只需用一对 括号,方括号,大括号 括起来就行了。

例如:

if(x<y and

    y<z):

        Print('true')

If[x<y and

    y<z]:

        Print('true')

If{x<y and

    y<z}:

        Print('true')

 

l  复合语句的主体可以出现在python的首先冒号之后,但只有当复合语句本身不包含任何复合语句的时候才能这样做,也就是单语句。例如 if x>y : print(x)

 

    while True:

         reply = raw_input('Enter text:')

         if reply  == 'stop':

                   break

         elif not reply.isdigit():

                   print('Bad!' * 8)

         else:

                   print(int(reply) ** 2)

 

    while True:

         reply = raw_input("Enter text:")

         if reply == 'stop' : break

         try:

                   num = int(reply)

         except:

                   print('bad!' * 8)

         else:

                   print(num ** 2)

 

由上例,从语句嵌套观点来看,因为try, except以及else这些关键字全都缩进在同一层次上,它们全都被视为单个try语句的一部分。注意:else部分是和try结合,而不是和if结合。在python中, else可出现在if 语句中,也可以出现在try语句以及循环中----其缩进会告诉你它属于哪个语句。



3.布尔运算

        布尔是英国的数学家,在1847年发明了处理二值之间关系的逻辑数学计算法,包括联合、相交、相减。在图形处理操作中引用了这种逻辑运算方法以使简单的基本图形组合产生新的形体。并由二维布尔运算发展到三维图形的布尔运算

       计算机编程布尔运算逻辑运算(logical operators) 通常用来测试真假值。最常见到的逻辑运算就是循环的处理,用来判断是否该离开循环或继续执行循环内的指令。


运算规则
组合\结果\运算符.....And.......Or.........Xor
0......0.......................0..........0............0
1......0.......................0..........1............1
0......1.......................0..........1............1
1......1.......................1..........1............0
简单的说
And:同为真时为真
Or:同为假时为假
Xor:相同为假


真值表

对象/常量

""

"string"

0

>=1

<=-1

()空元组

[]空列表

{}空字典

None




4.Python 短路逻辑和条件表达式


    布尔运算符有个有趣的特性:只有在需要求值时才进行求值。举例来说,表达式x and y需要两个变量都为真时才为真,所以如果x为假,表达式就会立刻返回false,而不管y的值(事实上各个语言都有这个特性)。实际上,如果x为假,表达式会返回x得值----否则它就返回y的值。这种行为被称为短路逻辑(short-circuit logic)或惰性求值(lazy evaluaion):布尔运算符通常被称为逻辑运算符,就像你看到的那样第2个值有时“被短路了”。这种行为对于or来说也同样适用。在表达式x or y中,x为真时,它直接返回x的值,否则返回y值。注意,这意味着在布尔运算符之后的所有代码都不会执行。

  这有什么用呢?它主要是避免了无用地执行代码,可以作为一种技巧使用,假设用户应该输入他/她的名字,但也可以选择什么都不输入,这时可以使用默认值‘<unknown>’。可以使用if语句,但是可以很简洁的方式:

  

name = raw_input('Please enter your name: ') or '<unknown>'

  换句话说,如果raw_input语句的返回值为真(不是空字符串),那么它的值就会赋给name,否则将默认的'<unknown>'赋值给name。

  这类短路逻辑可以用来实现C和Java中所谓的三元运算符(或条件运算符)。Python2.5中有一个内置的条件表达式,像下面这样:

  

a if b else c

  如果b为真,返回a,否则,返回c。(注意,这个运算符不用引用临时变量,就可以直接使用,从而得到与raw_input例子中同样的结果。)


5.Python中的random模块

Python中的random模块用于生成随机数。下面介绍一下random模块中最常用的几个函数。

random.random

random.random()用于生成一个0到1的随机符点数: 0 <= n < 1.0

random.uniform

  random.uniform的函数原型为:random.uniform(a, b),用于生成一个指定范围内的随机符点数,两个参数其中一个是上限,一个是下限。如果a > b,则生成的随机数n: a <= n <= b。如果 a <b, 则 b <= n <= a。

  1. print random.uniform(1020)  
  2. print random.uniform(2010)  
  3. #---- 结果(不同机器上的结果不一样)  
  4. #18.7356606526  
  5. #12.57982
print random.uniform(10, 20) print random.uniform(20, 10) #---- 结果(不同机器上的结果不一样) #18.7356606526 #12.5798298022random.randint

  random.randint()的函数原型为:random.randint(a, b),用于生成一个指定范围内的整数。其中参数a是下限,参数b是上限,生成的随机数n: a <= n <= b

  1. print random.randint(1220)  #生成的随机数n: 12 <= n <= 20  
  2. print random.randint(2020)  #结果永远是20  
  3. #print random.randint(20, 10)  #该语句是错误的。下限必须小于上限。  
print random.randint(12, 20) #生成的随机数n: 12 <= n <= 20 print random.randint(20, 20) #结果永远是20 #print random.randint(20, 10) #该语句是错误的。下限必须小于上限。random.randrange

  random.randrange的函数原型为:random.randrange([start], stop[, step]),从指定范围内,按指定基数递增的集合中 获取一个随机数。如:random.randrange(10, 100, 2),结果相当于从[10, 12, 14, 16, ... 96, 98]序列中获取一个随机数。random.randrange(10, 100, 2)在结果上与 random.choice(range(10, 100, 2) 等效。

random.choice

  random.choice从序列中获取一个随机元素。其函数原型为:random.choice(sequence)。参数sequence表示一个有序类型。这里要说明 一下:sequence在python不是一种特定的类型,而是泛指一系列的类型。list, tuple, 字符串都属于sequence。有关sequence可以查看python手册数据模型这一章。下面是使用choice的一些例子:

  1. print random.choice("学习Python")   
  2. print random.choice(["JGood""is""a""handsome""boy"])  
  3. print random.choice(("Tuple""List""Dict"))  
print random.choice("学习Python") print random.choice(["JGood", "is", "a", "handsome", "boy"]) print random.choice(("Tuple", "List", "Dict"))random.shuffle

  random.shuffle的函数原型为:random.shuffle(x[, random]),用于将一个列表中的元素打乱。如:

  1. p = ["Python""is""powerful""simple""and so on..."]  
  2. random.shuffle(p)  
  3. print p  
  4. #---- 结果(不同机器上的结果可能不一样。)  
  5. #['powerful', 'simple', 'is', 'Python', 'and so on...']  
p = ["Python", "is", "powerful", "simple", "and so on..."] random.shuffle(p) print p #---- 结果(不同机器上的结果可能不一样。) #['powerful', 'simple', 'is', 'Python', 'and so on...']random.sample

  random.sample的函数原型为:random.sample(sequence, k),从指定序列中随机获取指定长度的片断。sample函数不会修改原有序列。

  1. list = [12345678910]  
  2. slice = random.sample(list, 5)  #从list中随机获取5个元素,作为一个片断返回  
  3. print slice  
  4. print list #原有序列并没有改变。  

随机整数:
>>> import random
>>> random.randint(0,99)
21

随机选取0到100间的偶数:
>>> import random
>>> random.randrange(0, 101, 2)
42

随机浮点数:
>>> import random
>>> random.random() 
0.85415370477785668
>>> random.uniform(1, 10)
5.4221167969800881

随机字符:
>>> import random
>>> random.choice('abcdefg&#%^*f')
'd'

多个字符中选取特定数量的字符:
>>> import random
random.sample('abcdefghij',3) 
['a', 'd', 'b']

多个字符中选取特定数量的字符组成新字符串:
>>> import random
>>> import string
>>> string.join(random.sample(['a','b','c','d','e','f','g','h','i','j'], 3)).r
eplace(" ","")
'fih'

随机选取字符串:
>>> import random
>>> random.choice ( ['apple', 'pear', 'peach', 'orange', 'lemon'] )
'lemon'

洗牌:
>>> import random
>>> items = [1, 2, 3, 4, 5, 6]
>>> random.shuffle(items)
>>> items
[3, 2, 5, 6, 4, 1]


6.逻辑操作符

Python的逻辑操作有三种:and、or、not。分别对应与、或、非。
举例

严格的说,逻辑操作符的操作数应该为布尔表达式。但Python对此处理的比较灵活。
即使操作数是数字,解释器也把他们当成“表达式”。
非0的数字的布尔值为1,0的布尔值为0.
举例:

复制代码
1 #coding:utf-8
2  test1 = 12
3 test2 = 0
4  print (test1 and test2) #result = 0
5  print (test1 or test2) #result = 12
6  print (not test1) #result = Flase
7  print (not test2) #reslut = True
复制代码
在Python中,空字符串为假,非空字符串为真。非零的数为真。
数字和字符串之间、字符串之间的逻辑操作规律是:
对于and操作符:
只要左边的表达式为真,整个表达式返回的值是右边表达式的值,否则,返回左边表达式的值
对于or操作符:
只要两边的表达式为真,整个表达式的结果是左边表达式的值。
如果是一真一假,返回真值表达式的值
如果两个都是假,比如空值和0,返回的是右边的值。(空值或0)
举例:

复制代码
1 #coding:utf-8
2  test1 = 12
3 test2 = 0
4 test3 = ''
5 test4 = "First"
6  print test1 and test3 #result = ''
7  print test3 and test1 #result = ''
8  print test1 and test4 #result = "First"
9  print test4 and test1 #result = 12
10  print test1 or test2 #result = 12
11  print test1 or test3 #result = 12
12  print test3 or test4 #result = "First"
13  print test2 or test4 #result = "First"
14  print test1 or test4 #result = 12
15  print test4 or test1 #result = "First"
16  print test2 or test3 #result = ''
17  print test3 or test2 #result = 0



路过

雷人

握手

鲜花

鸡蛋

评论 (0 个评论)

facelist

您需要登录后才可以评论 登录 | 立即注册

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2026-3-16 06:23

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

返回顶部