Introduction to Python Programming | Python Language Introduction Tutorial For Beginners 2018. Here in this blog post Coding compiler sharing Python 3 language introduction tutorial for beginners. This tutorial is for absolute beginners who are looking for learning Python programming. Let’s start learning Python 3.
Introduction to Python
In the following example, the input and output are marked with a greater than sign and a full stop (
...), respectively: if you want to reproduce these examples, you need to type in the prompt (after the prompt) that does not contain the prompt after the interpreter prompt The line of code.
Related Articles: Python Getting Started Guide
It should be noted that the subordinate prompts encountered in the exercise indicate that you need to enter a blank line at the end, and the interpreter will know that this is the end of a multi line command.
Many of the examples in this manual – including those with interactive prompts – contain comments. Comments in Python
#character start until the actual end of the line (Annotation – author used herein to represent an actual physical line editor transducer row instead wrap).
Related Article: Python Interpreter Tutorial
Comments can start at the beginning of the line, they can be after the space or code, but they do not appear in the string. Text string
#of characters merely represent
#. Comments in the code are not interpreted by Python, and they can be ignored when entering the example.
The following example:
# 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."
Using Python as a Calculator
Let’s try some simple Python commands. Start the interpreter and wait for the primary prompt
>>>appears (not required for a long time).
The interpreter behaves like a simple calculator: you can enter some expressions to it, which will give you the return value. Expression syntax is straightforward: operators
/other languages (for example: Pascal or C); parentheses (
()) for a packet. E.g:
>>> 2 + 2 4 >>> 50 - 5 * 6 20 >>> ( 50 - 5 * 6 ) / 4 5.0 >>> 8 / 5 # division always returns a floating point number 1.6
Related Articles: Learn Python In One Day
/) always returns a float. To use floor division and get integer results (any fractional part discarded), you can use the
//operator; you can calculate the number of I 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 # result * divisor + remainder 17
By Python, may also be used
**operators calculated power power.
>>> 5 ** 2 # 5 squared 25 >>> 2 ** 7 # 2 to the power of 7 128
The equal sign (
'=') is used to assign values to variables. After the assignment, there will be no results before the next prompt:
>>> width = 20 >>> height = 5 * 9 >>> width * height 900
Variables must be “defined” (assigned) before they are used, otherwise errors occur:
>>> # try to access an undefined variable ... n Traceback (most recent call last): File "<stdin>" , line 1 , in <module> NameError : name 'n' is not defined
Floating-point numbers have complete support; integers and floats are mixed, and integers are converted to floating-point numbers:
>>> 3 * 3.75 / 1.5 7.5 >>> 7.0 / 2 3.5
In interactive mode, the value of the most recent expression is assigned to the variable
_. So we can use it as a desktop calculator, which is convenient for continuous calculations, such as:
>>> Tax = 12.5 / 100 >>> price = 100.50 >>> price * tax 12.5625 >>> price + _ 113.0625 >>> round ( _ , 2 ) 113.06
This variable is read-only for the user. Don’t try to assign value to it – you will only create a separate local variable with the same name, it masks the magic effect of the system’s built-in variables.
In addition to int and float , Python also supports other numeric types such as Decimal and Fraction . Python is also built-in support complex , suffix
Jrepresents an imaginary number part (e.g.,
Related Article: Python For Machine Learning
Python also provides strings that can be represented in several different ways than numeric values. They can be identified by single quotation marks (
'...') or double quotation marks (
\Can be used to escape quotation marks:
>>> '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," he said.' '"Yes," he said.' >>> " \" Yes, \" he said." '"Yes ,"he said.' >>> '"Isn \' t," she said.' '"Isn\'t," she said.'
In the interactive interpreter, the output string is quoted and special characters are escaped with a backslash. Although it may not look the same as the input, the two strings are equal. If the string has only single quotes and no double quotes, it is quoted in double quotes, otherwise it is quoted in single quotes. The print() function produces a more readable output. It will leave out the quotes and print out the escaped special characters:
>>> '"Isn \' t," she said.' 'Isn\'t," she said.' >>> print ( '"Isn \' t," she said.' ) "Isn't, "she said. >>> s = 'First line. \n Second 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 front of you with the
\character is treated as a special character, you can use the original string , it is to add one before the first quotation mark
>>> print ( 'C:\some \n ame' ) # here \n means newline! C:\some ame >>> print ( r 'C:\some\name' ) # note the r before the quote C :\some\name
String text can be divided into multiple lines. One way is to use triple quotes:
'''...'''. Newline end of the line will be automatically included in the string, but the end of the line may be coupled
\to avoid this behavior.
The following example: A continuous string that can use a backslash as the end of a line indicates that the next line is logically the follow-up to the line:
Print ( """ \ Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to """ )
The following output will be generated (note, there is no first line in the beginning):
Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to
The string can
+concatenation operator (stick together), may be formed of
>>> # 3 times 'un', followed by 'ium' >>> 3 * 'un' + 'ium' 'unununium'
Two adjacent strings of text are automatically linked together. :
>>> 'Py' 'thon' 'Python'
It is only used for two string literals and cannot be used for string expressions:
>>> prefix = 'Py' >>> prefix 'thon' # can't concatenate a variable and a string literal ... SyntaxError: invalid syntax >>> ( 'un' * 3 ) 'ium' ... SyntaxError : invalid syntax
If you want to connect multiple variables or connect a variable and a string literal, use
>>> prefix + 'thon' 'Python'
This feature is especially useful when you want to split long strings:
>>> text = ( 'Put several strings within parentheses ' ' have have them joined together.') >>> text 'Put several strings within parentheses to have have joined joined.'
Strings can also be intercepted (retrieved). Like C, the first character index of the string is 0. Python does not have a separate character type; a character is a simple one-length string. :
>>> word = 'Python' >>> word [ 0 ] # character in position 0 'P' >>> word [ 5 ] # character in position 5 'n'
The index can also be negative, which will cause the calculation to start from the right. E.g:
>>> word [ - 1 ] # last character 'n' >>> word [ - 2 ] # second-last character 'o' >>> word [ - 6 ] 'P'
Please note that -0 is actually 0, so it does not cause the calculation to start from the right.
In addition to the index, also supports slices . The index is used to get a single character, slice Let you get a 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'
Note that the starting character is included and does not include the last character. This makes is always equal :
s[:i] + s[i:]
>>> word [: 2 ] + word [ 2 :] 'Python' >>> word [: 4 ] + word [ 4 :] 'Python'
The index of the slice has very useful default values; the first omitted index defaults to zero, and the second omitted index defaults to the size of the slice’s string. :
>>> 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'
There is a way to easily remember slice works: when the index is sliced in two characters between . The index of the first character on the left is 0, and the string of length n is the right index of the last character of the string n . E.g:
+---+---+---+---+---+---+ | P | y | t | h | o | n | +---+---+--- +---+---+---+ 0 1 2 3 4 5 6 - 6 - 5 - 4 - 3 - 2 - 1
The first row of numbers in the text gives the index 0…6 in the string. The second line gives the corresponding negative index. Slices are all the characters between the boundaries marked by two values from i to j .
For non-negative indexes, the slice length is the difference between the two indexes if they are all within the boundary. For example, it
Attempting to use too large an index results in an error:
>>> word [ 42 ] # the word only has 6 characters Traceback (most recent call last): File "<stdin>" , line 1 , in <module> IndexError : string index out of range
Python gracefully handles those slicing indexes that don’t make sense: an index value that is too large (that is, the subscript value is greater than the actual length of the string) will be replaced by the actual length of the string when the upper boundary is larger than the lower boundary (that is, sliced left Values greater than the right value return an empty string:
>>> word [ 4 : 42 ] 'on' >>> word [ 42 :] ''
Python string can not be changed – they are immutable . Therefore, assigning to the position of a string index results in an error:
>>> word [ 0 ] = 'J' ... TypeError: 'str' object does not support item assignment >>> word [ 2 :] = 'py' ... 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 the string:
>>> s = 'supercalifragilisticexpialidocious' >>> len ( s ) 34
Several Python complex data type used to represent other values. The most common is the list , which can be written as a comma-separated list of values between square brackets. The elements of the list do not have to be of the same type:
>>> Squares = [ . 1 , . 4 , . 9 , 16 , 25 ] >>> Squares [. 1,. 4,. 9, 16, 25]
Like the string (and all the other built-in sequence types), as the list 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 of elements that contain the request. This means that the following slicing operation returns a new (shallow) copy of the list:
>>> squares [:] [1, 4, 9, 16, 25]
The list also supports connections like this:
>>> squares + [ 36 , 49 , 64 , 81 , 100 ] [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Unlike immutable strings, lists is variable , which allows to modify elements:
>>> 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 use the
append() method (later we’ll see more about the method list) to add new elements to the end of the list:
>>> 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]
You can also assign values to slices, which can change the size of the list, or empty it:
>>> 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 works for lists:
>>> letters = [ 'a' , 'b' , 'c' , 'd' ] >>> len ( letters ) 4
Allow nested lists (create a list of 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'
The First Step in Python Programming
Of course, we can use Python to accomplish more complex tasks than two plus two. For example, we can generate a write Fibonacci program sequence, as follows:
>>> # Fibonacci series: ... # the sum of two elements defines the next ... a , b = 0 , 1 >>> while b < 10 : ... print ( b ) ... a , b = b , a + b ... 1 1 2 3 5 8
This example introduces several new features.
The first line contains a multiple assignment : the variables
balso won the new values 0 and 1 the last line used once.
In this demo, before the variable assignment, the right side first completes the calculation. The right expression is evaluated from left to right.
When the condition (here is ) is true, the while loop executes. In Python, like C, any non-zero integer is true; 0 is false. The condition can also be a string or list, which can actually be any sequence;
b < 10
All non-zero lengths are true and the empty sequence is false. The test in the example is a simple comparison. Standard comparison operator and the same
Loop body is indented : indentation is Python organization method statement. Python (yet) doesn’t provide integrated line editing, so you have to enter TAB or space for each indentation.
In practice, it is recommended that you find a text editor to enter complex Python programs. Most text editors provide automatic indentation. When interactively entering a compound statement, you must enter a blank line at the end to identify the end (since the interpreter cannot guess which line you entered is the last line). Note that each line in the same block must be indented in the same way The number of blanks.
The print() statement of the keyword outputs the value of the given expression. It controls multiple expressions and string output for the string you want (as we did in the previous calculator example).
Strings are printed without quotation marks and spaces are inserted between each child, so you can make the format pretty, like this:
>>> i = 256 * 256 >>> print ( 'The value of i is' , i ) The value of i is 65536
Ending a line break with a comma:
>>> a , b = 0 , 1 >>> while b < 1000 : ... print ( b , end = ',' ) ... a , b = b , a + b ... 1,1, 2,3,5,8,13,21,34,55,89,144,233,377,610,987,