Python programming language basics in 10 minutes

Original author: Poromenos' Stuff
  • Transfer
Python Logo

An article was published on Poromenos' Stuff's website , which, in a concise form, talks about the basics of the Python language. I suggest you translate this article. The translation is not literal. I tried to explain in more detail some points that may not be clear.


If you are planning to learn the Python language, but cannot find a suitable guide, then this
article will be very useful to you! In a short time, you can learn the
basics of the Python language. Although this article often relies
on the fact that you already have programming experience, but I hope
this material will be useful even for beginners . Read each paragraph carefully. Due to the
compactness of the material, some topics are considered superficially, but contain all the
necessary material.



Basic properties



Python does not require explicit declaration of variables, it is case-sensitive (var is not equivalent to Var or VAR are three different variables) in an object-oriented language.



Syntax



First, an interesting feature of Python is worth noting. It does not contain operator brackets (begin..end in pascal or {..} in C), instead the blocks are indented : spaces or tabs, and the input to the block from operators is carried out by a colon. Single-line comments begin with the pound sign "#", multi-line comments begin and end with three double quotation marks "" "".
To assign a value to a variable, use the sign "=", and for comparison -
"==". To increase the value of a variable, or add the operator “+ =” is used to the string, and “- =” to decrease it. All these operations can interact with most types, including strings. For example


>>> myvar = 3
>>> myvar + = 2
>>> myvar - = 1
"" "This is a multi-line comment
Strings enclosed in three double quotes are ignored" ""
>>> mystring = "Hello"
>>> mystring + = "world."
>>> print mystring
Hello world.
# The next line swaps the
values ​​of variables. (Just one line!)
>>> myvar, mystring = mystring, myvar

Data structures

Python contains data structures such as lists, tuples, and dictionaries . Lists are like one-dimensional arrays (but you can use a List including lists - a multi-dimensional array), tuples - immutable lists, dictionaries - also lists, but indexes can be of any type, not just numeric. Arrays in Python can contain data of any type, that is, a single array can contain numeric, string and other data types. Arrays start at index 0, and the last element can be obtained at index -1. You can assign functions to variables and use them accordingly.


>>> sample = [1, ["another", "list"], ("a", "tuple")] # The list consists of an integer, another list and a tuple
>>> mylist = ["List item 1" , 2, 3.14] # This list contains a string, integer and fractional number
>>> mylist [0] = “List item 1 again” # Change the first (zero) element of the mylist sheet
>>> mylist [-1] = 3.14 # Change last element of the sheet
>>> mydict = {"Key 1": "Value 1", 2: 3, "pi": 3.14} # Create a dictionary, with numeric and integer indices
>>> mydict ["pi"] = 3.15 # We change the dictionary element under the index "pi".
>>> mytuple = (1, 2, 3) # Define a tuple
>>> myfunction = len #Python thus allows you to declare function synonyms
>>>

You can use part of the array by specifying the first and last index through a colon ":". In this case, you get a part of the array, from the first index to the second, not inclusive. If the first element is not specified, then the count starts from the beginning of the array, and if the last is not specified, then the array is read to the last element. Negative values ​​determine the position of the element from the end. For instance:


>>> mylist = [“List item 1”, 2, 3.14]
>>> print mylist [:] # Read all the elements of the array
['List item 1', 2, 3.1400000000000001]
>>> print mylist [0: 2] # Reads the zero and first element of the array.
['List item 1', 2]
>>> print mylist [-3: -1] # Items are read from zero (-3) to second (-1) (not inclusive)
['List item 1', 2]
> >> print mylist [1:] # Elements are read from the first to the last
[2, 3.14]

Lines

Lines in Python are enclosed in double quotes by double "" "or single" '" . Inside double quotes, there may be single quotes or vice versa. For example, the line“ He said' hello '! ”Will be displayed on the screen as“ He said' hello '! ”. if you need to use a string of several lines, then this line must begin and end with three double quotes "" "" ". You can substitute elements from a tuple or a dictionary into a string template. The percent sign “%” between the string and the tuple replaces the characters “% s” in the string with the tuple element. Dictionaries allow you to insert an element at a given index into a string. To do this, use the construction "% (index) s" in the string. In this case, instead of “% (index) s”, the dictionary value will be substituted under the given index.


>>> print “Name:% s \ nNumber:% s \ nString:% s”% (my class .name, 3, 3 * "-")
Name: Poromenos
Number: 3
String: -  
strString = "" "This the text is located
on several lines »" "
 
>>> print " This% (verb) sa% (noun) s. "% {" noun ":" test "," verb ":" is "}
This is a test.

Operators

The while, if , for statements make up the move statements. There is no analogue of the select statement, so you have to do if . The for statement compares the variable and the list . To get a list of numbers before a number - use the range function () Here is an example using operators


rangelist = range (10) # Get a list of ten digits (0 to 9)
>>> print rangelist
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for number in rangelist: # While the variable number (which increases by one each time) is on the list ...
# Check if the variable
# numbers is included in the tuple of numbers (3, 4, 7, 9)
if number in (3, 4, 7, 9): # If the variable number is part of the tuple (3, 4, 7, 9) ...
# The “ break ” operation provides
# exit from the loop at any time
break
else :
# “ continue ” scrolls through the
# loop. This is not required here, since after this operation
# in any case, the program goes back to processing the
continue
else loop :
# " else " is optional. The condition is satisfied
# if the loop has not been interrupted using " break ".
pass # Do nothing
 
if rangelist [1] == 2:
print “The second item (lists are 0-based) is 2”
elif rangelist [1] == 3:
print “The second item (lists are 0-based) is 3 "
else :
print " Dunno "
 
while rangelist [1] == 1:
pass

Functions

To declare a function is the key word « def » . Function arguments are given in brackets after the function name. You can specify optional arguments by giving them a default value. Functions can return tuples, in which case it is necessary to write the returned values ​​separated by commas. The keyword " lambda " is used to declare elementary functions.


# arg2 and arg3 are optional arguments, take a value declared by default,
# unless you give them a different value when calling the function.
def myfunction (arg1, arg2 = 100, arg3 = "test"):
return arg3, arg2, arg1
# The function is called with the value of the first argument - "Argument 1", the second - by default, and the third - "Named argument".
>>> ret1, ret2, ret3 = myfunction ("Argument 1", arg3 = "Named argument")
# ret1, ret2 and ret3 take the values ​​"Named argument", 100, "Argument 1" respectively
>>> print ret1, ret2 , ret3
Named argument 100 Argument 1
 
# The following entry is equivalent to def f (x):
functionvar = lambda x: x + 1
>>> print functionvar (1)
2

Classes

Python is limited to multiple inheritance in classes. Internal variables and internal class methods begin with two underscores “__” (for example, “__myprivatevar”). We can also assign a value to a class variable from the outside. Example:


class My class :
common = 10
def __init __ (self):
self.myvariable = 3
def myfunction (self, arg1, arg2):
return self.myvariable
 
# Here we declared the class My class . The __init__ function is called automatically when the classes are initialized.
>>> classinstance = My class () # We initialized the class and the myvariable variable acquired the value 3 as declared in the initialization method
>>> classinstance.myfunction (1, 2) # the myfunction method of the My class class returns the value of the myvariable
3
variable # The common variable is declared in all classes
>>> classinstance2 = Myclass ()
>>> classinstance.common
10
>>> classinstance2.common
10
# Therefore, if we change its value in the class My class, the
# changes and its values ​​in objects initialized by the class My class
>>> Myclass.common = 30
> >> classinstance.common
30
>>> classinstance2.common
30
# And here we do not change the class variable. Instead,
# we declare it in the object and assign it a new value
>>> classinstance.common = 10
>>> classinstance.common
10
>>> classinstance2.common
30
>>> Myclass.
# Now changing a class variable will not affect
# variables of objects of this class
>>> classinstance.common
10
>>> classinstance2.common
50
 
# The next class is an inheritor of the My class class
# inheriting its properties and methods, to which the class can
# inherit from several classes , in this case the entry
# is: class Otherclass (Myclass1, Myclass2, MyclassN)
class Otherclass (Myclass):
def __init __ (self, arg1):
self.myvariable = 3
print arg1
 
>>> classinstance = Otherclass ("hello")
hello
>>> classinstance.myfunction (1, 2)
3
# This class does not have test, but we can
# declare such a variable for an object. And
#t this variable will be a member of only class instance.
>>> classinstance.test = 10
>>> classinstance.test
10

Exceptions

Exceptions in Python have a try - except [ except ionname] structure:


def someFunction ():
the try :
# Division by zero causes an error
10/0
The except ZeroDivisionError:
# But the program is not "perform an illegal operation"
# A block handles exceptions corresponding error «ZeroDivisionError»
print «Oops, invalid.»
 
>>> the fn The except ()
Oops, invalid.

Import

External libraries can be connected using the “ import [libname]” procedure , where [libname] is the name of the library to be connected. You can also use the “ from [libname] import [funcname]” command so that you can use the [funcname] function from the [libname] library


import random # Import the library “random”
from time import clock # And at the same time the function “clock” from the library “time”
 
randomint = random.randint (1, 100)
>>> print randomint
64

Work with the file system



Python has many built-in libraries. In this example, we will try to save the list structure in a binary file, read it and save the line in a text file. To transform the data structure, we will use the standard pickle library


import pickle
mylist = ["This", "is", 4, 13327]
# Open the file C: \ binary.dat for writing. The symbol "r"
# prevents the replacement of special characters (such as \ n, \ t, \ b, etc.).
myfile = file (r "C: \ binary.dat", "w")
pickle.dump (mylist, myfile)
myfile.close ()
 
myfile = file (r "C: \ text.txt", "w")
myfile .write ("This is a sample string")
myfile.close ()
 
myfile = file (r "C: \ text.txt")
>>> print myfile.read ()
'This is a sample string'
myfile.close ( )
 
# Open the file for reading
myfile = file (r "C: \ binary.dat")
loadedlist = pickle.load (myfile)
myfile.close ()
>>> printloadedlist
['This', 'is', 4, 13327]

Features

  • Conditions can be combined. 1 <a <3 is satisfied when a is greater than 1 but less than 3.
  • Use the del operation to clear variables or array elements .
  • Python offers great features for working with lists . You can use list structure declaration operators. The for operator allows you to specify list items in a specific sequence, and if allows you to select items by condition.

>>> lst1 = [1, 2, 3]
>>> lst2 = [3, 4, 5]
>>> print [x * y for x in lst1 for y in lst2]
[3, 4, 5, 6, 8, 10, 9, 12, 15]
>>> print [x for x in lst1 if 4> x> 1]
[2, 3]
# The “any” operator returns true if at
least # one of the conditions in him, performed.
>>> any (i% 3 for i in [3, 3, 4, 4, 3])
True
# The following procedure counts the number of
# matching items in the list
>>> sum (1 for i in [3, 3, 4, 4,

>>> del lst1 [0]
>>> print lst1
[2, 3]
>>> del lst1

  • Global variables are declared outside functions and can be read without any declarations. But if you need to change the value of a global variable from a function, then you need to declare it at the beginning of the function with the keyword “ global ”, if you do not, then Python will declare a variable available only for this function.

number = 5
 
def myfunc():
# Выводит 5
print number
 
def anotherfunc():
# Это вызывает исключение, поскольку глобальная апеременная
# не была вызванна из функции. Python в этом случае создает
# одноименную переменную внутри этой функции и доступную
# только для операторов этой функции.
print number
number = 3
 
def yetanotherfunc():
global number
# И только из этой функции значение переменной изменяется.
number = 3

Эпилог

Разумеется в этой статье не описываются все возможности Python. Я надеюсь что эта статья поможет вам, если вы захотите и в дальнейшем изучать этот язык программирования.



Преимущества Python

  • Скорость выполнения программ написанных на Python очень высока. Это связанно с тем, что основные библиотеки Python
    написаны на C++ и выполнение задач занимает меньше времени, чем на других языках высокого уровня.
  • В связи с этим вы можете писать свои собственные модули для Python на C или C++
  • В стандартныx библиотеках Python вы можете найти средства для работы с электронной почтой, протоколами
    Интернета, FTP, HTTP, базами данных, и пр.
  • Скрипты, написанные при помощи Python выполняются на большинстве современных ОС. Такая переносимость обеспечивает Python применение в самых различных областях.
  • Python подходит для любых решений в области программирования, будь то офисные программы, вэб-приложения, GUI-приложения и т.д.
  • Thousands of enthusiasts from around the world have worked on Python development. By supporting modern technologies in standard libraries, we may be obligated to the fact that Python was open to all comers.


Also popular now: