python基础——第一个python程序(基础语法1)

菜鸟编程:

1.Spyder界面:左右两边都可以写程序

左边界面框:输入程序print("hello word")  按F5快捷键运行,在右界面框出结果。

左边输入:

按F5右边出结果:

左边可以写很多段小程序,F5运行时会把这几段程序结果都输出来。

右界面框:输入程序,回车直接出结果。

2.注释用#,可多行注释,若需要多行注释写在左界面。

多行注释可以用多个#号,还有 ''' 和 """

3.行与缩进

python使用缩进来代表代码块。不需要大括号{}

缩进的空格数是可以变的,但是同一个代码块的语句必须包含相同的缩空格数。

if True:
    print("1")
else:
    print("2")
    
1

若空格数不相同,会导致运行错误,实例如下:

缩进数指的是向里收缩的意思,print前移缩进数变报错,后移不影响。

if True:
    print("1")
else:
print("2")   #缩进数不同
  File "<ipython-input-19-ce72f1213308>", line 4
    print("2")

if True:
      print("1")   
else:
                 print("2")    #后移不叫缩进
                 
1
if True:
print("1")   #缩进数不同
else:
       print("2")
  File "<ipython-input-21-15c4b3ebf0db>", line 2
    print("1")
    ^
IndentationError: expected an indented block
if True:
    print("1")
    else:       #if/else的位置:对齐
        print("2")
  File "<ipython-input-17-8d87826d7c98>", line 3
    else:
    ^
SyntaxError: invalid syntax

4.多行语句

(1)Python语句通常一行写完一条,如果语句很长,可以使用(\)反斜杠来实现。

total=1+\
      2+\
      3

(2)在 [], {}, 或 () 中的多行语句,不需要使用反斜杠(\)

total=['1','2','3']

total={'w','o','r','d'}

total=('1','2','3')

猜你喜欢

转载自blog.csdn.net/zhangxue1232/article/details/108984364
今日推荐