Python-это язык на высоком уровне, интерпретируемый и общего назначения с расслабленным синтаксисом, под влиянием английского языка и математики.
Python используется практически в каждой отрасли и научных областях. Наиболее популярными вариантами использования являются: наука о данных. • Машинное обучение. • Веб-разработка. • Компьютерное зрение и обработка изображений. • Разработка игры. • Медицина и фармакология. • Биология и биоинформатика. • Нейробиология и психология. • Робототехника • Разработка графического интерфейса
Эта статья охватывает основные правила синтаксиса и языка, которым следует следовать при написании программы Python.
КОММЕНТАРИИ
- Вы используете хэш-символ для комментариев на одну строку и однократные или двойные цитаты для многострочных комментариев
#This is a comment ''' This is a multiline comment '''
Переменные
- Имена переменных чувствительны (имя и имя разные переменные)
- Должен начать с буквы или подчеркивания
- Могут иметь цифры, но не должны начинаться с одного
- Python слабо используется (вы не указываете тип при объявлении переменной.
x = 1 # int y = 2.5 # float name = 'John' # str is_cool = True #boolean x, y, name, is_cool = (3, 7.5, 'Anna', True) #multiple assignment # Casting x = str(x) #int casted to string y = int(y) #float casted to integer Print() statement: This outputs the result of an expression in the console. print(type(y), y) #prints int, 2 to the console
Функции
- В Python функции определяются с помощью ключевого слова DEF.
- Смешание используется вместо вьющихся скоб.
- Толстая кишка помещается после параметров.
- Нет полуколонов.
def getSum(num1, num2): total = num1 + num2 return total print(getSum(10, 3)) #prints 13 getSum = lambda num1, num2: num1 + num2 #lamba functions are very similar to arrow fns in JS
Строки
- Строки в питоне окружены одиночными или двойными кавычками
- F-стрит позволяет вам легко объединить два разных типа без необходимости отбрасывать его в первую очередь
name = 'Kingsley' age = 21 # Concatenate print('Hello, my name is ' + name + ' and I am ' + str(age)) #you must cast age int into a string # F-Strings (3.6+) print(f'Hello, my name is {name} and I am {age}') #with this you don't need str() helper #STRING METHODS s = 'helloworld' # Capitalize string s.capitalize() # Make all uppercase s.upper() # Make all lower s.lower() # Swap case s.swapcase() # Get length len(s) # Replace s.replace('world', 'everyone') # Count sub = 'h' s.count(sub) # Starts with s.startswith('hello') # Ends with s.endswith('d') # Split into a list s.split() # Find position s.find('r') # Is all alphanumeric s.isalnum() # Is all alphabetic s.isalpha() # Is all numeric s.isnumeric()
Списки
- Это коллекции данных, которые упорядочены, изменяются и могут иметь дублирующие члены
numbers = [1, 2, 3, 4, 5] fruits_list = ['Apples', 'Oranges', 'Grapes', 'Pears'] # Get a value print(fruits[1]) #METHODS # Append to list fruits.append('Mangos') # Remove from list fruits.remove('Grapes') # Insert into position fruits.insert(2, 'Strawberries') # Change value fruits[0] = 'Blueberries' # Remove with pop fruits.pop(2) # Reverse list fruits.reverse() # Sort list fruits.sort() # Reverse sort fruits.sort(reverse=True)
Кортежи
- Это коллекции данных, которые упорядочены, неизменные и могут иметь дублирующие члены.
# Create tuple fruits_tuple = ('Apples', 'Oranges', 'Grapes') # Get value print(fruits[1]) # unchangeable values fruits[0] = 'Pears' # Deletes tuple del fruits2 ## SETS - These are data collections which are unordered and doesn't allow duplicate members fruits_set = {'Apples', 'Oranges', 'Mango'} # Add to set fruits_set.add('Grape') # Remove from set fruits_set.remove('Grape') # Add duplicate fruits_set.add('Apples') # Clear set fruits_set.clear() # Delete del fruits_set # Check if in set print('Apples' in fruits_set)
ТОЛКОВЫЙ СЛОВАРЬ
- Это коллекции данных, которые неупопорядочен, изменяемые и индексируемые. Аналогичный синтаксис для объектов в JavaScript.
# Get value print(person['first_name']) print(person.get('last_name')) # Get value print(person['first_name']) print(person.get('last_name')) # Add key/value person['phone'] = '111-222-3333' # Get dict keys print(person.keys()) # Get dict items print(person.items()) # Copy dict, like spread in javascript person2 = person.copy() person2['city'] = 'Boston' #remove a person del(person['age']) person.pop('phone') # Clear person.clear() # Get length print(len(person2)) # List of dict, like array of objects in javascript people = [ {'name': 'Martha', 'age': 30}, {'name': 'Kevin', 'age': 25} ]
Петли
- Петли – это механизмы для итерации над списком элементов, выполняя постоянное действие для каждого из них, студенты = [«Эмма», «Сэнди», «Джеймс», «Итан»]
# Simple for loop for pupil in students: print(f'Current Pupil: {pupil}') # Break for pupil in students: if person == 'Sara': break print(f'Current Pupil: {pupil}') # Continue for pupil in students: if person == 'Sara': continue print(f'Current Pupil: {pupil}') # range for i in range(len(students)): print(students[i]) # prints a pupil and increments to the next # While loops execute a set of statements as long as a condition is true. count = 0 while count < 10: print(f'Count: {count}') count += 1
Условные
- Если/else выражения используются для выполнения набора инструкций на основе того, является ли оператор истинным или ложным.
x = 15 y = 14 if x > y: print(f'{x} is greater than {y}') #if/else if x > y: print(f'{x} is greater than {y}') else: print(f'{y} is greater than {x}') # elif if x > y: print(f'{x} is greater than {y}') elif x == y: print(f'{x} is equal to {y}') else: print(f'{y} is greater than {x}') # Logical operators (and, or, not) - Used to combine conditional statements # and if x > 4 and x <= 12: print(f'{x} is greater than 2 and less than or equal to 10') # or if x > 4 or x <= 12: print(f'{x} is greater than 2 or less than or equal to 10') # not if not(x == y): print(f'{x} is not equal to {y}')
Модули
- Модуль – это файл, содержащий набор функций для включения в ваше приложение. Существуют основные модули Python, которые являются частью среды Python, модули, которые вы можете установить, используя диспетчер пакетов PIP, а также пользовательские модули
# Core modules import datetime from datetime import date import time from time import time # Pip module from camelcase import CamelCase # Import custom module import validator from validator import validate_email # today = datetime.date.today() today = date.today() timestamp = time() c = CamelCase() # print(c.hump('hello there world')) email = 'test#test.com' if validate_email(email): print('Email is valid') else: print('Email is bad')
Классы
Класс похож на план создания объектов. Объект имеет свойства и методы (функции), связанные с ним.
- Как и в случае с функциями, все поля внутри класса должны быть отступок, а толще нужно разместить после названия класса
- Используйте ключевое слово DEF, чтобы определить метод
- Самостоятельное ключевое слово используется для обозначения текущего класса, как это ключевое слово в JavaScript
class User: # Constructor def __init__(self, name, email, age): self.name = name self.email = email self.age = age # Adding Encapsulation of variables... Encapsulation is the concept of making the variables non-accessible or accessible upto some extent from the child classes self._private = 1000 # Encapsulated variables are declares with '_' in the constructor. def greeting(self): return f'My name is {self.name} and I am {self.age}' def has_birthday(self): self.age += 1 #function for encap variable def print_encap(self): print(self._private) # Extend class class Customer(User): # Constructor def __init__(self, name, email, age): User.__init__(self, name, email, age) #Called proper parent class constructor to make this as proper child inehriting all methods. self.name = name self.email = email self.age = age self.balance = 0 def set_balance(self, balance): self.balance = balance def greeting(self): return f'My name is {self.name} and I am {self.age} and my balance is {self.balance}' # Init user object brad = User('Brad Traversy', 'brad@gmail.com', 37) # Init customer object janet = Customer('Janet Johnson', 'janet@yahoo.com', 25) janet.set_balance(500) print(janet.greeting()) brad.has_birthday() print(brad.greeting()) #Encapsulation --> brad.print_encap() brad._private = 800 #Changing for brad brad.print_encap() # Method inherited from parent janet.print_encap() #Changing the variable for brad doesn't affect janets variable --> Encapsulation janet._private = 600 janet.print_encap() #Similary changing janet's doesn't affect brad's variable. brad.print_encap() class User: # Constructor def __init__(self, name, email, age): self.name = name self.email = email self.age = age def greeting(self): return f'My name is {self.name} and I am {self.age}' def has_birthday(self): self.age += 1 #function for encap variable def print_encap(self): print(self._private) # Extend class class Customer(User): # Constructor def __init__(self, name, email, age): User.__init__(self, name, email, age) #Called proper parent class constructor to make this as proper child inheriting all methods. self.name = name self.email = email self.age = age self.balance = 0 def set_balance(self, balance): self.balance = balance def greeting(self): return f'My name is {self.name} and I am {self.age} and my balance is {self.balance}' # Initialize user object Kingsley = User('Kingsley Ubah', 'ubah@gmail.com', 21) # Init customer object cara = Customer('Cara Mason', 'cara@yahoo.com', 25) cara.set_balance(500) print(cara.greeting()) kingsley.has_birthday() print(kingsley.greeting()) #Encapsulation --> kingsley.print_encap() kingsley._private = 800 #Changing for kingsley kingsley.print_encap() # Method inherited from parent cara.print_encap() #Changing the variable for kingsley doesn't affect cara's variable --> Encapsulation cara._private = 600 cara.print_encap() #Similary changing cara's doesn't affect kingsley's variable. cara.print_encap()
Файлы
- Python имеет функции для создания, чтения, обновления и удаления файлов.
# Open a file, file is stored in same directory myFile = open('myfile.txt', 'w') # Get some info print('Name: ', myFile.name) #gets the file name print('Is Closed : ', myFile.closed) #returns a Boolean of either true or false print('Opening Mode: ', myFile.mode) #outputs the mode # Write to file myFile.write('I love Python') myFile.write(' and JavaScript') myFile.close() # closes file # Append to file myFile = open('myfile.txt', 'a') myFile.write(' I also like PHP') myFile.close() # Read from file myFile = open('myfile.txt', 'r+') text = myFile.read(100) #reads the first 100 characters from file print(text)
Json
- JSON обычно используется с API данных. Здесь, как мы можем разобрать JSON в словарь Python
# Import built-in json object import json # User JSON userJSON = '{"first_name": "Kingsley", "last_name": "Ubah", "age": 21}' # Parse to dict user = json.loads(userJSON) print(user) print(user['first_name']) car = {'make': 'Ford', 'model': 'Mustang', 'year': 1970} # Parse to JSON carJSON = json.dumps(car) print(carJSON)
С этим мы подошли к концу этого урока. Если вам понравилась статья и не возражает, чтобы увидеть больше этого, пожалуйста, поделитесь и следуйте. Кроме того, вы можете связаться со мной на Twitter Анкет
P/S. : Если вы ищете кого-то, кто может создать верхний контент для вашего блога или веб-сайта, я доступен. Пожалуйста, отправляйтесь на мой концерт на Fiverr и сделайте заказ или дотянитесь со мной на Twitter для чата.
Оригинал: “https://dev.to/ubahthebuilder/learn-all-about-python-s-syntax-in-6-minutes-fgb”