python基本語法

python版本3.6

運行軟件spyder

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

"""

Created on Tue Mar? 3 11:19:18 2020

@author: Administrator

"""

print("hello world")

print("hello world"+"23")

print("")

"""

運算

%取余 //取整? **乘方?

"""

#循環(huán)

condition = 1

while condition <5:

? ? print(condition)

? ? condition+=1

#for循環(huán)

for i in range (5):

? ? print(i)

for i in range(2,10):

? ? print(i)

print("end")

for i in range(2,10,2):

? ? print(i)

print("end")

for i in[1,2,3,4]:

? ? print(i)

print("end")

for i in(1,2,3,4):

? ? print(i)

#列表

a_list = [1,2,23,23,34,45]

print(a_list)

print(a_list[1])? ? ? ? ? ? #打印列表第一個元素

print(a_list[-2])? ? ? ? ? #從右往左數(shù)第二個

print(a_list[1:4])? ? ? ? ? #從第一個打印到第四個

print(a_list[:-2])? ? ? ? ? #從頭打印到倒數(shù)第二個

print(len(a_list))

for content in a_list:

? ? print(content)

print(a_list.index(23))? ? #打印位置

a_list.sort()? ? ? ? ? ? ? #排序

print(a_list)? ? ? ? ? ? ? #

a_list.sort(reverse=True)?

print(a_list)

#列表操作

a_list[1] = 100? ? ? ? ? ? #修改元素內(nèi)容

print(a_list)

a_list.append(200)? ? ? ? ? #在元素末尾添加一個元素

a_list.insert(3,300)? ? ? ? #在元素3位置插入元素

del a_list[2]? ? ? ? ? ? ? #刪除列表第二個元素‘

a_list.remove(1)? ? ? ? ? #列表中刪除一個具體的數(shù)

a = a_list.pop()? ? ? ? ? ? #將最后一個元素出棧

print(a)

#多維數(shù)組

b_list = [[1,2,3],

? ? ? ? ? [3,4,5],

? ? ? ? ? [7,8,9]]

print(b_list[1])? ? ? ? ? ? #打印第一行的? [3,4,5]

print(b_list[1][2])? ? ? ? #打印第一行第二列的?

#元組? 能和數(shù)組一樣查看元素 但是不能修改元素

a_tuple = (1,23,4,453,5)

b_tuple = 2,23,4,56,6,3

print(a_tuple[1])? ? ? ? ? ? #打印第一個元素

#條件語句 if? ? ==等于? != 不等于

a = 2

b = 3

c = 5

d = 9

if a<b:

? ? print(b)

else:

? ? print(a)

#多條件

if a==b:

? ? print("right")

elif a==c:

? ? print("right")

elif a==d:

? ? print("right")

else:

? ? print("error")

#and or? if中的使用

if a<b and a<c:

? ? print(a)

colors = ['red','blue','black','green']

for color in colors:

? if color=='black':

? ? print(color)? ? ?

? ? break? ? ? ? ? ? ? ? ? #跳出循環(huán)

? elif color=='blue':

? ? print(color)

? ? continue? ? ? ? ? ? ? #跳出單次循環(huán)

? else :

? ? print(color)

if 'red' in colors:? ? ? ? #判斷列表中是否有red若無則返回時Flase? 有True

? ? print('red')

#字典

d = {'pen':7,'apple':3,'applepen':9}? ? #key:value? 鍵/值

d2 = {1:'q',3:'s',2:'v'}

d3 = {23:'s','d':23,5:'2'}

d4 = {'a':[1,2,3],'b':[2,34,5],'c':{'aa':2,'ss':44}}

print(d4['c']['aa'])

d['pen'] = 39? ? ? ? ? ? ? #修改鍵的值

print(d)

del d['apple']? ? ? ? ? ? #刪除一個鍵值對

for key,value in d.items():? #遍歷整個鍵值對

? ? print('key',key,'\t','value',value)

for key in d.keys():? ? ? ? ? #a遍歷整個字典的鍵

? ? print('key:',key)

for value in d.values():? ? ? #遍歷整個字典的值

? ? print('value',value)

for key in sorted(d2.keys()): #將鍵排序

? ? print('key',key)

#函數(shù)?

def function():? ? ? ? ? ? ? #定義函數(shù)

? ? a = 2

? ? b = 34

? ? c = a + b

? ? print ("c",c)

function()

def function2(a,b):? ? ? ? ? #定義一個帶參數(shù)的函數(shù) a,b 為形參 (局部變量),只有在函數(shù)內(nèi)部發(fā)生作用

? ? ? ? ? ? ? ? ? ? ? ? ? ? #若函數(shù)中的局部變量和全局變量重復(fù)的話 默認使用局部變量 若要使用則加global

? ? c = a+b

? ? print ("c",c)

function2(23,34)

def function3(a,b=35):? ? ? ? ? #設(shè)置默認值

? ? c = a+b

? ? print ("c",c)

function3(23)?

function3(45,234)

def add(a,b):

? ? c=a+b

? ? return c

d = add(23,45)

print(d)

#模塊? 模塊內(nèi)為已經(jīng)定義好的函數(shù)

#可以在其他文件中使用import max(模塊名) 導(dǎo)入? 然后在命令中使用max.funcmax(定義的函數(shù)名)進行操作

#或者 from max import func_max? 從該模塊中導(dǎo)入func_max中的函數(shù) 使用 直接func_max 不需模塊名

#或from max import *? ? ? ? ? ? 從該模塊中導(dǎo)入所有的函數(shù)

#import max as m? ? ? ? ? ? ? ? 重命名該模塊

import os

print(os.getcwd())

#類

class human:? ? ? ? ? ? ? ? ? ? #定義類

? ? def __init__(self,name='someone',age=20):? #初始化 創(chuàng)建對象時會執(zhí)行? 傳入兩個對象值? 注init必須要前面后面兩個下劃線

? ? ? ? self.name=name

? ? ? ? self.age = age

? ? ? ? print("human init")

#? ? #類的屬性

#? ? name = 'someone'

#? ? age = 100

? ? #類的方法

? ? def my_name(self):

? ? ? ? print("my name is :",self.name)

? ? def my_age(self):

? ? ? ? print("my age is :",self.age)

? ? def eat(self):

? ? ? ? print("eat")

? ? def think(self,a,b):

? ? ? ? print(a+b)

#person1 = human()? ? ? ? #創(chuàng)建一個person的對象?

#person1.name

#person1.name = 'zhangsan'

#print(person1.name)

#person1.think(23,25)


person2 = human('xiaoming',10)

person2 = human(name='xiaohong',age=10)

person2.my_name()

#類的繼承

class student(human):? ? ? ? ? #子類繼承父類

? ? pass

stu1 = student()

stu1.my_name()

class student(human):? ? ? ? ? #子類繼承父類

? ? def __init__(self,grade=1,school='MIT'):

? ? ? ? super().__init__()? ? ? #父類的初始化

? ? ? ? self.school = school

? ? ? ? self.grade = grade

? ? ? ? self.scroe = 100

? ? ? ? print("student init")


? ? ? ? #添加子類自己的方法

? ? def learn(self):

? ? ? ? print('learning')

? ? def my_school(self):

? ? ? ? print('my school is',self.school)

? ? #子類可以重寫父類方法

? ? def think(self,a,b):

? ? ? ? print(a*b)

stu2 = student(4)

stu2.my_age()

stu2.learn()

stu2.my_school()

stu2.think(3,5)

#文件讀寫

text = 'Writing a text \n hello world'

print(text)

my_file = open('file1.txt','w')? ? ? ? ? #以寫入方式打開文件 如果文件不存在則會在當(dāng)前文件目錄創(chuàng)建文件 或者在指定路徑創(chuàng)建文件

my_file.write(text)

my_file.close()

with open('file2.txt','w') as f2:? ? ? ? #? 清空文件 然后寫入? ? ? ? ? ? ? ? ? ? ? ? 使用with的話就不用使用close命令

? ? f2.write('hahaha\n123123')

with open('file2.txt','a') as f2:? ? ? ? #? 在文件最后追加內(nèi)容? ? ? ? ? ? ? ? ? ? ? ? 使用with的話就不用使用close命令

? ? f2.write(text)

with open('file2.txt','r') as f2:? ? ? ? #? 以讀取方式打開文件? ? ? ? ? ? ? ? ? ? ? ? 使用with的話就不用使用close命令

? ? content = f2.read()? ? ? ? ? ? ? ? ? # 讀取全部內(nèi)容

? ? print(content)

with open('file2.txt','r') as f2:? ? ? ? #? 以讀取方式打開文件? ? ? ? ? ? ? ? ? ? ? ? 使用with的話就不用使用close命令

? ? content = f2.readline()? ? ? ? ? ? ? # 讀取文件第一行? ? ? 若要讀取多行用readlines 會將所有行存放到一個列表中

? ? print(content)

#將所有的行打印出來‘

filename = 'file2.txt'

with open(filename) as f:

? ? for line in f:

? ? ? ? print(line)? ? ? ? ? ? ? ? ? ? ? #若要去除換行符 用line.rstrip()

#異常處理

#file = open('hahaha','r+')? ? ? ? ? ? ? ? #先去讀一個文件 如果能打開的話就可以寫入顯然會出現(xiàn)錯誤

try:

? ? file = open('hahaha','r+')

except Exception as e:

? ? print(e)

try:

? ? file = open('hahaha','r+')

except Exception as e:

? ? print(e)

? ? response = input('Do you want to creat it ')

? ? if(response=='yes'):

? ? ? ? with open('hahaha','w') as f:

? ? ? ? ? ? pass

? ? ? ? print('The file was created successfully')

? ? else:

? ? ? ? pass

else:? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? #如果文件沒有出錯

? ? file.write('hahahahahahahahahah')

? ? file.close()

#數(shù)據(jù)存儲

import json

a_dict = {'user_id':'qdf','user_name':'assf',100:200}

with open('example.json','w')as f:

? ? json.dump(a_dict,f)

with open('example.json')as f:

? ? content = json.load(f)

? ? print(content)

#猜數(shù)字小游戲

import random

n = random.randint(1,100)? ? ? ? ? #生成一個1-100的隨機整數(shù)

step = 0? ? ? ? ? ? ? ? ? ? ? ? ? #游戲的步數(shù)

print ('Game start')

def get_number():

? ? guess = input('Please enter an integer from 1 to 100:')

? ? while True:

? ? ? ? if guess.isdigit():? ? ? ? #判斷輸入內(nèi)容是否是數(shù)字

? ? ? ? ? ? guess = int(guess)

? ? ? ? ? ? return guess

? ? ? ? else:

? ? ? ? ? ? guess = input('Please enter an integer from 1 to 100:')

guess = get_number()

low=0

high=100

while True:

? ? step+=1

? ? print('step',step)

? ? if guess ==0:? ? ? ? #退出游戲

? ? ? ? print('quit')

? ? ? ? break

? ? if guess<n:

? ? ? ? print(guess,'is low')

? ? ? ? low = guess+1

? ? elif guess>n:

? ? ? ? print(guess,'is high')

? ? ? ? high = guess+1

? ? else:

? ? ? ? print('You win!')

? ? ? ? break

? ? print('You can try ',low,'to',high)

? ? guess = get_number()

print('Game over')

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容