Python nima
The built-in function len() also applies to lists:
3. An Informal Introduction to Python¶
In the following examples, input and output are distinguished by the presence or absence of prompts ( >>> and … ): to repeat the example, you must type everything after the prompt, when the prompt appears; lines that do not begin with a prompt are output from the interpreter. Note that a secondary prompt on a line by itself in an example means you must type a blank line; this is used to end a multi-line command.
You can toggle the display of prompts and output by clicking on >>> in the upper-right corner of an example box. If you hide the prompts and output for an example, then you can easily copy and paste the input lines into your interpreter.
Many of the examples in this manual, even those entered at the interactive prompt, include comments. Comments in Python start with the hash character, # , and extend to the end of the physical line. A comment may appear at the start of a line or following whitespace or code, but not within a string literal. A hash character within a string literal is just a hash character. Since comments are to clarify code and are not interpreted by Python, they may be omitted when typing in examples.
# this is the first comment spam = 1 # and this is the second comment # . and now a third! text = "# This is not a comment because it's inside quotes."
3.1. Using Python as a Calculator¶
Let’s try some simple Python commands. Start the interpreter and wait for the primary prompt, >>> . (It shouldn’t take long.)
3.1.1. Numbers¶
The interpreter acts as a simple calculator: you can type an expression at it and it will write the value. Expression syntax is straightforward: the operators + , – , * and / work just like in most other languages (for example, Pascal or C); parentheses ( () ) can be used for grouping. For example:
>>> 2 + 2 4 >>> 50 - 5*6 20 >>> (50 - 5*6) / 4 5.0 >>> 8 / 5 # division always returns a floating point number 1.6
The integer numbers (e.g. 2 , 4 , 20 ) have type int , the ones with a fractional part (e.g. 5.0 , 1.6 ) have type float . We will see more about numeric types later in the tutorial.
Division ( / ) always returns a float. To do floor division and get an integer result you can use the // operator; to calculate the remainder you can use % :
>>> 17 / 3 # classic division returns a float 5.666666666666667 >>> >>> 17 // 3 # floor division discards the fractional part 5 >>> 17 % 3 # the % operator returns the remainder of the division 2 >>> 5 * 3 + 2 # floored quotient * divisor + remainder 17
With Python, it is possible to use the ** operator to calculate powers 1:
>>> 5 ** 2 # 5 squared 25 >>> 2 ** 7 # 2 to the power of 7 128
The equal sign ( = ) is used to assign a value to a variable. Afterwards, no result is displayed before the next interactive prompt:
>>> width = 20 >>> height = 5 * 9 >>> width * height 900
If a variable is not “defined” (assigned a value), trying to use it will give you an error:
>>> n # try to access an undefined variable Traceback (most recent call last): File "", line 1, in NameError: name 'n' is not defined
There is full support for floating point; operators with mixed type operands convert the integer operand to floating point:
>>> 4 * 3.75 - 1 14.0
In interactive mode, the last printed expression is assigned to the variable _ . This means that when you are using Python as a desk calculator, it is somewhat easier to continue calculations, for example:
>>> tax = 12.5 / 100 >>> price = 100.50 >>> price * tax 12.5625 >>> price + _ 113.0625 >>> round(_, 2) 113.06
This variable should be treated as read-only by the user. Don’t explicitly assign a value to it — you would create an independent local variable with the same name masking the built-in variable with its magic behavior.
In addition to int and float , Python supports other types of numbers, such as Decimal and Fraction . Python also has built-in support for complex numbers , and uses the j or J suffix to indicate the imaginary part (e.g. 3+5j ).
3.1.2. Strings¶
Besides numbers, Python can also manipulate strings, which can be expressed in several ways. They can be enclosed in single quotes ( ‘. ‘ ) or double quotes ( “. ” ) with the same result 2. \ can be used to escape quotes:
>>> 'spam eggs' # single quotes 'spam eggs' >>> 'doesn\'t' # use \' to escape the single quote. "doesn't" >>> "doesn't" # . or use double quotes instead "doesn't" >>> '"Yes," they said.' '"Yes," they said.' >>> "\"Yes,\" they said." '"Yes," they said.' >>> '"Isn\'t," they said.' '"Isn\'t," they said.'
In the interactive interpreter, the output string is enclosed in quotes and special characters are escaped with backslashes. While this might sometimes look different from the input (the enclosing quotes could change), the two strings are equivalent. The string is enclosed in double quotes if the string contains a single quote and no double quotes, otherwise it is enclosed in single quotes. The print() function produces a more readable output, by omitting the enclosing quotes and by printing escaped and special characters:
>>> '"Isn\'t," they said.' '"Isn\'t," they said.' >>> print('"Isn\'t," they said.') "Isn't," they said. >>> s = 'First line.\nSecond line.' # \n means newline >>> s # without print(), \n is included in the output 'First line.\nSecond line.' >>> print(s) # with print(), \n produces a new line First line. Second line.
If you don’t want characters prefaced by \ to be interpreted as special characters, you can use raw strings by adding an r before the first quote:
>>> print('C:\some\name') # here \n means newline! C:\some ame >>> print(r'C:\some\name') # note the r before the quote C:\some\name
There is one subtle aspect to raw strings: a raw string may not end in an odd number of \ characters; see the FAQ entry for more information and workarounds.
String literals can span multiple lines. One way is using triple-quotes: “””. “”” or ”’. ”’ . End of lines are automatically included in the string, but it’s possible to prevent this by adding a \ at the end of the line. The following example:
print("""\ Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to """)
produces the following output (note that the initial newline is not included):
Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to
Strings can be concatenated (glued together) with the + operator, and repeated with * :
>>> # 3 times 'un', followed by 'ium' >>> 3 * 'un' + 'ium' 'unununium'
Two or more string literals (i.e. the ones enclosed between quotes) next to each other are automatically concatenated.
>>> 'Py' 'thon' 'Python'
This feature is particularly useful when you want to break long strings:
>>> text = ('Put several strings within parentheses ' . 'to have them joined together.') >>> text 'Put several strings within parentheses to have them joined together.'
This only works with two literals though, not with variables or expressions:
>>> prefix = 'Py' >>> prefix 'thon' # can't concatenate a variable and a string literal File "", line 1 prefix 'thon' ^^^^^^ SyntaxError: invalid syntax >>> ('un' * 3) 'ium' File "", line 1 ('un' * 3) 'ium' ^^^^^ SyntaxError: invalid syntax
If you want to concatenate variables or a variable and a literal, use + :
>>> prefix + 'thon' 'Python'
Strings can be indexed (subscripted), with the first character having index 0. There is no separate character type; a character is simply a string of size one:
>>> word = 'Python' >>> word[0] # character in position 0 'P' >>> word[5] # character in position 5 'n'
Indices may also be negative numbers, to start counting from the right:
>>> word[-1] # last character 'n' >>> word[-2] # second-last character 'o' >>> word[-6] 'P'
Note that since -0 is the same as 0, negative indices start from -1.
In addition to indexing, slicing is also supported. While indexing is used to obtain individual characters, slicing allows you to obtain substring:
>>> word[0:2] # characters from position 0 (included) to 2 (excluded) 'Py' >>> word[2:5] # characters from position 2 (included) to 5 (excluded) 'tho'
Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.
>>> word[:2] # character from the beginning to position 2 (excluded) 'Py' >>> word[4:] # characters from position 4 (included) to the end 'on' >>> word[-2:] # characters from the second-last (included) to the end 'on'
Note how the start is always included, and the end always excluded. This makes sure that s[:i] + s[i:] is always equal to s :
>>> word[:2] + word[2:] 'Python' >>> word[:4] + word[4:] 'Python'
One way to remember how slices work is to think of the indices as pointing between characters, with the left edge of the first character numbered 0. Then the right edge of the last character of a string of n characters has index n, for example:
+---+---+---+---+---+---+ | P | y | t | h | o | n | +---+---+---+---+---+---+ 0 1 2 3 4 5 6 -6 -5 -4 -3 -2 -1
The first row of numbers gives the position of the indices 0…6 in the string; the second row gives the corresponding negative indices. The slice from i to j consists of all characters between the edges labeled i and j, respectively.
For non-negative indices, the length of a slice is the difference of the indices, if both are within bounds. For example, the length of word[1:3] is 2.
Attempting to use an index that is too large will result in an error:
>>> word[42] # the word only has 6 characters Traceback (most recent call last): File "", line 1, in IndexError: string index out of range
However, out of range slice indexes are handled gracefully when used for slicing:
>>> word[4:42] 'on' >>> word[42:] ''
Python strings cannot be changed — they are immutable . Therefore, assigning to an indexed position in the string results in an error:
>>> word[0] = 'J' Traceback (most recent call last): File "", line 1, in TypeError: 'str' object does not support item assignment >>> word[2:] = 'py' Traceback (most recent call last): File "", line 1, in TypeError: 'str' object does not support item assignment
If you need a different string, you should create a new one:
>>> 'J' + word[1:] 'Jython' >>> word[:2] + 'py' 'Pypy'
The built-in function len() returns the length of a string:
>>> s = 'supercalifragilisticexpialidocious' >>> len(s) 34
Strings are examples of sequence types, and support the common operations supported by such types.
Strings support a large number of methods for basic transformations and searching.
String literals that have embedded expressions.
Information about string formatting with str.format() .
The old formatting operations invoked when strings are the left operand of the % operator are described in more detail here.
3.1.3. Lists¶
Python knows a number of compound data types, used to group together other values. The most versatile is the list, which can be written as a list of comma-separated values (items) between square brackets. Lists might contain items of different types, but usually the items all have the same type.
>>> squares = [1, 4, 9, 16, 25] >>> squares [1, 4, 9, 16, 25]
Like strings (and all other built-in sequence types), lists can be indexed and sliced:
>>> squares[0] # indexing returns the item 1 >>> squares[-1] 25 >>> squares[-3:] # slicing returns a new list [9, 16, 25]
All slice operations return a new list containing the requested elements. This means that the following slice returns a shallow copy of the list:
>>> squares[:] [1, 4, 9, 16, 25]
Lists also support operations like concatenation:
>>> squares + [36, 49, 64, 81, 100] [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Unlike strings, which are immutable , lists are a mutable type, i.e. it is possible to change their content:
>>> cubes = [1, 8, 27, 65, 125] # something's wrong here >>> 4 ** 3 # the cube of 4 is 64, not 65! 64 >>> cubes[3] = 64 # replace the wrong value >>> cubes [1, 8, 27, 64, 125]
You can also add new items at the end of the list, by using the append() method (we will see more about methods later):
>>> cubes.append(216) # add the cube of 6 >>> cubes.append(7 ** 3) # and the cube of 7 >>> cubes [1, 8, 27, 64, 125, 216, 343]
Assignment to slices is also possible, and this can even change the size of the list or clear it entirely:
>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] >>> letters ['a', 'b', 'c', 'd', 'e', 'f', 'g'] >>> # replace some values >>> letters[2:5] = ['C', 'D', 'E'] >>> letters ['a', 'b', 'C', 'D', 'E', 'f', 'g'] >>> # now remove them >>> letters[2:5] = [] >>> letters ['a', 'b', 'f', 'g'] >>> # clear the list by replacing all the elements with an empty list >>> letters[:] = [] >>> letters []
The built-in function len() also applies to lists:
>>> letters = ['a', 'b', 'c', 'd'] >>> len(letters) 4
It is possible to nest lists (create lists containing other lists), for example:
>>> a = ['a', 'b', 'c'] >>> n = [1, 2, 3] >>> x = [a, n] >>> x [['a', 'b', 'c'], [1, 2, 3]] >>> x[0] ['a', 'b', 'c'] >>> x[0][1] 'b'
3.2. First Steps Towards Programming¶
Of course, we can use Python for more complicated tasks than adding two and two together. For instance, we can write an initial sub-sequence of the Fibonacci series as follows:
>>> # Fibonacci series: . # the sum of two elements defines the next . a, b = 0, 1 >>> while a 10: . print(a) . a, b = b, a+b . 0 1 1 2 3 5 8
This example introduces several new features.
- The first line contains a multiple assignment: the variables a and b simultaneously get the new values 0 and 1. On the last line this is used again, demonstrating that the expressions on the right-hand side are all evaluated first before any of the assignments take place. The right-hand side expressions are evaluated from the left to the right.
- The while loop executes as long as the condition (here: a < 10 ) remains true. In Python, like in C, any non-zero integer value is true; zero is false. The condition may also be a string or list value, in fact any sequence; anything with a non-zero length is true, empty sequences are false. The test used in the example is a simple comparison. The standard comparison operators are written the same as in C: < (less than), >(greater than), == (equal to), = (greater than or equal to) and != (not equal to).
- The body of the loop is indented: indentation is Python’s way of grouping statements. At the interactive prompt, you have to type a tab or space(s) for each indented line. In practice you will prepare more complicated input for Python with a text editor; all decent text editors have an auto-indent facility. When a compound statement is entered interactively, it must be followed by a blank line to indicate completion (since the parser cannot guess when you have typed the last line). Note that each line within a basic block must be indented by the same amount.
- The print() function writes the value of the argument(s) it is given. It differs from just writing the expression you want to write (as we did earlier in the calculator examples) in the way it handles multiple arguments, floating point quantities, and strings. Strings are printed without quotes, and a space is inserted between items, so you can format things nicely, like this:
>>> i = 256*256 >>> print('The value of i is', i) The value of i is 65536
The keyword argument end can be used to avoid the newline after the output, or end the output with a different string:
>>> a, b = 0, 1 >>> while a 1000: . print(a, end=',') . a, b = b, a+b . 0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,
Since ** has higher precedence than – , -3**2 will be interpreted as -(3**2) and thus result in -9 . To avoid this and get 9 , you can use (-3)**2 .
Unlike other languages, special characters such as \n have the same meaning with both single ( ‘. ‘ ) and double ( “. ” ) quotes. The only difference between the two is that within single quotes you don’t need to escape ” (but you have to escape \’ ) and vice versa.
Table of Contents
- 3. An Informal Introduction to Python
- 3.1. Using Python as a Calculator
- 3.1.1. Numbers
- 3.1.2. Strings
- 3.1.3. Lists
Python nima?
Python dasturlash tili erkin va mavjud bo’lgan muammolarni echishda kompyuter muammolarini deyarli osonlashtiradi. Kod bir marta yozilishi va dasturni o’zgartirishga hojat qoldirmasdan deyarli barcha kompyuterlarda ishlaydi.
02 of 06
Python qanday ishlatilgan
Google / cc
Python har qanday zamonaviy kompyuter operatsion tizimida ishlatilishi mumkin bo’lgan umumiy dasturlash tilidir. Matn, raqamlar, tasvirlar, ilmiy ma’lumotlar va kompyuterda saqlay oladigan boshqa narsalarni qayta ishlash uchun foydalanish mumkin. U har kuni Google qidiruv tizimining operatsiyalarida, video almashish veb-sayti YouTube, NASA va Nyu-York fond birjalarida qo’llaniladi. Bular Python biznes, hukumat va notijorat tashkilotlarining muvaffaqiyatlarida muhim rol o’ynaydigan joylardan bir nechtasi; ko’plab boshqalar bor.
Python tarjima qilingan tildir . Bu shuni anglatadiki, u dasturni ishga tushirishdan oldin, lekin ish vaqtida kompyuter o’qiladigan kodga aylantirilmaydi. Ilgari tilning bunday turi skript tiliga aylandi, uni ishlatish juda ahamiyatsiz vazifalar edi. Biroq, Python kabi dasturiy tillari bu nomenklaturadagi o’zgarishni majbur qildi. Keyinchalik, katta ilovalar, deyarli faqat Python’da yoziladi. Pythonni qo’llashning ayrim usullari quyidagilardan iborat:
- Veb dasturlari uchun CGI dasturlash
- RSS Reader yaratish
- MySQL-dan o’qish va Yozish
- PostgreSQL-dan o’qish va Yozish
- HTMLda kalendarlarni yaratish
- Fayllar bilan ishlash
03 ning 06
Python Perl bilan qanday solishtiriladi?
Rahmatli ko’z fondi / Qahramonlikdagi tasvirlar / Getty Images
Python katta yoki murakkab dasturiy loyihalari uchun ajoyib tildir. Har qanday tilda dasturlash uchun integral dasturni o’qish va saqlash uchun kodni osonlashtiradi. Perl va PHP dasturlarini o’qilishi uchun juda ko’p kuch talab etiladi. Perl 20 yoki 30 chiziqdan keyin noto’g’ri yo’l tutadigan bo’lsa, Python toza va o’qilishi mumkin bo’lib, hatto yirik loyihalarni boshqarishni osonlashtiradi.
Uning okunabilirliği, sotib olish va kengayish kolaylığıyla, Python juda tez dastur ishlab chiqishni taklif etadi. Oddiy sintaksisdan va jiddiy ishlash qobiliyatidan tashqari, Python ba’zan kutubxonadan ishlaydigan oldindan yozib olingan kodning saqlanadigan keng kutubxonasi tufayli “batareyalar” bilan birga keltirilgan.
04 of 06
Python PHP ga qanday qilib solishtiriladi?
Hero Images / Getty Images
Python buyruqlar va sintaksisi boshqa talqin qilingan tillardan farq qiladi. PHP veb-ishlab chiqishning lingua frankasi sifatida Perldan tobora ko’proq joy olib bormoqda. Biroq PHP yoki Perldan ko’prog’i Python o’qish va unga rioya qilish juda oson.
PHP Perl bilan baham ko’rgan kamida bitta salbiy tomoni uning sindirish kodidir. PHP va Perlning sintaksisi tufayli 50 yoki 100 satrdan oshadigan dasturlarni kodlashtirish juda qiyin. Boshqa tomondan, Python tilning matosiga qattiq o’qish imkonini beradi. Pythonning okunabilirliği, dasturlarni himoya qilish va kengaytirish uchun dasturlarni osonlashtiradi.
PHP ko’pincha umumiy foydalanishni boshlaganiga qaramasdan, tizim darajasidagi vazifalarni bajarmaslik uchun veb-o’qitiladigan ma’lumotni ishlab chiqishga mo’ljallangan veb-dasturiy tildir. Bu farq Python’ta PHPni tushunadigan veb-serverni ishlab chiqishingiz mumkinligi bilan izohlanadi, lekin Pythonni tushunadigan PHP veb-serverini ishlab chiqa olmaysiz.
Nihoyat, Python ob’ektga asoslangan. PHP emas. Ushbu dasturlarning okunabilirliği, parvarishlash kolaylığı va ölçeklenebilirliği uchun katta ahamiyatga ega.
05 of 06
Python Ruby’ga qanday qilib solishtiriladi?
Todd Pearson / Getty Images
Python tez-tez Ruby bilan taqqoslanadi. Har ikkisi ham ta’riflangan va shuning uchun yuqori darajada. Ularning kodlari barcha tafsilotlarni tushunmasligingiz kerakligi bilan amalga oshiriladi. Ular faqat g’amxo’rlik qilishadi.
Har ikkalasi ham ob’ektdan ob’ektga yo’naltirilgan. Sinflar va ob’ektlarni amalga oshirish kodni yanada takomillashtirish va parvarish qilish qulayligini ta’minlash imkonini beradi.
Har ikkisi ham umumiy maqsaddir. Ular matnni aylantirish yoki robotlar nazorat qilish va yirik moliyaviy ma’lumot tizimlarini boshqarish kabi murakkab masalalar uchun eng oddiy vazifalar uchun ishlatilishi mumkin.
Ikkita til orasida ikkita asosiy farq mavjud: okunabilirlik va moslashuvchanlik. Ob’ektga yo’naltirilganligi tufayli, Ruby kodi Perl yoki PHP kabi chinakam bo’lishda xato emas. Buning o’rniga, odatda o’qilmaydi, shuning uchun u juda shafqatsizdir; dasturchining niyatiga tayanadi. “Ruby” ni o’rganayotgan o’quvchilarning bosh savollaridan biri “Bunga qanday erishish mumkin?” Python bilan, bu ma’lumot sintaksisda odatda aniq ko’rinadi. Indentatsiyani okunabilirlik uchun bajarishdan tashqari, Python shuningdek, ma’lumotni oshkoralikni juda ko’p qabul qilmagan holda amalga oshiradi.
Python, bunday o’zgarishlarning kodda ochiqligini ta’kidlayotganda, kerak bo’lganda narsalarni qilishning standart usulidan oson o’zgarishlarga imkon beradi. Bu dasturchiga zarur bo’lgan barcha narsani bajarish uchun kuch beradi, ammo keyinchalik kodni o’qiydiganlarni tushunish mumkin. Dasturchilar bir nechta vazifalar uchun Pythondan foydalanganlaridan so’ng, ko’pincha boshqa narsalarni ishlatish qiyin.
06 of 06
Python Java-ga qanday qaraydi?
karimhesham / Getty Images
Python va Java ikkala har qanday operatsion tizimda ishlaydigan oldindan yoziladigan kodning muhim kutubxonalari bilan ob’ektga asoslangan tillar. Biroq, ularni amalga oshirish juda katta farq qiladi.
Java nima tarjima til, na tuzilgan tildir. U ikkalasining ham bittasi. Tarkib olingan Java dasturlari bytecode-ga Java kodli kod turi bilan kompilyatsiya qilinadi. Dastur ishga tushirilganda ushbu bytecode Java Runtime Environment orqali ishlaydi va uni kompyuter tomonidan o’qilishi mumkin va bajarilishi mumkin bo’lgan kompyuter kodiga aylantiradi. Bytecode uchun tuzilganidan so’ng Java dasturlarini o’zgartirib bo’lmaydi.
Boshqa tomondan, Python dasturlari odatda Python tarjimoni dasturni o’qigan vaqtda ishlayotgan vaqtda tuziladi. Biroq, ular kompyuter yordamida o’qilishi mumkin bo’lgan mashina kodiga tuzilishi mumkin. Python platforma mustaqillik uchun vositachilik qadamini ishlatmaydi. Buning o’rniga platformaning mustaqilligi tarjimonni amalga oshirishda.
Python – bu nima? Oliy darajadagi dasturlash tili
Python kengaytirilgan va ko’milgan bo’lishi mumkin bo’lgan yuqori darajada universal til hisoblanadi. U, masalan, yozuv makrolar uchun bir vosita sifatida ilovalar to’plamidir. Python u katta va kichik, va hisoblash vazifalar kichik raqami uchun shunday yaxshi emas ko’p dasturlash vazifalar, bir o’rtacha tanlov qiladi.
Qaerda foydalanish kerak?
Python jadal rivojlantirish talab loyihalari uchun ideal. Bu uslubni talab dasturlar uchun yaxshi bo’lgan narsani bir necha dasturlash paradigmalar, qo’llab-quvvatlaydi. Va paketlar va modullar bir qancha mavjudligi moslashuvchan beradi va vaqtni tejash imkonini beradi.
Guido van Rossum – Python yaratuvchisi, yaxshi mukofot jamoa nomi “hayot uchun mehribon diktator”. kech 1980-yilda, Guido ba’zi dasturlash tillari xususiyatlariga yoqdi, lekin ularning hech biri u istayman barcha xususiyatlari bor edi. Xususan, til quyidagi xususiyatlarga ega bo’lishi edi.
scripting tili
skript boshqa dasturlar ishlaydigan, bir dastur. Ular bir komponent ma’lumotlarni uzatish bilan yaxshi engish va xotira boshqarish kabi bu qiziq narsalardan programcısı engillashtirish, chunki Chegaralangan tillari, tez rivojlanishi va prototipleme uchun MUMKIN.
Foydalanuvchi jamoa Python dinamik dasturlash tilini qo’ng’iroq qilish yoqadi.
operatorlari jamlanishi uchun belgi
Python padding yordamida shu guruhga mansub so’zlar belgilaydi. Bunday guruh kodi blok deb ataladi. Boshqa tillarda, u turli sintaksisini yoki tinish belgilari foydalanadi. natija ko’rsatmalar oxiri – Misol uchun, bir belgi C start ramzi va <> anglatadi. kesmada mavjudligi boshqa tillarda yaxshi amaliyot hisoblanadi, lekin belgi kuch bajarish taqdim qilingan birinchi biridir Python edi. Nima beradi? Indent o’qish va beixtiyor tushirib qoldirilgan mumkin, ularning boshida va oxirida, va tinish belgilari, kam kodi bloklari tasnifi talab uchun kodi oson qiladi. Barcha bu kamroq xato sabab bo’ladi.
yuqori darajadagi ma’lumotlar turlari
Kompyuterlar birliklari va nol ma’lumotlarni saqlash, lekin odamlar matn yanada murakkab shakllar, bo’lishi kerak. yuqori darajadagi ma’lumotlar turlarini qo’llab-quvvatlaydi, deb, murakkab ma’lumotlarni qo’llab-quvvatlaydi haqida tili. Ushbu ma’lumotlar turlari faoliyat oson. Misol uchun, Python liniyasi bo’linib bo’lishi mumkin, birlashtirish, yuqori yoki pastki holda tarjima, ular saqlanishi va boshqa ma’lumotlar ancha faoliyati ega bo’lishi mumkin va t. D. bunday ro’yxatlari va lug’atlar sifatida oliy darajadagi ma’lumotlar turlari, qidirishingiz mumkin, boshqa tillarda ortiq.
kengayish
Kengaytiriladigan dasturlash tili qo’shilishi mumkin. qo’shimchalar dasturlar va operatsion tizimlari turli ularni munosib qilish, chunki, bu tillar, juda kuchli bo’ladi. Extensions qo’shishingiz mumkin ma’lumotlar turlarini yoki tushunchalarni, modul va plaginlari. Python tili bir necha yo’llar bilan kengaytirildi. unda ish dasturchilar asosiy guruh o’zgarishlar va o’zgarishlar va boshqa modullar yuzlab maxsus maqsadlar uchun yoziladi.
tarjima
Talqin tillar odamlar tomonidan yozilgan manba to’g’ridan-to’g’ri uddasidan amalga oshiriladi, va bu kabi C ++ kabi kompilyatsiya tillarda yozilgan dasturlar, mashina kodi tarjima qilinishi kerak. tarjima chivin sodir beri talqin tillari, sekin, lekin Tuzuvchining bajarilishi kutish uchun hech qanday ehtiyoj bor, chunki yozuv va nosozliklarni tuzatish dasturlari tez. Ular turli platformalarda ustidan olib osonroq bo’ladi.
Bir Python talqin yoki til olingan bo’lsin haqida bahslasha mumkin. C tilida yozilgan bo’lib, kodni ijro (Java kabi) olingan oldin bir, talqin va uning komponentlarini ko’p mashina to’la tezlikda ishlaydigan, deb ko’p jihatdan u ishlaydi-da
Guido 1989 yilda Rojdestvo dam olish paytida Python yozishni boshladi, va keyingi yil davomida, u o’z hamkasblarining mulohazangiz asosida til yakunladi. U Yangiliklar Guruhlar Usenet’te birida joylashtirilgan edi keng jamoatchilik, fevral 1991 yil, natija ko’rdim.
Boshlovchilar uchun Python
Python yozuv dasturlarni ishga tushirish uchun, uni o’rnatish kerak. Python 2,7 va Python 3.5 versiyalarida, mos kelmaydigan tufayli qaysi ularga yozilgan dasturlar uchun muhim farqlar mavjud.
kompyuter-yilda “McIntosh” Til oldindan o’rnatilgan bo’lib, u operatsion tizim yoshi versiyasiga bog’liq. Windows ostida Python o’rnatish bo’lishi mumkin. o’rnatish paketi fayllari python.org saytida tanlanishi mumkin.
o’zaro ikki yo’llari
Python dasturlarni xarakterlanadi oddiylik sabablarga, biri siz, rivojlantirish yozish va debug dasturlari yordam vositalari bilan keladi, deb.
interaktiv rejimda, buyruqlar operatsion tizimi (qobiq) buyruq qatorni buyruqlarni qabul sifatida deyarli bir xil, bir vaqtning o’zida bir chiziq ustida kiriladi. Bundan tashqari, qisqa bir nechta dastur yaratish mumkin, yoki bir matn fayli yoki ajralmas Python modullar kodni import qilish. yangilar uchun, interaktiv rejimi keng yordam tizimi o’z ichiga oladi, deb bilish foydali bo’ladi. Bu dasturlash tili xususiyatlarini o’rganish uchun qulay yo’lidir.
IDLE rivojlantirish muhiti interaktiv rejimini va yozishni vositalari va dasturlarni ishga tushirish, shuningdek, kuzatuv tizimi nomlarini o’z ichiga oladi. o’rta Python yozilgan va tilining keng imkoniyatlar namoyish etiladi.
interaktiv rejimi
Bu yerda siz ham, ko’p satırlı kodni yozish, dastur amalga oshirilishi mumkin deyarli hech narsa, albatta, mumkin. Bu xil bo’lishi mumkin:
- xavfsiz tajribalar uchun sinov muhiti;
- Agar Python dasturlarni o’rganish imkonini beruvchi atrof-muhit;
- topish va xatolarni tuzatish uchun vosita.
interaktiv rejimda kirib qutqarish uchun ekanligini yodda tuting mumkin emas. Buning uchun, kodni nusxa va faylida natijalarini yozib.
Interaktiv rejimi matnni manipulyatsiya va o’zgaruvchilar uchun qiymatlar sozlang, bir kalkulyator sifatida foydalanish mumkin. Bundan tashqari, ularni sinash uchun dasturlar modul, vazifalari, yoki qismlar import mumkin. Bu vaqtda qismlari bir import tomonidan uzoq dasturlari va debug dasturlarini yozmasdan Python ob’ektlar bilan tajriba qilishga yordam beradi.
onlayn ishlash
Terminal oynasida Python Run joriy dastur versiyasi haqida ma’lumot ko’rsatadi so’ng, uning ozod sanasi, yanada harakatlar uchun bir necha maslahatlar va bir taklif >>> kiriting.
, Interaktiv rejimda ishlaydi, bir buyruq yoki ifoda kiriting va Enter tugmasini bosing.
yozilgan javob talab qiladi, yoki tarjimon uni tushunish emas, agar Python usulidan fahmlaydi va munosabat.
quyidagi buyruqni chop etadi. Bosib chiqarish joy ko’rsatilmagan, chunki, chiqish ekranga ketadi.
- >>> Print “Salom dunyo!”
- dunyoni Salom!
Bu bitta chiziq butun dastur! Python interaktiv Enter ni bosib, kirib har tor kodni qiladi va natija ostida ko’rsatiladi.
ob’ektga haqida ma’lumotni ko’rsatish
interaktiv rejimda, ob’ekti haqida ma’lumotni ko’rish uchun ikki yo’l bor:
- ob’ektini (yoki nomini) va Enter tugmasini bosing qo’yish;
- Chop etish uchun buyruqni va ob’ekt (yoki nomini) kiriting va Enter tugmasini bosing.
Natijada ob’ektga bog’liq.
Ba’zi ma’lumotlar turlari (masalan integer va ro’yxatlarini,) bilan, bu ikki usul ham bir xil natija ishlab chiqarish:
- >>> x = [3,2]
- >>> x
- [3, 2]
- >>> Chop x
- [3, 2]
torlar uchun, «Print nomi” buyruq majmui natijasi nomi uchun olingan natija bir oz farq qiladi. : Mavjud emas – birinchi holda, qiymati ikkinchi esa, tirnoq ichida bo’ladi
- >>> x = “MyString”
- >>> x
- “MyString”
- >>> Chop x
- MyString
nomi (misol, vazifalari, modul, yoki sinf misol uchun) kodi blokda anglatadi bo’lsa, nomini kirib ma’lumotlar, nomi va saqlash joyi turi haqida ma’lumot beradi.
Quyidagi misol bir sinf deb atalgan Xabarni yaratadi va haqida ma’lumot ko’rsatadi
- >>> sinf Xabar:
- . o’tishi
- .
- >>> Xabar
- >>> Chop etish Xabar
- __main __. Xabar
chiziqlar
Python chiziqlar belgilar sekanslarıdır. bitta tirnoq ( ‘) belgilarni kiritish orqali yaratilgan tom ma’nodagi A string, er-xotin ( “) yoki uch (‘ ‘yoki” “”) narx belgilari. Masalan, qiymat o’zgaruvchan x tayinlangan:
- >>> x = “MyString”
Python tor bir necha ichki xususiyatlarga ega. Ulardan biri, barcha bilan nusxasini qaytarib qobiliyatidir kichik harflar. Bu qobiliyat usullari sifatida ma’lum. bir ob’ekt ustida bir usulini chaqirish uchun, bir nuqta sintaksisi foydalanishingiz kerak. (.) Bu holatda bir tor ob’ektga mos yozuvlar bo’lgan o’zgaruvchilar nomi, kirganidan keyin, siz nuqta operatori qo’yish kerak, keyin ochilishi va yopilish Qavs ortidan usuli nomi, bo’ladi:
- >>> x.lower ()
- “Mystring”
Katalog tuzish operator s [i] dan foydalanib liniyasi qismini olish mumkin. s [0] mag’lubiyatga birinchi belgi qaytadi, shunday qilib, katalog yaratish [1] soniya qaytadi, va hokazo b, noldan boshlanadi:
String usullari, va “Unicode” bilan oddiy chiziqlar ishlash. Ular quyidagi ishlab chiqarish:
- o’zgarish (quyi, swapcase, unvoni, foyda yuqori) ro’yxatdan;
- (Hisoblash) hisoblash;
- kodlash (robita, decode) o’zgartirish;
- qidirish va (rfind, indeks, rindex, tarjima, topish o’rniga) almashtirish;
- sharoitlar (startswith, endswith, isalnum, isalpha, isdigit, islower, isspace, istitle, isupper) tekshirish;
- birlashgan va (bo’lim, rpartition, split, splitlines, qo’shilishga) ajratilgan;
- format (markazi, ljust, lstrip, rstring, rjust, strip, zfill, expandtabs).
Python: Do’slashish
Python satr cheklangan belgilar bo’lsa, hech qanday cheklovlar yo’q ro’yxati. Ular boshqa ro’yxatlarini, shu jumladan o’zboshimchalik obyekt, ketliklar buyurilgan. Bundan tashqari, u, kiritish o’chirish va uning elementlari o’rniga mumkin. A ichki vergul bilan ajratilgan ob’ekt soni, kvadrat qavs, va bir Python ro’yxat bor. Nima bu, quyida ko’rsatilgan ifodalaydi – bu yerda misollar va ma’lumotlar operatsiyalar ular bilan birga bo’lgan:
- >>> asoslari = [ ‘A’, ‘C “,” G “,” T “]
- >>> asoslari
- [ ‘A’, ‘C “,” G “,” T “]
- >>> bases.append ( «U»)
- >>> asoslari
- [ ‘A’, ‘C “,” G “,” T “,” U’]
- >>> bases.reverse ()
- >>> asoslari
- [ «U», «t», «G», «C», «A»]
- >>> asoslari [0]
- “U”
- >>> asoslari [1]
- “T”
- >>> bases.remove ( «U»)
- >>> asoslari
- [ ‘T “,” G “,” C “,” A “]
- >>> bases.sort ()
- >>> asoslari
- [ ‘A’, ‘C “,” G “,” T “]
Bu, masalan, u individual belgilar ro’yxatini tomonidan yaratilgan. So’ngra unsurlar tartibini qaragan element oxiriga qo’shiladi edi, ularning indeksi lavozimiga tomonidan qazib elementlar element qiymatini «U» ega va ishlab chiqarilgan mahsulot saralash o’chirildi. ro’yxatdan ob’ektni ko’tarilishi () usuli, ya’ni qo’shimcha ma’lumot, ko’tarilishi kerak bo’lgan qiymat berish uchun vaziyatni ko’rsatib turibdi.
usullari bilan bir qatorda, shunga o’xshash Remove () ichida, Python funktsiyasi deb nomlangan boshqa bir shunga o’xshash xususiyatiga ega. funktsiya va usuli orasidagi yagona farq birinchi bir ob’ekt bilan bog’liq emas, deb hisoblanadi.
Python: funktsiyasi
Funksiyalar bir yoki bir necha qadriyatlar bo’yicha operatsiyalarni amalga oshirish va natija qaytadi. Ularning katta soni Python qurildi. ajralmas vazifalarni misollar:
- Len () – ketma-ketlikda elementlar sonini qaytaradi;
- dir () – ob’ekt xususiyatlarini ifodalovchi skriptlarini ro’yxati qaytadi;
- ro’yxati () – bir necha boshqa qatori boshlab, bir yangi ro’yxatini qaytaradi.
- >>> yordam (dumaloq)
- davra ajralmas funktsiyasi haqida Yordam:
- dumaloq (. )
- dumaloq (Number [ndigits]) -> suzuvchi nuqta soni
Bu o’z vazifalarini aniqlash ham mumkin.
Foydalanuvchi belgilangan vazifalar
o’z Python-funktsiyasi kabi yaratish jarayoni. Birinchi satrda funktsiya nomi va Qavslar ichiga dalillarni (kutilmoqda kiritish qiymatlari) tomonidan ta’qib daf kalit so’zi bilan boshlanadi, va bir yo’g’on bilan tugaydi. Keyingi buyruqlar tanasi vazifalarini tashkil qilish va girintilidir kerak. Fikr funktsiya tanasi boshida joylashgan bo’lsa, uning hujjatlarini bir qismi bo’ladi. funktsiya oxirgi liniyasi natija qaytaradi:
- >>> daf (DNK) moslashtirmoq:
- . “” “RNK mag’lubiyatga DNK satrni qaytish.” “”
- . Qaytish dna.replace ( «T», «U»)
- .
- >>> transkribe ( ‘CCGGAAGAGCTTACTTAG’)
- “CCGGAAGAGCUUACUUAG”
Bu, masalan, DNK ketma-ketlikni ifodalovchi bir qator kutadi transkribe deb nomlangan vazifasini, tashkil etildi. usuli bir xarakterdagi barcha hodisalar bilan asl mag’lubiyatga bir nusxasini qaytaradi () o’zgartiring. kodeksining uch chiziqlar RNK DNK ko’chirmoq ruxsat etiladi. quyidagicha teskari funksiyasi:
- >>> daf (S) teskari:
- . “” “teskari tartibda natija satrni qaytish.” “”
- . harflar = ro’yxati (lar)
- . letters.reverse ()
- . Qaytish ‘.join (harflar)
- .
- ( «CCGGAAGAGCTTACTTAG ‘) teskari >>>
- “GATTCATTCGAGAAGGCC”
Teskari funktsiya, bir mag’lubiyatga oladi unga asoslangan ro’yxatini yaratadi, va uning tartibini o’zgartirish. Endi Siz teskari qilish kerak. ob’ekt mag’lubiyatga qiymati har bir elementi bulish, ro’yxatni birlashtiradi a birlashtirish () usuli, bor. separator kerak emas, chunki, usul, ikki chiqib ketish ( ” yoki “”) tasvirlab, bir chiziq ustida ishlatiladi.
Lug’atlar
A Dictionary Python – bu nima? Bu an’anaviy qog’oz lug’atda bir xil foydalari bor. Bu tezlik bir kaliti (so’z) bilan bog’liq kerakli qiymatini (definition) topish imkonini beradi. Lug’atlar asosiy-qiymati juft bir ketma-ketlikni o’z ichiga olgan ayraç va vergul bilan ajratiladi. Lug’atlar buyurdi emas. Buning o’rniga, Dictionary qadriyatlar o’z kaliti emas, balki ularning lavozim orqali mavjud.
- >>> basecomplement =
- >>> basecomplement.keys ()
- [ ‘A’, ‘C “,” T “,” G’]
- >>> basecomplement.values ()
- [ ‘T “,” G “,” A “,” C “]
- >>> basecomplement [ ‘A’]
- “T”
darslari
O’z moslamalarni yaratish uchun, siz bir sinf deb ataladi naqsh qanday aniqlash kerak bo’ladi. Python, bu nom va yo’g’on ortidan operator sinf, uchun. sinf belgilash tana, bu sinf asoslangan ob’ektlarini barcha hollarda mavjud bo’ladi xususiyatlarini va usullarini o’z ichiga oladi.
afzalliklari
Eng dasturlash tillari samimiy xususiyatlarini taklif, lekin ularning hech biri qulay va Python tomonidan taklif muassasalari bunday birlashmasidan ega. Bu qanday foyda keltiradi? Mana, ulardan ba’zilari:
- Til boshqa dasturlar singdirilishi va so’l yaratish uchun foydalanish mumkin. Misol uchun, Bo’yoq Pro 8 do’kon yoki keyinchalik, bu dasturlash tili hisoblanadi.
- Python foydalanish va taqsimlash, tijorat asosida yoki yo’q qilish uchun bepul.
- Til kuchli ishlash qobiliyat bor, va matn ma’lumotlar juda ko’p bilan ishlash ilovalar ishlatiladi matnni qidirish.
- Bu boshlang’ich dasturlarini tekshirish kerak bo’lmasdan katta ilovalarni yaratish mumkin.
- Python individual modullar va butun dasturlari sinov va tuzatishni qo’llab-quvvatlaydi.
- 3.1. Using Python as a Calculator