返回顶部
扩大
缩小

Heaton

Python基础(一)

搭建python环境移步(https://www.cnblogs.com/ttzzyy/p/10391557.html)[https://www.cnblogs.com/ttzzyy/p/10391557.html]

1:python执行流程


linux上操作

windows上开发工具Pycharm操作

print("helloworld!")

2:python注释


#打印一行文字,单行注释
'''
多行注释
打印
一行
文字
'''
"""
另一种
多行
注释
"""
print("helloworld!")
print("hello python")
# print("hello !可以注释代码")

3:python变量


'''
变量
'''
name = "zhangsan"
age = 20
print(name)
print(age)
#变量的使用
age = age + 10
print(age)

4:python变量与类型转换



#类型转换
a = input("输入数字1:")
b = input("输入数字2:")
print(type(a))
print(type(b))
sum = a + b
print(type(sum))
print(sum)
sum = int(a) + int(b)
print(type(sum))
print(sum)

5:python标识符


import keyword
print(keyword.kwlist)

这些就是python已经定义好的,我们不能使用这些做变量名
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

6:python输入输出









'''
输入输出
'''
#input输入
name = input("请输入用户名:")
age = input("请输入年龄:")
print(type(name))
print(type(age))
print(name)
print(age)

#print输出
name = "zhangsan"
age = 20
height = 105.5
print(name,age,height)

#格式化输出
name = "zhangsan"
age = 20
height = 105.5
print("姓名:%s,年龄%d,身高:%f" % (name,age,height))
#保留小数点位数
print("姓名:%s,年龄%d,身高:%.2f" % (name,age,height))
#如果只有一个参数可以省略()
print("姓名:%s" % name)
#如果要输出%那么需要使用%%做转换
num = 99.99
print("您的电脑超过全国%f%%的用户!" % num)

#无换行输出
print("hello",end="")
print("world")

#format格式化输出
name = "zhangsan"
age = 20
height = 105.5
print("姓名:{},年龄:{},身高:{}".format(name,age,height))

7:python运算符


'''
加减乘除不介绍
'''
#取余运算符 % 商3余1
a = 10 % 3
print(a)

#取整运算符 // 商3余1
b = 10 // 3
print(b)

#幂运算符 ** 2的3次方
c = 2 ** 3
print(c)

8:python if条件判断


'''
if条件判断
'''
age = input("输入年龄:")
age_int = int(age)
if age_int >= 0 and age_int <= 18:
    print("好好体会同年乐趣!")
elif age_int >= 18 and age_int <= 60:
    print("好好挣钱吧!")
elif age_int < 0 or age_int >100:
    print("妖怪哪里走!")
else:
    print("退休养老!")

9:python while循环


'''
while循环
'''
#打印1-10的数字
num = 1
while num <= 10:
    print(num)
    num += 1

10:break跳出、continue跳过while循环 与debug调试

'''
break跳出、continue跳过while循环   与debug调试
'''
#打印1-20的偶数,当遇到10的时候不打印(跳过),等于16的时候中断循环不再继续(跳出)
num = 1
while num <= 20:
    if num % 2 == 0:
        if num == 10:
            num += 1
            continue
        if num == 16:
            break
        print(num)
    num += 1

11:for循环使用方法



'''
for循环
range(start,end,步长) 默认步长是1 range(0,10)=[0,10)左闭右开的区间0.1.2.3.4...9
'''
#打印1-10的数
for x in range(1,11):
    print(x)

#打印1-10的偶数方法1
for x in range(1,11):
    if x % 2 == 0:
        print(x)

# 打印1-10的偶数方法2
for x in range(0,12,2):
    print(x)

#遇到6跳出continue
for x in range(1,11):
    if x == 6:
        continue
    print(x)

#遇到6跳过break
for x in range(1,11):
    if x == 6:
        break
    print(x)

12:字符串


'''
字符串使用
'''
a = "hello"
print(a[0])#h
print(a[1])#e
print(a[-1])#o
print(a[-2])#l
print(len(a))#5

# print(a[6])#IndexError: string index out of range
str = "zhangsan,20"
print(str[0:8])#zhangsan
print(str[9:])#20
print(str[::2])#zaga,0    从0开始每个一个字符取一个字符
print(str[::-1])#02,nasgnahz   倒叙取

13:列表的使用


'''
列表的使用方法
'''
info_list = ["zhangsan",20,180.5,80,True]
#遍历
for item in info_list:
    print(item)
#修改
info_list[4] = 70
print(info_list)
#添加
#append
info_list.append("bb")
print(info_list)
#insert(位置,元素)
info_list.insert(0,"bb")
print(info_list)
#删除
#del[下标]
del info_list[4]
print(info_list)
#remove(元素值)
info_list.remove(80)
print(info_list)
#pop(可选下标)
a = info_list.pop()
a = info_list.pop(1)
print(a)
print(info_list)

14:元组的使用

'''
元组的使用方法
'''
info_tuple = ("zhangsan",20,180.5,80,True)
#遍历
for item in info_tuple:
    print(item)

#修改,添加(元组不允许修改,需要重新创建使用)
info_tuple[3] = 50#TypeError: 'tuple' object does not support item assignment
info_tuple1 = ("lisi",20)
info_tuple2 = info_tuple + info_tuple1
print(info_tuple2)
#删除
del info_tuple2
print(info_tuple2)#NameError: name 'info_tuple2' is not defined
#截取切片
print(info_tuple[:])#('zhangsan', 20, 180.5, 80, True)
print(info_tuple[1:3])#左开右闭(20, 180.5)
print(info_tuple[-1])#True
print(info_tuple[0])#zhangsan
print(info_tuple[::2])#('zhangsan', 180.5, True)
print(info_tuple[::-1])#(True, 80, 180.5, 20, 'zhangsan')

15:字典的使用


'''
字典的使用
'''
user_info_dict = {"name":"唐僧","age":100,"job":"取经"}

#打印job的值
print(user_info_dict["job"])
#修改job为 取经|念咒
user_info_dict["job"] = "取经|念咒"
print(user_info_dict["job"])
#怎么获取一个没有的键值对
# print(user_info_dict["tel"])#KeyError: 'tel'
print(user_info_dict.get("tel","13565897845"))
#keys获取所有key
for key in user_info_dict.keys():
    print(key)

#values获取所有value
print("*******")
for value in user_info_dict.values():
    print(value)

#items获取所有键值对
print("*******")
for item in user_info_dict.items():
    print(item)
print("*******")
for key,value in user_info_dict.items():
    print(key,":",value)

16:函数


'''
函数的定义和使用
'''

#无参函数
def print_name_age():
    print("name:zhangsan")
    print("age:15")

print_name_age()

#有参函数
def print_info(name,age):
    print("name:",name)
    print("age:",age)

print_info("lisi",15)

def print_info1(name,age,height=180.5):
    print("name:", name)
    print("age:", age)
    print("height:", height)

print("********")
print_info1("lisi",22)
print("********")
print_info1("lisi",22,190.55)

#有返回值的函数
def x_y_sum(x,y):
    sum = x + y
    return x,y,sum

print("********")
a,b,s = x_y_sum(5,4)
print(a,"+",b,"=",s)

17:python异常

  • 处理异常
'''
try:
    尝试执行代码
except <name>:
    如果在try部份引发了'name'异常执行代码
except Exception,err:
    如果引发了'name'异常,获得附加的数据
else:
    如果没有异常发生
finally:
    一定会执行的代码
'''
# a = 10 / 0 #ZeroDivisionError

try:
    a = 10 / 1
except ZeroDivisionError:
    print("ERROR:出现异常")
else:
    print(a)
finally:
    print("这是一个异常测试")
  • 带参数处理异常
'''
带参数处理异常
'''
# 定义函数
def temp_convert(var):
    try:
        return int(var)
    except ValueError as args:
        print("出现ValueError异常,参数为:\n",args)

# 调用函数
temp_convert("xyz")
  • 自定义异常
'''
自定义异常
raise 触发|抛出异常
'''
class NetWorkError(RuntimeError):
    def __init__(self,args):
        self.args = args


try:
    raise NetWorkError("Bad HostName!")
except NetWorkError as args:
    print(args)

demo:

https://www.cnblogs.com/ttzzyy/articles/10381228.html

posted on 2019-02-18 11:42  咘雷扎克  阅读(453)  评论(0编辑  收藏  举报

导航