python学习笔记(1)

来源:互联网 发布:淘宝做什么 编辑:程序博客网 时间:2024/05/17 23:34

猜数游戏:

import random

secret = random.randint(1,99)

guess = 0

tries=0

print("AHOY! I have a secret!It is a number from 1 to 99.I'll give you 6 tries.")

while guess!=secret and tries<6:

    guess=int(input("what's yer guess"))

    if guess < secret:

        print("Too low ,ye scurvy dog!")

    elif guess > secret:

        print("Too high ,ye scurvy dog!")

        

    tries=tries+1

        

if guess == secret:

   print("Avast! ye got it !Found my secret,ye did!")

else :

   print("No more guesses!Better luck next time ,matey")

   print("The secret number was",secret)

 

涉及指令:whileifelseelifinputprint

其中 printinputPython2Python3中略有不同;

Python中关于循环的嵌套由缩进来掌控,所以在Python中有常见错误:

Python语言是一款对缩进非常敏感的语言,给很多初学者带来了困惑,即便是很有经验的Python程序员,也可能陷入陷阱当中。最常见的情况是tab和空格的混用会导致错误,或者缩进不对,而这是用肉眼无法分别的。

在编译时会出现这样的错IndentationError:expected an indented block说明此处需要缩进,你只要在出现错误的那一行,按空格或Tab(但不能混用)键缩进就行。

往往有的人会疑问:我根本就没缩进怎么还是错,不对,该缩进的地方就要缩进,不缩进反而会出错,,比如:

if xxxxxx:

(空格)xxxxx

或者

def xxxxxx:

(空格)xxxxx

还有

for xxxxxx:

(空格)xxxxx

一句话 有冒号的下一行往往要缩进,该缩进就缩进

  假如在上述代码中将缩进改为:

import random

secret = random.randint(1,99)

guess = 0

tries=0

print("AHOY! I have a secret!It is a number from 1 to 99.I'll give you 6 tries.")

while guess!=secret and tries<6:

    guess=int(input("what's yer guess"))

    if guess < secret:

        print("Too low ,ye scurvy dog!")

    elif guess > secret:

        print("Too high ,ye scurvy dog!")

        

    tries=tries+1

        

    if guess == secret:

        print("Avast! ye got it !Found my secret,ye did!")

    else :

        print("No more guesses!Better luck next time ,matey")

        print("The secret number was",secret)

那么,标注红色的部分也属于while循环中。

0 0
原创粉丝点击