Python基础入门——基本
print('hello world') # Note that print is a function
注释多行代码:选中代码,Ctrl + / 使用 ''' ''' 或者 """ """ ,将需要注释的内容插入其中即可
计算
Numbers
- integers and floats.
Strings
#换行打印 """ """ 也可 s = '''This is a multi-line string. This is the second line.''' silly_string = '''He said, "Aren't can't shouldn't wouldn't."''' single_quote_str = 'He said, "Aren\'t can\'t shouldn\'t wouldn\'t."' # ' escaping double_quote_str = "He said, \"Aren't can't shouldn't wouldn't.\"" # " #format 方法 age = 20 name = 'Swaroop' print('{0} was {1} years old when he wrote this book'.format(name, age)) print('Why is {0} playing with that python?'.format(name)) print('{} was {} years old when he wrote this book'.format(name, age)) print('Why is {} playing with that python?'.format(name)) #或者使用 %s myscore = 1000 message = 'I scored %s points' print(message % myscore) nums = 'What did the number %s say to the number %s? Nice belt!!' print(nums % (0, 8)) #字符串乘法 print(10 * 'a')
List
可以操作 其中的元素可以是数字、字符串或者列表
wizard_list[2] #第三个元素 wizard_list[2:5] #第三到第五个元素 mylist = [numbers, strings] #列表中的两个元素也是列表 wizard_list.append('bear burp') #在末尾增加元素 del wizard_list[5] #删除第六个元素 list3 = list1 + list2 #列表加法 合并 [1, 2, 3, 4, 'I', 'tripped', 'over', 'and', 'hit', 'the', 'floor'] list1 = [1, 2] print(list1 * 5) #列表乘法 得到 [1, 2, 1, 2, 1, 2, 1, 2, 1, 2] #list1 + 50 错误 指不定list里面有字符串 #不能使用division (/) 和subtraction (-) #That dumb computer sees things only in black and white.Ask it to make a complicated decision, and it throws up its hands with errors.
Tuples
列表使用 parentheses 括号
The main difference between a tuple and a list is that a tuple cannot change once you’ve created it.
fibs = (0, 1, 1, 2, 3)
Map(each key maps to a particular value),
In Python, a map (also referred to as a dict, short for dictionary) is a collection of things, like lists and tuples. Each item in a map has a key and a corresponding value. For example, say we have a list of people and their favorite sports:
favorite_sports = {'Ralph Williams' : 'Football','Michael Tippett' : 'Basketball','Edward Elgar' : 'Baseball'} print(favorite_sports['Rebecca Clarke']) #打印值 del favorite_sports['Ethel Smyth'] #删除 favorite_sports['Ralph Williams'] = 'Ice Hockey' #更改值
if 语句
We combine conditions and responses into if statements. Conditions can be more complicated than a single question, and if statements can also be combined with multiple questions and different responses based on the answer to each question.
age = 13 if age > 20: print('You are too old!') #The lines following the colon must be in a block
A block of code is a grouped set of programming statements.
Each line in the block has four spaces at the beginning:
In Python, whitespace, such as a tab or a space, is meaningful. Code that is at the same position (indented the same number of spaces from the left margin) is grouped into a block, and whenever you start a new line with more spaces than the previous one, you are starting a new block that is part of the previous one, like this:
We group statements together into blocks because they are related. The statements need to be run together. When you change the indentation, you’re generally creating new blocks.
Python expects you to use the same number of spaces for all the lines in a block. So if you start a block with four spaces, you should consistently use four spaces for that block. Here’s an example:
A condition is a programming statement that compares things and tells us whether the criteria set by the comparison are either True (yes) or False (no). For example, age > 10 is a condition, and is another way of saying, “Is the value of the age variable greater than 10?” We use symbols in Python (called operators) to create our conditions, such as equal to, greater than, and less than:
if-then-else statement /if and elif statements /Combining Conditions
if age == 12: print("A pig fell in the mud!") else: print("Shh. It's a secret.") if age == 10: print("What do you call an unhappy cranberry?") elif age == 11: print("What did the green grape say to the blue grape?") else: print("Huh?") if age == 10 or age == 11 or age == 12 or age == 13: print('What is 13 + 49 + 84 + 155 + 97? A headache!') else: print('Huh?') if age >= 10 and age <= 13:
an empty value is referred to as None, and it is the absence of value. And it’s important to note that the value None is different
from the value 0 because it is the absence of a value, rather than a number with a value of 0.
myval = None
Assigning a value of None to a variable is one way to reset it to its original, empty state. Setting a variable to None is also a way to define a variable without setting its value.
strings 和 numbers 转换
age = '10' converted_age = int(age) age = '10.5' converted_age = float(age) age = 10 converted_age = str(age)
Loops 循环(for 和 while)
for x in range(0, 5): print('hello %s' % x) #注意没有逗号哦
range函数用于创建数字列表 That may sound a little confusing. Let’s combine the range function with the list function to see exactly how this works. The range function doesn’t actually create a list of numbers; it returns an iterator, which is a type of Python object specially designed to work with loops. However, if we combine range with list, we get a list of numbers.
In the case of the for loop, the code is actually telling Python to do the following:
• Start counting from 0 and stop before reaching 5.
• For each number we count, store the value in the variable x. Then Python executes the block of code
You don’t need to stick to using the range and list functions when making for loops. You could also use a list you’ve already created:
wizard_list = ['spider legs', 'toe of frog', 'snail tongue','bat wing', 'slug butter', 'bear burp'] for i in wizard_list: print(i) #This code is a way of saying, “For each item in wizard_list, store the value in the variable i, and then print the contents of that variable.” ingredients = ['snails', 'leeches', 'gorilla belly-button lint','caterpillar eyebrows', 'centipede toes'] x=0; for i in ingredients: x=x+1; print(x,'---',i)#原来打印的时候逗号隔开就是一个空格间隔了
Python expects the number of spaces in a block to be consistent. It doesn’t matter how many spaces you insert, as long as you use the same number for every new line
hugehairypants = ['huge', 'hairy', 'pants'] for i in hugehairypants: print(i) for j in hugehairypants: print(j) for week in range(1, 53): coins = coins + magic_coins - stolen_coins print('Week %s = %s' % (week, coins))
A for loop is a loop of a specific length, whereas a while loop is a loop that is used when you don’t know ahead of time when it needs to stop looping.
while 循环
x = 45 y = 80 while x < 50 and y < 100: x = x + 1 y = y + 1 print(x, y)
1. Check the condition. 2. Execute the code in the block. 3. Repeat.
Another common use of a while loop is to create semi-eternal loops.
while True: lots of code here lots of code here lots of code here if some_value == True: break
Reuse code代码重用
If you don’t reuse some of what you’re doing, you’ll eventually wear your fingers down to painful stubs through overtyping.
Reuse also makes your code shorter and easier to read.
Using functions 函数
Functions are chunks of code that tell Python to do something. They are one way to reuse code—you can use functions in your programs again and again.
函数包括: a name, parameters, and a body. 函数名 参数 内容
#定义函数 def testfunc(myname): print('hello %s' % myname) def savings(pocket_money, paper_route, spending): return pocket_money + paper_route – spending#返回值 another_variable = 100 #函数内的变量作用范围只在函数中 def variable_test(): first_variable = 10 second_variable = 20 return first_variable * second_variable * another_variable def spaceship_building(cans): total_cans = 0 for week in range(1, 53): total_cans = total_cans + cans print('Week %s = %s cans' % (week, total_cans)) #调用函数 testfunc('Mary') #hello Mary print(variable_test())
The name of this function is testfunc. It has a single parameter, myname, and its body is the block of code immediately following the line beginning with def (short for define). A parameter is a variable that exists only while a function is being used. You can run the function by calling its name, using parentheses around the parameter value.
Functions can also be grouped together into modules, which is where Python becomes really useful, as opposed to just mildly useful.
Using Modules 使用模块(包)
Modules are used to group functions, variables, and other things together into larger, more powerful programs. Some modules are built in to Python, and you can download other modules separately.
You’ll find modules to help you write games (such as tkinter, which is built in, and PyGame, which is not), modules for manipulating images (such as PIL, the Python Imaging Library), and modules for drawing three-dimensional graphics (such as Panda3D). Modules can be used to do all sorts of useful things.
you could calculate the current date and time using a built-in module called time.
Here, the import command is used to tell Python that we want to use the module time. We can then call functions that are available in this module, using the dot symbol.For example, here’s how we might call the asctime function with the time module:
import time print(time.asctime()) #The function asctime is a part of the time module that returns the current date and time, as a string
Inside the sys module is a special object called stdin (for standard input), which provides a rather useful function called readline. The readline function is used to read a line of text typed on the keyboard until you press enter.
def silly_age_joke(): print('How old are you?') age = int(sys.stdin.readline())#在jupyter运行的时候可能会报错 这里理解就好 if age >= 10 and age <= 13: print('What is 13 + 49 + 84 + 155 + 97? A headache!') else: print('Huh?') silly_age_joke()
Objects are a way of organizing code in a program and breaking things down to make it easier to think about complex ideas.
we used classes to create categories of things and made objects (instances) of those classes. You learned how the child of a class inherits the functions of its parent, and that even though two objects are of the same class, they’re not necessarily clones. For example, a giraffe object can have its own number of spots. You learned how to call (or run) functions on an object and how object variables are a way of saving values in those objects. Finally, we used the self parameter in functions to refer to other functions and variables.
Breaking things into Classes
In Python, objects are defined by classes, which we can think of as a way to classify objects into groups. Here is a tree diagram of the classes that giraffes and sidewalks would fit into based on our preceding definitions:
We can use classes to organize bits of Python code.
class Things: pass #To tell Python that a class is a child of another class, we add the name of the parent class in parentheses after the name of our new class class Inanimate(Things): pass class Animate(Things): pass class Sidewalks(Inanimate): pass class Animals(Animate): def breathe(self): print('breathing') def move(self): print('moving') class Mammals(Animals): pass class Giraffes(Mammals): def eat_leaves_from_trees(self): print('eating leaves') #create an object in the Giraffes class and assign it to the variable reginald reginald = Giraffes() reginald.move()
Classes and objects make it easy to group functions.
functions Calling other functions
Initializing an object
Sometimes when creating an object, we want to set some values (also called properties) for later use. For example, suppose we want to set the number of spots on our giraffe objects when they are created—that is, when they’re initialized. To do this, we create an __init__ function .
This is a special type of function in Python classes and must have this name. The init function is a way to set the properties for an object when the object is first created, and Python will automatically call this function when we create a new object.
the init function also needs to have self as the first parameter. Next, we set the parameter spots to an object variable (its property) called giraffe_spots using the self parameter, with the code self.giraffe_spots = spots. You might think of this line of code as saying, “Take the value of the parameter spots and save it for later (using the object variable giraffe_spots).” Just as one function in a class can call another function using the self parameter, variables in the class are also accessed using self. 父类的函数可以继承到子类使其使用
Python’s built-in functions don’t need to be imported first 内置函数
print(abs(-10)) #绝对值 print(bool(0)) #False print(bool(None)) #False my_silly_list = [] print(bool(my_silly_list)) #False print(bool(' ')) #True print(bool('a')) #True
dir 作提示用
The dir function (short for directory) returns information about any value. Basically, it tells you the functions that can be used with that value in alphabetical order.
The dir function can be useful when you have a variable and quickly want to find out what you can do with it.
The ellipsis (...) means that upper is a built-in function of the string class and, in this case, takes no parameters. The arrow (->) on the next line means that this function returns a string (str). The last line offers a brief description of what the function does.
eval
The eval function (short for evaluate) takes a string as a parameter and runs it as though it were a Python expression. For example, eval('print("wow")') will actually run the statement print("wow").
The eval function works only with simple expressions.Expressions that are split over more than one line (such as if statements) generally won’t evaluate
Since user input is read in as a string, Python needs to convert it into numbers and operators before doing any calculations.
exec
The exec function is like eval, except that you can use it to run more complicated programs. The difference between the two is that eval returns a value (something that you can save in a variable), whereas exec does not.
Players of the game would provide the instructions for their robot as mini Python programs. The Dueling Robots game would read in these scripts and use exec to run.
其实这个可以很有用 程序中运行程序 游戏中进行指令发布
The float function converts a string or a number into a floatingpoint number, which is a number with a decimal place (also called a real number). For example, the number 10 is an integer (also called a whole number), but 10.0, 10.1, and 10.253 are all floatingpoint numbers (also called floats).
The len function returns the length of an object or, in the case of a string, the number of characters in the string.
max() min() The max function returns the largest item in a list, tuple, or string.
The numbers that range generates begin with the number given as the first parameter and end with the number that’s one less than the second parameter.
The range function actually returns a special object called an iterator that repeats an action a number of times. In this case, it returns the next highest number each time it is called. You can convert the iterator into a list (using the function list). If you then print the returned value when calling range, you’ll see the numbers it contains as well:
You can also add a third parameter to range, called step. Each number in the list increases by two from the previous number, and the list ends with the number 28, which is 2 less than 30.
The sum function adds items in a list and returns the total.
Working with files 文件读写
使用python内置函数 open 对文件进行读写
test_file = open('c:\\test.txt') text = test_file.read() print(text) test_file = open('c:\\myfile.txt', 'w') test_file.write('What is green and loud? A froghorn!')#写入 test_file.close()#关闭文件
The parameter 'w' tells Python that we want to write to the file object, rather than read from it.
On the first line, we use open, which returns a file object with functions for working with files. The parameter we use with the open function is a string telling Python where to find the file.
On the second line, we use the read function, provided by the file object, to read the contents of the file and store it in the variable text. We print the variable on the final line to display the contents of the file.
使用Module
Python uses modules to group functions and classes in order to make them easier to use.
import copy harry = Animal('hippogriff', 6, 'pink') harriet = copy.copy(harry) my_animals = [harry, carrie, billy] more_animals = copy.copy(my_animals) #浅拷贝只是一个影子 原来的变了 它就变 不过原来的list增加了元素 它不会增加 '''copy actually makes a shallow copy, which means it doesn’t copy objects inside the objects we copied. Here, it has copied the main list object but not the individual objects inside the list. So we end up with a new list that does not have its own new objects—the list more_animals has the same three objects inside it. By the same token, if we add a new animal to the first list (my_animals), it doesn’t appear in the copy (more_animals). ''' '''deepcopy, actually creates copies of all objects inside the object being copied. When we use deepcopy to copy my_animals, we get a new list complete with copies of all of its objects. 深拷贝''' more_animals = copy.deepcopy(my_animals) my_animals[0].species = 'wyrm' print(more_animals[0].species)
随机数
#插一嘴关键词 import keyword print(keyword.iskeyword('if')) print(keyword.kwlist) # import random print(random.randint(1, 100))#打印1-100之间随机数 desserts = ['ice cream', 'pancakes', 'brownies', 'cookies','candy'] print(random.choice(desserts)) #列表中随机选取一个元素 random.shuffle(desserts) #打乱列表顺序 #The sys module contains system functions that you can use to control the Python shell itself import sys sys.exit() print(sys.version)
时间
import time print(time.time()) #The number returned by the call to time() is actually the number of seconds since January 1, 1970, at 00:00:00 AM to be exact. #计算某段程序运行时间 t1 = time.time() for x in range(0, max): print(x) t2 = time.time() print('it took %s seconds' % (t2-t1)) #The function asctime takes a date as a tuple and converts it into something more readable. print(time.asctime()) #返回现在的时间 Wed Apr 1 22:04:40 2020 #The values in the sequence are year, month, day, hours, minutes, seconds, day of the week (0 is Monday, 1 is Tuesday, and so on), day of the year (we put 0 as a placeholder), and whether or not it is daylight saving time (0 if it isn’t; 1 if it is). t = (2020, 2, 23, 10, 30, 48, 6, 0, 0) print(time.asctime(t))#Sun Feb 23 10:30:48 2020 print(time.localtime())#localtime returns the current date and time as an object time.sleep(1)#延迟
The pickle module is used to convert Python objects into something that can be written into a file and then easily read back out
we use dump to pass in the map and the file variable as two parameters.
Plain text files contain only characters that humans can read. Images, music files, movies, and pickled Python objects have information that isn’t always readable by humans, so they’re known as binary files
We can unpickle objects we’ve written to the file using pickle’s load function