python基础

时间:2022-04-23
本文章向大家介绍python基础,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

学习前准备,了解

基础环境部署,工作原理,发展和历史

pycharm,notepad++等工具

交互模式 命令行模式

废话不多说,直接上分

第一个脚本 打印

linux命令行下,vim 1.py

#!/bin/env python

print "hello world"

保存退出。

chmoc +x 1.py

python 1.py

[root@localhost xiaoai]# python 1.py

hello world

2.打印+运算

[root@localhost xiaoai]# cat 2.py

#!/bin/env python

print "The answer is",2*2

print "test"

print ("The answer is",2*2)

print "test"

print ("The answer is 2*2")

输出结果

[root@localhost xiaoai]# python 2.py

The answer is 4

test

('The answer is', 4)

test

The answer is 2*2

不知道为什么有时候会有括号,版本问题吗!?

3.对一个错误的python

[root@localhost xiaoai]# python 3.py

File "3.py", line 3

print(x,end=" ") # Appends a space instead of a newline

^

SyntaxError: invalid syntax

[root@localhost xiaoai]# cat 3.py

#!/bin/env python

print x,# Trailing comma suppresses newline

print(x,end=" ") # Appends a space instead of a newline

print (x,end="") # Appends a space instead of a newline

[root@localhost xiaoai]#

4.输入 输出

5.定义变量 交互式

[root@localhost xiaoai]# cat 5.py

#!/bash/env python

name=input('please enter your name:')

print ('hello~',name)

[root@localhost xiaoai]# python 5.py

please enter your name:qingqing

Traceback (most recent call last):

File "5.py", line 2, in

name=input('please enter your name:')

File "", line 1, in

NameError: name 'qingqing' is not defined

报错,因为没有加引号,很脑残

[root@localhost xiaoai]# python 5.py

please enter your name:'qingqing'

('hello~', 'qingqing')

[root@localhost xiaoai]#

6.约定俗成的4空格缩进

[root@localhost xiaoai]# cat 6.py

# print absolute value of an integer:

a = -78

if a >= 0:

print(a)

else:

print(-a)

[root@localhost xiaoai]# python 6.py

78

7.转义与浮点数

[root@localhost xiaoai]# cat 7.py

#!/bash/env python

print ('I'm ok')

print ('I'm "OK"!')

print ('I'm learningnPython.')

print ('\n\')

print (1.23e-3)

print 12.23e4

[root@localhost xiaoai]# python 7.py

I'm ok

I'm "OK"!

I'm learning

Python.

0.00123

122300.0

8.添加中午注释,报错

[root@localhost xiaoai]# cat 8.py

# -*- coding: utf-8 -*-

#!/bash/env python

#如果字符串里面有很多字符都需要转义,就需要加很多,为了简化,Python还允许用r''表示''内部的字符串默认不转义,可以自己试试:

print ('\t\')

[root@localhost xiaoai]# python 8.py

File "8.py", line 4

print ('\t\')

^

SyntaxError: EOL while scanning string literal

[root@localhost xiaoai]#

网上给的方法就是在解释器第一行指定UTF-8.例如

# -*- coding: UTF-8-*-或者 #coding=utf-8

实际不管用

呵呵。