⬆️ ⬇️

Basics of the Python programming language in 10 minutes

Python Logo



Poromenos' Stuff was

published an article in which, in concise form,

talk about the basics of the Python language. I offer you a translation of this article. The translation is not literal. I have tried to explain in more detail some points that might not be clear.

If you are going to learn Python, but cannot find a suitable manual, then this

The article is very useful to you! In a short time, you will be able to meet

basics of python language. Although this article often relies

that you already have programming experience, but, I hope, even for beginners

This material will be useful. Read each paragraph carefully. In connection with

by the compactness of the material, some topics are considered superficially, but contain

required metrial.





Basic properties





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



')

Syntax





Firstly, an interesting feature of Python is worth noting. It does not contain operator brackets (begin..end in pascal or {..} in C), instead, blocks are indented : spaces or tabs, and entry into the block from operators is done with a colon. Single-line comments begin with a pound “#” sign, multi-line comments begin and end with three double quotes “" "" ".

To assign a value to a variable, the symbol “=” is used, and for comparison -

"==" To increase the value of a variable, or add to the string, use the “+ =” operator, and to decrease - “- =”. 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 changes

variable values ​​in places. (Just one line!)

>>> myvar, mystring = mystring, myvar


Data structures

Python contains such data structures as lists (lists), tuples (tuples) and dictionaries (dictionaries ). Lists are similar to one-dimensional arrays (but you can use a List that includes lists — a multidimensional array), tuples are immutable lists, dictionaries are also lists, but indices can be of any type, not just numeric. "Arrays" in Python can contain data of any type, that is, in the same array can be numeric, string and other data types. Arrays start with index 0, and the last element can be obtained by 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 the string, integer and fractional number

>>> mylist [ 0 ] = "List item 1 again" # Change the first (zero) element of the sheet mylist

>>> mylist [- 1 ] = 3 . 14 # Change the 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 # Change dictionary element with index “pi”.

>>> mytuple = ( 1 , 2 , 3 ) # Set a tuple

>>> myfunction = len #Python thus allows you to declare synonyms of the function

>>> print myfunction ( list )

3


You can use part of an array by specifying the first and last index with a colon ":". In this case, you will get a portion of the array, from the first index to the second, not inclusive. If the first element is not specified, then the counting 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 example:



>>> mylist = [ "List item 1" , 2 , 3 . 14 ]

>>> print mylist [:] # All elements of the array are read.

[ 'List item 1' , 2 , 3 . 1400000000000001 ]

>>> print mylist [ 0 : 2 ] # The zero and first element of the array are read.

[ 'List item 1' , 2 ]

>>> print mylist [- 3 : - 1 ] # Elements from zero (-3) to second (-1) are read (inclusive)

[ 'List item 1' , 2 ]

>>> print mylist [ 1 :] # Read items from first to last

[ 2 , 3 . 14 ]


Strings

Python strings are separated by double quotation marks or single quotes . Single quotes may appear inside double quotes or vice versa. For example, the string “He said hello!” Will be displayed as “He said hello!”. you need to use a line of several lines, then this line should be started and ended with three double quotes “" "" ". You can insert elements from a tuple or dictionary into a string template. The percent sign “%” between the line and the tuple replaces the characters “% s” in the string with a tuple element. Dictionaries allow you to insert an element at a given index into a string. For this purpose it is necessary to use the construction “% (index) s” in the string. In this case, the value of the dictionary under the specified index will be substituted instead of “% (index) s”.



>>> print "Name:% s \ nNumber:% s \ nString:% s" % (my class .name, 3 , 3 * "-" )

Name: Poromenos

Number: 3

String: -

strString = "" "This text is located

on several lines "" "



>>> print "This% (verb) sa% (noun) s." % { "noun" : "test" , "verb" : "is" }

This is a test.


Operators

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



rangelist = range ( 10 ) # Get a list of ten digits (from 0 to 9)

>>> print rangelist

[ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ]

for number in rangelist: # As long as the variable number (which is incremented each time) is on the list ...

# Check if variable is included

# numbers per tuple of numbers ( 3 , 4 , 7 , 9 )

if number in ( 3 , 4 , 7 , 9 ): # If the variable number enters a tuple (3, 4, 7, 9) ...

# Operation " break " provides

# exit from loop at any time

break

else :

# “ Continue ” scrolls

# cycle. Here it is not required, since after this operation

# in any case, the program goes back to loop processing

continue

else :

# “ Else ” is optional. The condition is met

# if the loop was not interrupted with a 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 keyword " def " . Function arguments are given in brackets after the function name. You can set optional arguments by assigning 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 - optional arguments, take the 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): return x + 1

functionvar = lambda x: x + 1

>>> print functionvar ( 1 )

2


Classes

Python is limited to multiple inheritance in classes. Internal variables and internal methods of classes 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 classes are initialized.

>>> classinstance = My class () # We initialized the class and the variable myvariable acquired the value 3 as stated in the initialization method

>>> classinstance.myfunction ( 1 , 2 ) # The myfunction method of the class My class returns the value of the variable myvariable

3

# Common variable declared in all classes

>>> classinstance2 = My class ()

>>> classinstance.common

ten

>>> classinstance2.common

ten

# Therefore, if we change its value in the class My class will change

# and its values ​​in objects initialized by the class My class

>>> Myclass.common = 30

>>> classinstance.common

thirty

>>> classinstance2.common

thirty

# And here we do not change the class variable. Instead of this

# we declare it in the object and assign a new value to it

>>> classinstance.common = 10

>>> classinstance.common

ten

>>> classinstance2.common

thirty

>>> Myclass.common = 50

# Now changing the class variable will not affect

# of variable objects of this class

>>> classinstance.common

ten

>>> classinstance2.common

50



# The following class is a successor to the class My class

# inheriting its properties and methods, to the same class can

# inherit from several classes, in this case the record

# such: 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 has no test, but we can

# declare such a variable for the object. And

The # this variable will be a member of class instance only.

>>> classinstance.test = 10

>>> classinstance.test

ten


Exceptions

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



def somefunction ():

try :

# Dividing by zero causes an error

10/0

except ZeroDivisionError :

# But the program is not "Performs an illegal operation"

# A handles an exception block corresponding to the “ZeroDivisionError” error

print "Oops, invalid."



>>> fn except ()

Oops, invalid.


Import

External libraries can be connected using the “ import [libname]” procedure, where [libname] is the name of the connected library. 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 “random” library

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 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 convert the data structure, we will use the standard library "pickle"



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 ()

>>> print loadedlist

[ 'This' , 'is' , 4 , 13327 ]


Features



>>> 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

# one of the conditions included in it is satisfied.

>>> any (i% 3 for i in [ 3 , 3 , 4 , 4 , 3 ])

True

# The following procedure counts the number.

# matching items in the list

>>> sum ( 1 for i in [ 3 , 3 , 4 , 4 , 3 ] if i == 3 )

3

>>> del lst1 [ 0 ]

>>> print lst1

[ 2 , 3 ]

>>> del lst1




number = 5



def myfunc ():

# Displays 5

print number



def anotherfunc ():

# This causes an exception because the global variable.

# was not called from a function. Python in this case creates

# variable of the same name inside this function and accessible

# only for operators of this function.

print number

number = 3



def yetanotherfunc ():

global number

# And only from this function the variable value changes.

number = 3


Epilogue

Of course, this article does not describe all the features of Python. I hope that this article will help you if you want to continue to learn this programming language.





Python Benefits

Source: https://habr.com/ru/post/31180/



All Articles