python猜数字1001untitled_ML - Python 基础
數據類型 Numeric & String
1. Python數據類型
1.1 總體:numerics, sequences, mappings, classes, instances, and exceptions
1.2 Numeric Types: int (包含boolean), float, complex
1.3 int: unlimited length; float: 實現用double in C, 可查看 sys.float_info; complex: real(實部) & imaginary(虛部),用z.real 和 z.imag來取兩部分
import sys
a = 3
b = 4
c = 5.66
d = 8.0
e = complex(c, d)
f = complex(float(a), float(b))
print (*"a is type"* , type(a))
print (*"b is type"* , type(b))
print (*"c is type"* , type(c))
print (*"d is type"* , type(d))
print (*"e is type"* , type(e))
print (*"f is type"* , type(f))
print(a + b)
print(d / c)
print (b / a)
print (b // a)
print (e)
print (e + f)
print (*"e's real part is: "* , e.real)
print (*"e's imaginary part is: "* , e.imag)
print (sys.float_info)
D:\Anaconda3\python.exe D:/python/untitled1/note08.py
a is type
b is type
c is type
d is type
e is type
f is type
7
1.4134275618374559
1.3333333333333333
1
(5.66+8j)
(8.66+12j)
e's real part is: 5.66
e's imaginary part is: 8.0
sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.220446049250313e-16, radix=2, rounds=1)
Process finished with exit code 0
字符串(String)&變量 (Variable)
字符串:
一串字符
顯示或者打印出來文字信息
導出
編碼:# -- coding: utf-8 --
單引號,雙引號,三引號
不可變(immutable)
Format字符串
age = 3
name = "Tom"
print("{0} was {1} years old".format(name, age))
聯合:+: print(name + " was " + str(age) + " years old")
換行符: print("What's your name? \nTom")
字面常量(literal constant):
可以直接以字面的意義使用它們:
如:6,2.24,3.45e-3, "This is a string"
常量:不會被改變
變量:
儲存信息
屬于identifier
identifier命名規則:
第一個字符必須是字母或者下劃線
其余字符可以是字母,數字,或者下劃線
區分大小寫
如:合法:i, name_3_4, big_bang
不合法:2people, this is tom, my-name, >123b_c2
注釋: #
縮進(Indentation)
數據結構:列表(List)
print中的編碼:
編碼:# -- coding: utf-8 --
print中的換行
print("What's your name? \nTom")
List
創建
訪問
更新
刪除
腳本操作符
函數方法
# -*- coding: utf-8 -*-
#創建一個列表
number_list = [1, 3, 5, 7, 9]
string_list = ["abc", "bbc", "python"]
mixed_list = ['python', 'java', 3, 12]
#訪問列表中的值
second_num = number_list[1]
third_string = string_list[2]
fourth_mix = mixed_list[3]
print("second_num: {0} third_string: {1} fourth_mix: {2}".format(second_num, third_string, fourth_mix))
#更新列表
print("number_list before: " + str(number_list))
number_list[1] = 30
print("number_list after: " + str(number_list))
#刪除列表元素
print("mixed_list before delete: " + str(mixed_list))
del mixed_list[2]
print("mixed_list after delete: " + str(mixed_list))
#Python腳本語言
print(len([1,2,3])) #長度
print([1,2,3] + [4,5,6]) #組合
print(['Hello'] * 4) #重復
print(3 in [1,2,3]) #某元素是否在列表中
#列表的截取
abcd_list =['a', 'b', 'c', 'd']
print(abcd_list[1])
print(abcd_list[-2])
print(abcd_list[1:])
D:\Anaconda3\python.exe D:/python/untitled1/note08.py
second_num: 3 third_string: python fourth_mix: 12
number_list before: [1, 3, 5, 7, 9]
number_list after: [1, 30, 5, 7, 9]
mixed_list before delete: ['python', 'java', 3, 12]
mixed_list after delete: ['python', 'java', 12]
3
[1, 2, 3, 4, 5, 6]
['Hello', 'Hello', 'Hello', 'Hello']
True
b
c
['b', 'c', 'd']
Process finished with exit code 0
列表操作包含以下函數:
1、cmp(list1, list2):比較兩個列表的元素
2、len(list):列表元素個數
3、max(list):返回列表元素最大值
4、min(list):返回列表元素最小值
5、list(seq):將元組轉換為列表
列表操作包含以下方法:
1、list.append(obj):在列表末尾添加新的對象
2、list.count(obj):統計某個元素在列表中出現的次數
3、list.extend(seq):在列表末尾一次性追加另一個序列中的多個值(用新列表擴展原來的列表)
4、list.index(obj):從列表中找出某個值第一個匹配項的索引位置
5、list.insert(index, obj):將對象插入列表
6、list.pop(obj=list[-1]):移除列表中的一個元素(默認最后一個元素),并且返回該元素的值
7、list.remove(obj):移除列表中某個值的第一個匹配項
8、list.reverse():反向列表中元素
9、list.sort([func]):對原列表進行排序
tuple(元組)
創建只有一個元素的tuple,需要用逗號結尾消除歧義
a_tuple = (2,)
tuple中的list
mixed_tuple = (1, 2, ['a', 'b'])
print("mixed_tuple: " + str(mixed_tuple))
mixed_tuple[2][0] = 'c'
mixed_tuple[2][1] = 'd'
print("mixed_tuple: " + str(mixed_tuple))
D:\Anaconda3\python.exe D:/python/untitled1/note08.py
mixed_tuple: (1, 2, ['a', 'b'])
mixed_tuple: (1, 2, ['c', 'd'])
Process finished with exit code 0
Tuple 是不可變 list。 一旦創建了一個 tuple 就不能以任何方式改變它。
Tuple 與 list 的相同之處
定義 tuple 與定義 list 的方式相同, 除了整個元素集是用小括號包圍的而不是方括號。
Tuple 的元素與 list 一樣按定義的次序進行排序。 Tuples 的索引與 list 一樣從 0 開始, 所以一個非空 tuple 的第一個元素總是 t[0]。
負數索引與 list 一樣從 tuple 的尾部開始計數。
與 list 一樣分片 (slice) 也可以使用。注意當分割一個 list 時, 會得到一個新的 list ;當分割一個 tuple 時, 會得到一個新的 tuple。
Tuple 不存在的方法
您不能向 tuple 增加元素。Tuple 沒有 append 或 extend 方法。
您不能從 tuple 刪除元素。Tuple 沒有 remove 或 pop 方法。
然而, 您可以使用 in 來查看一個元素是否存在于 tuple 中。
用 Tuple 的好處
Tuple 比 list 操作速度快。如果您定義了一個值的常量集,并且唯一要用它做的是不斷地遍歷它,請使用 tuple 代替 list。
如果對不需要修改的數據進行 “寫保護”,可以使代碼更安全。使用 tuple 而不是 list 如同擁有一個隱含的 assert 語句,說明這一數據是常量。如果必須要改變這些值,則需要執行 tuple 到 list 的轉換。
Tuple 與 list 的轉換
Tuple 可以轉換成 list,反之亦然。內置的 tuple 函數接收一個 list,并返回一個有著相同元素的 tuple。而 list 函數接收一個 tuple 返回一個 list。從效果上看,tuple 凍結一個 list,而 list 解凍一個 tuple。
Tuple 的其他應用
一次賦多值
v = ('a', 'b', 'e')
(x, y, z) = v
解釋:v 是一個三元素的 tuple, 并且 (x, y, z) 是一個三變量的 tuple。將一個 tuple 賦值給另一個 tuple, 會按順序將 v 的每個值賦值給每個變量。
字典 (Dictionary)
字典內置函數&方法( 鍵(key),對應值(value))
Python字典包含了以下內置函數:
1、cmp(dict1, dict2):比較兩個字典元素。
2、len(dict):計算字典元素個數,即鍵的總數。
3、str(dict):輸出字典可打印的字符串表示。
4、type(variable):返回輸入的變量類型,如果變量是字典就返回字典類型。
Python字典包含了以下內置方法:
1、radiansdict.clear():刪除字典內所有元素
2、radiansdict.copy():返回一個字典的淺復制
3、radiansdict.fromkeys():創建一個新字典,以序列seq中元素做字典的鍵,val為字典所有鍵對應的初始值
4、radiansdict.get(key, default=None):返回指定鍵的值,如果值不在字典中返回default值
5、radiansdict.has_key(key):如果鍵在字典dict里返回true,否則返回false
6、radiansdict.items():以列表返回可遍歷的(鍵, 值) 元組數組
7、radiansdict.keys():以列表返回一個字典所有的鍵
8、radiansdict.setdefault(key, default=None):和get()類似, 但如果鍵不已經存在于字典中,將會添加鍵并將值設為default
9、radiansdict.update(dict2):把字典dict2的鍵/值對更新到dict里
10、radiansdict.values():以列表返回字典中的所有值
# -*- coding: utf-8 -*-
#創建一個詞典
phone_book = {'Tom': 123, "Jerry": 456, 'Kim': 789}
mixed_dict = {"Tom": 'boy', 11: 23.5}
#訪問詞典里的值
print("Tom's number is " + str(phone_book['Tom']))
print('Tom is a ' + mixed_dict['Tom'])
#修改詞典
phone_book['Tom'] = 999
phone_book['Heath'] = 888
print("phone_book: " + str(phone_book))
phone_book.update({'Ling':159, 'Lili':247})
print("updated phone_book: " + str(phone_book))
#刪除詞典元素以及詞典本身
del phone_book['Tom']
print("phone_book after deleting Tom: " + str(phone_book))
#清空詞典
phone_book.clear()
print("after clear: " + str(phone_book))
#刪除詞典
del phone_book
# print("after del: " + str(phone_book))
#不允許同一個鍵出現兩次
rep_test = {'Name': 'aa', 'age':5, 'Name': 'bb'}
print("rep_test: " + str(rep_test))
#鍵必須不可變,所以可以用數,字符串或者元組充當,列表不行
list_dict = {['Name']: 'John', 'Age':13}
list_dict = {('Name'): 'John', 'Age':13}
D:\Anaconda3\python.exe D:/python/untitled1/note08.py
Tom's number is 123
Tom is a boy
phone_book: {'Tom': 999, 'Jerry': 456, 'Kim': 789, 'Heath': 888}
updated phone_book: {'Tom': 999, 'Jerry': 456, 'Kim': 789, 'Heath': 888, 'Ling': 159, 'Lili': 247}
phone_book after deleting Tom: {'Jerry': 456, 'Kim': 789, 'Heath': 888, 'Ling': 159, 'Lili': 247}
after clear: {}
rep_test: {'Name': 'bb', 'age': 5}
Traceback (most recent call last):
File "D:/python/untitled1/note08.py", line 46, in
list_dict = {['Name']: 'John', 'Age':13}
TypeError: unhashable type: 'list'
Process finished with exit code 1
函數
函數:程序中可重復使用的程序段
給一段程程序起一個名字,用這個名字來執行一段程序,反復使用 (調用函數)
用關鍵字 ‘def' 來定義,identifier(參數)
identifier
參數list
return statement
局部變量 vs 全局變量
# -*- coding: utf-8 -*-
#沒有參數和返回的函數
def say_hi():
print(" hi!")
say_hi()
say_hi()
#有參數,無返回值
def print_sum_two(a, b):
c = a + b
print(c)
print_sum_two(3, 6)
def hello_some(str):
print("hello " + str + "!")
hello_some("China")
hello_some("Python")
#有參數,有返回值
def repeat_str(str, times):
repeated_strs = str * times
return repeated_strs
repeated_strings = repeat_str("Happy Birthday!", 4)
print(repeated_strings)
#全局變量與局部 變量
x = 60
def foo(x):
print("x is: " + str(x))
x = 3
print("change local x to " + str(x))
foo(x)
print('x is still', str(x))
x = 60
def foo():
global x
print("x is: " + str(x))
x = 3
print("change local x to " + str(x))
foo()
print('value of x is', str(x))
D:\Anaconda3\python.exe D:/python/untitled1/note08.py
hi!
hi!
9
hello China!
hello Python!
Happy Birthday!Happy Birthday!Happy Birthday!Happy Birthday!
x is: 60
change local x to 3
x is still 60
x is: 60
change local x to 3
value of x is 3
Process finished with exit code 0
默認參數
關鍵字參數
VarArgs參數
# -*- coding: utf-8 -*-
# 默認參數
def repeat_str(s, times=1):
repeated_strs = s * times
return repeated_strs
repeated_strings = repeat_str("Happy Birthday!")
print(repeated_strings)
repeated_strings_2 = repeat_str("Happy Birthday!", 4)
print(repeated_strings_2)
# 不能在有默認參數后面跟隨沒有默認參數
# f(a, b =2)合法
# f(a = 2, b)非法
# 關鍵字參數: 調用函數時,選擇性的傳入部分參數
def func(a, b=4, c=8):
print('a is', a, 'and b is', b, 'and c is', c)
func(13, 17)
func(125, c=24)
func(c=40, a=80)
# VarArgs參數
def print_paras(fpara, *nums, **words):
print("fpara: " + str(fpara))
print("nums: " + str(nums))
print("words: " + str(words))
print_paras("hello", 1, 3, 5, 7, word="python", anohter_word="java")
D:\Anaconda3\python.exe D:/python/untitled1/note08.py
Happy Birthday!
Happy Birthday!Happy Birthday!Happy Birthday!Happy Birthday!
a is 13 and b is 17 and c is 8
a is 125 and b is 4 and c is 24
a is 80 and b is 4 and c is 40
fpara: hello
nums: (1, 3, 5, 7)
words: {'word': 'python', 'anohter_word': 'java'}
Process finished with exit code 0
控制流:if & for 語句
if 語句
if condition:
do something
elif other_condition:
do something
for 語句
# -*- coding: utf-8 -*-
#if statement example
number = 59
guess = int(input('Enter an integer : '))
if guess == number:
# New block starts here
print('Bingo! you guessed it right.')
print('(but you do not win any prizes!)')
# New block ends here
elif guess < number:
# Another block
print('No, the number is higher than that')
# You can do whatever you want in a block ...
else:
print('No, the number is a lower than that')
# you must have guessed > number to reach here
print('Done')
# This last statement is always executed,
# after the if statement is executed.
#the for loop example
for i in range(1, 10):
print(i)
else:
print('The for loop is over')
a_list = [1, 3, 5, 7, 9]
for i in a_list:
print(i)
a_tuple = (1, 3, 5, 7, 9)
for i in a_tuple:
print(i)
a_dict = {'Tom':'111', 'Jerry':'222', 'Cathy':'333'}
for ele in a_dict:
print(ele)
print(a_dict[ele])
for key, elem in a_dict.items():
print(key, elem)
D:\Anaconda3\python.exe D:/python/untitled1/note08.py
Enter an integer : 77
No, the number is a lower than that
Done
1
2
3
4
5
6
7
8
9
The for loop is over
1
3
5
7
9
1
3
5
7
9
Tom
111
Jerry
222
Cathy
333
Tom 111
Jerry 222
Cathy 333
Process finished with exit code 0
控制流:while & range語句
# -*- coding: utf-8 -*-
number = 59
guess_flag = False
while guess_flag == False:
guess = int(input('Enter an integer : '))
if guess == number:
# New block starts here
guess_flag = True
# New block ends here
elif guess < number:
# Another block
print('No, the number is higher than that, keep guessing')
# You can do whatever you want in a block ...
else:
print('No, the number is a lower than that, keep guessing')
# you must have guessed > number to reach here
print('Bingo! you guessed it right.')
print('(but you do not win any prizes!)')
print('Done')
D:\Anaconda3\python.exe D:/python/untitled1/note08.py
Enter an integer : 66
No, the number is a lower than that, keep guessing
Enter an integer : 38
No, the number is higher than that, keep guessing
Enter an integer : 59
Bingo! you guessed it right.
(but you do not win any prizes!)
Done
Process finished with exit code 0
# -*- coding: utf-8 -*-
number = 59
num_chances = 3
print("you have only 3 chances to guess")
for i in range(1, num_chances + 1):
print("chance " + str(i))
guess = int(input('Enter an integer : '))
if guess == number:
# New block starts here
print('Bingo! you guessed it right.')
print('(but you do not win any prizes!)')
break
# New block ends here
elif guess < number:
# Another block
print('No, the number is higher than that, keep guessing, you have ' + str(num_chances - i) + ' chances left')
# You can do whatever you want in a block ...
else:
print('No, the number is lower than that, keep guessing, you have ' + str(num_chances - i) + ' chances left')
# you must have guessed > number to reach here
print('Done')
D:\Anaconda3\python.exe D:/python/untitled1/note08.py
you have only 3 chances to guess
chance 1
Enter an integer : 55
No, the number is higher than that, keep guessing, you have 2 chances left
chance 2
Enter an integer : 69
No, the number is lower than that, keep guessing, you have 1 chances left
chance 3
Enter an integer : 23
No, the number is higher than that, keep guessing, you have 0 chances left
Done
Process finished with exit code 0
控制流:break, continue & pass
1. break
2. continue
3. pass
number = 59
while True:
guess = int(input('Enter an integer : '))
if guess == number:
# New block starts here
break
# New block ends here
if guess < number:
# Another block
print('No, the number is higher than that, keep guessing')
continue
# You can do whatever you want in a block ...
else:
print('No, the number is a lower than that, keep guessing')
continue
# you must have guessed > number to reach here
print('Bingo! you guessed it right.')
print('(but you do not win any prizes!)')
print('Done')
a_list = [0, 1, 2]
print("using continue:")
for i in a_list:
if not i:
continue
print(i)
print("using pass:")
for i in a_list:
if not i:
pass
print(i)
D:\Anaconda3\python.exe D:/python/untitled1/note08.py
Enter an integer : 23
No, the number is higher than that, keep guessing
Enter an integer : 59
Bingo! you guessed it right.
(but you do not win any prizes!)
Done
using continue:
1
2
using pass:
0
1
2
Process finished with exit code 0
輸入輸出方式介紹(Output Format)
str_1 = input("Enter a string: ")
str_2 = input("Enter another string: ")
print("str_1 is: " + str_1 + ". str_2 is :" + str_2)
print("str_1 is {} + str_2 is {}".format(str_1, str_2))
D:\Anaconda3\python.exe D:/python/untitled1/note08.py
Enter a string: fanrunqi
Enter another string: rookie
str_1 is: fanrunqi. str_2 is :rookie
str_1 is fanrunqi + str_2 is rookie
Process finished with exit code 0
讀寫文件
1. 寫出文件
2. 讀入文件
some_sentences = '''\
I love learning python
because python is fun
and also easy to use
'''
#Open for 'w'irting
f = open('sentences.txt', 'w')
#Write text to File
f.write(some_sentences)
f.close()
#If not specifying mode, 'r'ead mode is default
f = open('sentences.txt')
while True:
line = f.readline()
#Zero length means End Of File
if len(line) == 0:
break
print(line)
# close the File
f.close
D:\Anaconda3\python.exe D:/python/untitled1/note08.py
I love learning python
because python is fun
and also easy to use
Process finished with exit code 0
錯誤與異常處理(Error & Exceptions)
Python有兩種錯誤類型:
1. 語法錯誤(Syntax Errors)
2. 異常(Exceptions)
首先,try語句下的(try和except之間的代碼)被執行
如果沒有出現異常,except語句將被忽略
如果try語句之間出現了異常,try之下異常之后的代碼被忽略,直接跳躍到except語句
如果異常出現,但并不屬于except中定義的異常類型,程序將執行外圍一層的try語句,如果異常沒有被處理,將產生unhandled exception的錯誤
處理異常(Handling Exceptions)
#Handling exceptions
while True:
try:
x = int(input("Please enter a number"))
break
except ValueError:
print("Not valid input, try again...")
D:\Anaconda3\python.exe D:/python/untitled1/note08.py
Please enter a numberfan
Not valid input, try again...
Please enter a numberrun
Not valid input, try again...
Please enter a numberqi
Not valid input, try again...
Please enter a number7
Process finished with exit code 0
面向對象編程(Object-Oriented)和裝飾器(decorator)
1. 面向對象編程
Python支持面向對象編程
類(class):現實世界中一些事物的封裝 (如:學生)
類:屬性 (如:名字,成績)
類對象
實例對象
引用:通過引用對類的屬性和方法進行操作
實例化:創建一個類的具體實例對象 (如:學生張三)
2. 裝飾器(decorator)
class Student:
def __init__(self, name, grade):
self.name = name
self.grade = grade
def introduce(self):
print("hi! I'm " + self.name)
print("my grade is: " + str(self.grade))
def improve(self, amount):
self.grade = self.grade + amount
jim = Student("jim", 86)
jim.introduce()
jim.improve(10)
jim.introduce()
D:\Anaconda3\python.exe D:/python/untitled1/note08.py
hi! I'm jim
my grade is: 86
hi! I'm jim
my grade is: 96
Process finished with exit code 0
def add_candles(cake_func):
def insert_candles():
return cake_func() + " candles"
return insert_candles
def make_cake():
return "cake"
gift_func = add_candles(make_cake)
print(make_cake())
print(gift_func())
def add_candles(cake_func):
def insert_candles():
return cake_func() + " candles"
return insert_candles
def make_cake():
return "cake"
make_cake = add_candles(make_cake)
print(make_cake())
# print(gift_func)
def add_candles(cake_func):
def insert_candles():
return cake_func() + " and candles"
return insert_candles
@add_candles
def make_cake():
return "cake"
# make_cake = add_candles(make_cake)
print(make_cake())
# print(gift_func)
D:\Anaconda3\python.exe D:/python/untitled1/note08.py
cake
cake candles
cake candles
cake and candles
Process finished with exit code 0
圖形界面(GUI)
1. GUI: Graphical User Interface
2. tkinter: GUI library for Python
3. GUI Example
# -*- coding: utf-8 -*-
from tkinter import *
import tkinter.simpledialog as dl
import tkinter.messagebox as mb
# tkinter GUI Input Output Example
# 設置GUI
root = Tk()
w = Label(root, text="Label Title")
w.pack()
# 歡迎消息
mb.showinfo("Welcome", "Welcome Message")
guess = dl.askinteger("Number", "Enter a number")
output = 'This is output message'
mb.showinfo("Output: ", output)
猜數字游戲
# -*- coding: utf-8 -*-
from tkinter import *
import tkinter.simpledialog as dl
import tkinter.messagebox as mb
root = Tk()
w = Label(root, text = "Guess Number Game")
w.pack()
#歡迎消息
mb.showinfo("Welcome", "Welcome to Guess Number Game")
#處理信息
number = 59
while True:
#讓用戶輸入信息
guess = dl.askinteger("Number", "What's your guess?")
if guess == number:
# New block starts here
output = 'Bingo! you guessed it right, but you do not win any prizes!'
mb.showinfo("Hint: ", output)
break
# New block ends here
elif guess < number:
output = 'No, the number is a higer than that'
mb.showinfo("Hint: ", output)
else:
output = 'No, the number is a lower than that'
mb.showinfo("Hint: ", output)
print('Done')
總結
以上是生活随笔為你收集整理的python猜数字1001untitled_ML - Python 基础的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 南方和华安哪个基金好?南方基金和华安基金
- 下一篇: 大学生怎么买基金定投?定投一定会赚钱吗