PyCharm学习笔记及Python基础语法总结
来源:互联网 发布:mysql grouping 编辑:程序博客网 时间:2024/05/28 03:03
本文先介绍了PyCharm IDE工具的使用,然后基于Python3.6版本对Python基础语法知识进行了总结,包括覆盖模块、注释、打印、算术运算符、操作顺序、列表、元组、字典、条件运算符、逻辑运算符、if、else、elif、循环、for、while、break、continue、函数、返回、readline() 、字符串运算符、文件i/ o、类、对象等,最后介绍了Python Challenge在线编程闯关游戏。
PyCharm
一种PythonIDE,其带有一整套可以帮助用户在使用Python语言开发时提高其效率的工具,比如, 调试、语法高亮、Project管理、代码跳转、智能提示、自动完成、单元测试、版本控制等等。
Tip
在 Tool>>Python console 处,可调出Python Console
在 Editor>>Font 选项下,可修改字体
在导航处文件名右键 Split Vertically/Horizontally,可实现多窗口SHOW
在Preferences>>Project Interpreter处,可进行解释器设置
在Configurations>>Python interpreter及Preferences>>Project>>Project Interpreter处同时修改,可完成版本切换
KeyMap
cmd+B/click -->查看源码cmd+alt+l -->代码PEP8cmd+J -->插入常用代码shift+F9/F10 -->debug/run
Cheat Sheet
# import is used to make specialty functions available# These are called modulesimport randomimport sysimport os'''This is a multi-line comment'''# The arithmetic operators +, -, *, /, %, **, //# ** Exponential calculation# // Floor Divisionprint("5 * 2 =", 5*2)print("5 / 2 =", 5/2)print("5 % 2 =", 5%2)print("5 ** 2 =", 5**2)print("5 // 2 =", 5//2)# quote quote = "\"Always remember your unique,"multi_line_quote = ''' justlike everyone else" '''print(quote + multi_line_quote)# To embed a string in output use %sprint("%s %s %s" % ('I like the quote', quote, multi_line_quote))# To keep from printing newlines use end=""print("I don't like ",end="")print("newlines")# You can print a string multiple times with *print('\n' * 5)# LISTS -------------# A list allows you to create a list of values and manipulate themgrocery_list = ['Juice', 'Tomatoes', 'Potatoes', 'Bananas']print('The first item is', grocery_list[1])# You can change the value stored in a list boxgrocery_list[0] = "Green Juice"print(grocery_list)# You can get a subset of the list with [min:up to but not including max]print(grocery_list[1:3])# You can put any data type in a a list including a listother_events = ['Wash Car', 'Pick up Kids', 'Cash Check']to_do_list = [other_events, grocery_list]print(to_do_list)# Get the second item in the second list (Boxes inside of boxes)print(to_do_list[1][1])# You add values using appendgrocery_list.append('onions')print(to_do_list)# Insert item at given indexgrocery_list.insert(1, "Pickle")# Remove item from listgrocery_list.remove("Pickle")# Sorts items in listgrocery_list.sort()# Reverse sort items in listgrocery_list.reverse()# del deletes an item at specified indexdel grocery_list[4]print(to_do_list)# We can combine lists with a +to_do_list = other_events + grocery_listprint(to_do_list)# Get length of listprint(len(to_do_list))# Get the max item in listprint(max(to_do_list))# Get the minimum item in listprint(min(to_do_list))# TUPLES -------------# Values in a tuple can't change like listspi_tuple = (3, 1, 4, 1, 5, 9)# Convert tuple into a listnew_tuple = list(pi_tuple)# Convert a list into a tuple# new_list = tuple(grocery_list)# tuples also have len(tuple), min(tuple) and max(tuple)# DICTIONARY or MAP -------------# Made up of values with a unique key for each value# Similar to lists, but you can't join dicts with a +super_villains = {'Fiddler' : 'Isaac Bowin', 'Captain Cold' : 'Leonard Snart', 'Weather Wizard' : 'Mark Mardon', 'Mirror Master' : 'Sam Scudder', 'Pied Piper' : 'Thomas Peterson'}print(super_villains['Captain Cold'])# Delete an entrydel super_villains['Fiddler']print(super_villains)# Replace a valuesuper_villains['Pied Piper'] = 'Hartley Rathaway'# Print the number of items in the dictionaryprint(len(super_villains))# Get the value for the passed keyprint(super_villains.get("Pied Piper"))# Get a list of dictionary keysprint(super_villains.keys())# Get a list of dictionary valuesprint(super_villains.values())# CONDITIONALS -------------age = 30if age >= 21 : print('You are old enough to drive a tractor trailer')elif age >= 16: print('You are old enough to drive a car')else : print('You are not old enough to drive')# You can combine conditions with logical operators# Logical Operators : and, or, notif ((age >= 1) and (age <= 18)): print("You get a birthday party")elif (age == 21) or (age >= 65): print("You get a birthday party")elif not(age == 30): print("You don't get a birthday party")else: print("You get a birthday party yeah")# FOR LOOPS -------------# Allows you to perform an action a set number of times# Range performs the action 10 times 0 - 9for x in range(0, 10): print(x , ' ', end="")print('\n')# You can use for loops to cycle through a listgrocery_list = ['Juice', 'Tomatoes', 'Potatoes', 'Bananas']for y in grocery_list: print(y)# You can also define a list of numbers to cycle throughfor x in [2,4,6,8,10]: print(x)# You can double up for loops to cycle through listsnum_list =[[1,2,3],[10,20,30],[100,200,300]];for x in range(0,3): for y in range(0,3): print(num_list[x][y])# WHILE LOOPS -------------# While loops are used when you don't know ahead of time how many# times you'll have to looprandom_num = random.randrange(0,100)while (random_num != 15): print(random_num) random_num = random.randrange(0,100)# An iterator for a while loop is defined before the loopi = 0;while (i <= 20): if(i%2 == 0): print(i) elif(i == 9): # Forces the loop to end all together break else: # Shorthand for i = i + 1 i += 1 # Skips to the next iteration of the loop continue i += 1# FUNCTIONS -------------# Functions allow you to reuse and write readable code# Type def (define), function name and parameters it receives# return is used to return something to the caller of the functiondef addNumbers(fNum, sNum): sumNum = fNum + sNum return sumNumprint(addNumbers(1, 4))# Can't get the value of rNum because it was created in a function# It is said to be out of scope# print(sumNum)# If you define a variable outside of the function it works every placenewNum = 0;def subNumbers(fNum, sNum): newNum = fNum - sNum return newNumprint(subNumbers(1, 4))# USER INPUT -------------print('What is your name?')# Stores everything typed up until ENTERname = sys.stdin.readline()print('Hello', name)# STRINGS -------------# A string is a series of characters surrounded by ' or "long_string = "I'll catch you if you fall - The Floor"# Retrieve the first 4 charactersprint(long_string[0:4])# Get the last 5 charactersprint(long_string[-5:])# Everything up to the last 5 charactersprint(long_string[:-5])# Concatenate part of a string to anotherprint(long_string[:4] + " be there")# String formattingprint("%c is my %s letter and my number %d number is %.5f" % ('X', 'favorite', 1, .14))# Capitalizes the first letterprint(long_string.capitalize())# Returns the index of the start of the string# case sensitiveprint(long_string.find("Floor"))# Returns true if all characters are letters ' isn't a letterprint(long_string.isalpha())# Returns true if all characters are numbersprint(long_string.isalnum())# Returns the string lengthprint(len(long_string))# Replace the first word with the second (Add a number to replace more)print(long_string.replace("Floor", "Ground"))# Remove white space from front and endprint(long_string.strip())# Split a string into a list based on the delimiter you providequote_list = long_string.split(" ")print(quote_list)# FILE I/O -------------# Overwrite or create a file for writingtest_file = open("test.txt", "wb")# Get the file mode usedprint(test_file.mode)# Get the files nameprint(test_file.name)# Write text to a file with a newlinetest_file.write(bytes("Write me to the file\n", 'UTF-8'))# Close the filetest_file.close()# Opens a file for reading and writingtest_file = open("test.txt", "r+")# Read text from the filetext_in_file = test_file.read()print(text_in_file)# Delete the fileos.remove("test.txt")# CLASSES AND OBJECTS -------------# The concept of OOP allows us to model real world things using code# Every object has attributes (color, height, weight) which are object variables# Every object has abilities (walk, talk, eat) which are object functionsclass Animal: # None signifies the lack of a value # You can make a variable private by starting it with __ __name = None __height = None __weight = None __sound = None # The constructor is called to set up or initialize an object # self allows an object to refer to itself inside of the class def __init__(self, name, height, weight, sound): self.__name = name self.__height = height self.__weight = weight self.__sound = sound def set_name(self, name): self.__name = name def set_height(self, height): self.__height = height def set_weight(self, height): self.__height = height def set_sound(self, sound): self.__sound = sound def get_name(self): return self.__name def get_height(self): return str(self.__height) def get_weight(self): return str(self.__weight) def get_sound(self): return self.__sound def get_type(self): print("Animal") def toString(self): return "{} is {} cm tall and {} kilograms and says {}".format(self.__name, self.__height, self.__weight, self.__sound)# How to create a Animal objectcat = Animal('Whiskers', 33, 10, 'Meow')print(cat.toString())# You can't access this value directly because it is private#print(cat.__name)# INHERITANCE -------------# You can inherit all of the variables and methods from another classclass Dog(Animal): __owner = None def __init__(self, name, height, weight, sound, owner): self.__owner = owner self.__animal_type = None # How to call the super class constructor super(Dog, self).__init__(name, height, weight, sound) def set_owner(self, owner): self.__owner = owner def get_owner(self): return self.__owner def get_type(self): print ("Dog") # We can overwrite functions in the super class def toString(self): return "{} is {} cm tall and {} kilograms and says {}. His owner is {}".format(self.get_name(), self.get_height(), self.get_weight(), self.get_sound(), self.__owner) # You don't have to require attributes to be sent # This allows for method overloading def multiple_sounds(self, how_many=None): if how_many is None: print(self.get_sound) else: print(self.get_sound() * how_many)spot = Dog("Spot", 53, 27, "Ruff", "Derek")print(spot.toString())# Polymorphism allows use to refer to objects as their super class# and the correct functions are called automaticallyclass AnimalTesting: def get_type(self, animal): animal.get_type()test_animals = AnimalTesting()test_animals.get_type(cat)test_animals.get_type(spot)spot.multiple_sounds(4)
Python Challenge
Python Challenge是一个网页版在线闯关游戏,每一关都需编写程序寻找答案以通关,很适合初学者用来学习Python,详情见 Python Challenge闯关游戏指南。
阅读全文
0 0
- PyCharm学习笔记及Python基础语法总结
- Python基础语法学习笔记
- Python学习笔记 基础语法
- Python学习笔记:语法基础
- python基础学习,基础语法总结
- Python基础语法(学习笔记)
- Python学习笔记(一)基础语法
- Python学习笔记(2):语法基础
- Python学习笔记(1):语法基础
- Python学习笔记——语法基础
- Python学习笔记1-基础语法
- Python学习笔记 —— 基础语法
- Python 学习笔记(基础语法)
- Python学习笔记三:基础语法
- python 学习笔记之基础语法
- Python学习笔记(一) 之 基础语法
- 【学习笔记】python的基础语法
- python学习笔记(基础语法)
- java——static为什么不能定义在方法里
- IDEA 提示jar包问题
- 【POJ3683】Priest John's Busiest Day
- redis入门学习总结
- 剑指offer-字符串的排列
- PyCharm学习笔记及Python基础语法总结
- java中类型的两种传值方式,按址传递和按值传递
- ajax实现分页,多条件查询步骤(基于nodejs)
- VMWare虚拟机Bridged类型网卡ping不通的原因和解决办法
- iPhone中无法播放视频--avplayer视频框架
- PS技巧一-----镜头光晕
- uva 11389 贪心
- Tablayout
- yolov2 笔记