Python基础 Day1

一、需要了解的

Python种类:
  JPython
  IronPython
  JavaScriptPython
  RubyPython
  CPython **********
  pypy 是用CPython开发的Python

安装:
Python安装在OS上,
执行操作:
写一个文件文件中按照Python的规则写,将文件交给Python软件,读取文件中的内容,然后进行转换和执行,最终获取结果。

Python软件 ==> Python解释器(内存管理)

Python版本

Python3 在继续更新
Python2 在继续更新

二、Python基础

1. 第一句Python

- 后缀名是可以是任意?
- 导入模块时,如果不是.py文件
==> 以后文件后缀名是 .py

2. 两种执行方式
Python解释器 py文件路径
Python 进入解释器:
实时输入并获取到执行结果

3. 解释器路径

#!/usr/bin/env python

 便于Linux上运行


4. 编码

# -*- coding:utf8 -*-

Python3 无需关注
Python2 每个文件中只要出现中文,头部必须加

5. 执行一个操作
提醒用户输入:用户和密码
获取用户名和密码,检测:用户名=root 密码=root!23

正确:登录成功
错误:登陆失败

n1 = input("请输入用户名:")
n2 = input("请输入密码:")

if n1 == "root" and n2 == "root!23":
  print("登录成功")
else:
  print("登录失败")

input的用法,永远等待,直到用户输入了值,就会将输入的值赋值给一个东西

6. 变量

只能由
- 字母
- 数字
- 下划线

PS:
不能以数字开头

不能使用Python关键字如下

'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del',
'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global',
'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise',
'return', 'try', 'while', 'with', 'yield'

*最好不和Python内置的东西重复 

name = "even"

7. 条件语句
Python严格参照缩进执行代码块
缩进用4个空格,使用Tab键

a.if基本语句

if 条件:
  内部代码块
  内部代码块
else:
  ...
print('...')

示例:

if 1 == 1:
  print("Hello World")
  print("Hello World")
else:
  print("NO WAY!")

b.嵌套if和else

if 1 == 1:
  if 2 == 2:
    print("Hello World")
    print("Hello World")
  else:
    print("NO WAY!")
else:
  print("zzzz")

c.if中的pass

if 条件1:
  pass
elif 条件2:
  pass
elif 条件3:
  pass
else:
  pass

print('end')

PS:

pass 代指空代码,无意义,仅仅用于表示代码块

d. 条件and or

if n1 == "root" or n2 == "root!23":
  print('OK')
else:
  print('NO')

8. 基本数据类型

字符串 

n1 = "alex" n2 = 'root' n3 = """eric""" n4='''tony'''

数字 

age=21 weight = 64 fight = 5

字符串:
加法:

n1 = "even"
n2 = "a"
n4 = "b"
n3 = n1 + n2 + n4
# "evenab"

乘法:

n1 = "q"
n3 = n1 * 10
#"qqqqqqqqqq"

数字:

n1 = 9
n2 = 2
n3 = n1 + n2
n3 = n1 - n2
n3 = n1 * n2
n3 = n1 / n2
n3 = n1 % n2 #获取n1除以n2得到的余数
n3 = n1 ** n2 #n1的n2次方

奇偶数示例

num = 12
n = num % 2
if n == 0:
  print('偶数')
else:
  print('奇数')

9. 循环
死循环

while 1==1:
  print('ok')


10. 练习题

if条件语句
while循环
奇数偶数


1、使用while循环输入 1 2 3 4 5 6 8 9 10

n = 1
while n < 11:
  if n == 7:
    pass
  else:
    print(n)
  n = n + 1

print('----end----')

2、求1-100的所有数的和

n = 1
s = 0
while n < 101:
  s = s + n
  n = n + 1

print(s)

3、输出 1-100 内的所有奇数

n = 1
while n < 101:
  temp = n % 2
  if temp == 0:
    pass
  else:
    print(n)
  n = n + 1

print('----end----')

4、输出 1-100 内的所有偶数

n = 1
while n < 101:
  temp = n % 2
  if temp == 0:
    print(n)
  else:
    pass
  n = n + 1

print('----end----')

5、求1-2+3-4+5 ... 99的所有数的和

n = 1
s = 0 # s是之前所有数的总和
while n < 100:
  temp = n % 2
  if temp == 0:
    s = s - n
  else:
    s = s + n
  n = n + 1

print(s)

猜你喜欢

转载自www.cnblogs.com/evenyao/p/9138978.html