Have you ever wondered how a computer works? Although we can't teach you everything in an article, you can get a good start by learning how to write your own program. In this Python tutorial, you will learn the basics of computer programming and use one of the best programming languages for beginners.
What is programming?
As simple as possible, programming is the art of writing code that commands a computer to accomplish a task. One of the tasks here can be a simple two-number addition, or a complex task like putting a spaceship into orbit!
Inside a program, the smallest component is called a statement (statement)--a directive that is made to a computer.
When you have completed your program, the compiler will convert your code to machine code-the lowest level of computer language. The machine code indicates that the CPU is working (central processing Unit), or CPU, where the bread contains some steps, such as loading a value or doing a mathematical operation.
If you've ever heard someone say, "I've compiled my program," that means they've converted the code into machine code.
Why not just write the machine code? The reason is clearly that the code is readable. The following is a comparison of the Python version of the program and its corresponding machine code:
Python code
Print "Hello, world!" ... "Hello, world!"
The corresponding machine code
C7 3c 2a 3c 2a 2b 2a 5c 3c 5c 2a 2b 2a 5c 3C28 5c 2a 2b 2a 5c 3c 5c 2a 2b 2a 5c 3c 5C2A 2b 2a 5c 2 A 5c 3c 5c 2a 2B2A 5c 3c all 5c 2a 2b 2a 5c 3c 5c 2a 2b 2a 5C3C 5c 2a 2b 2a 5c 3c 5c 2a 2b 2a 5c 3c 285C 2a 2b 2a 5c 3c 5c 2a 2b 2a 5c 3c 2A2B 5c 2a 00 00 01 00 00 00 00 00 00 00 00 00 00 0000 00 00 00 00 00 00 00 00 00 00 00 0 0 00 00 0000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0000 00 00 00 00 00 The xx xx xx 0000 xx xx xx xx xx xx xx 0000 xx xx xx (6c 6c 6f 2c 20 5) at XX. 76F 6c 64 21 00 00 00 00 00 00 00 00 00 00 0000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ... " Hello, world! "
It's obvious why you don't want to write the machine code directly. However, there are some people will write machine code-radish cabbage each their own!
We have overlooked a small problem above. Python is an interpreted language; you don't compile it directly into machine code, as we hinted above.
In fact, Python uses something called an interpreter. An interpreter is another program that compiles code into something called a binary code, and then translates it into machine code when the program runs. You'll learn more about the interpreter in a few more things.
When you finally run the program, the machine code you just compiled will be loaded into memory and the CPU will read it and execute the program.
However, when you start learning to use Python programming, you don't need to fully understand how the compiler works inside, but you have to make sure that you have Python installed.
Ready to start
If you're using a Mac, you're lucky that--python is already preinstalled on your Mac. Using the Python interpreter in your Mac, open * * Terminal * * (**terminal.app**), you can find it in the application/Tools folder, or enter it in spotlight, like this:
After opening the terminal, enter the following command and press ENTER:
$ python
You will see a result similar to the following:
Note: If you do not get the results above, copy the output to the forum and we will do our best to help you! **
Windows
On Windows, the process is a little bit complicated--but still, most of the stuff is still in windows!. On:]
First, visit the download page of the Python website in your browser.
Scrolling page Skips all Python 3.x.x versions, directly to Python 2.7.x. Download the Windows installation package (Windows Installer), run it, follow the instructions, and accept the default options.
Once the installation package is complete, you can start it.
On Windows Vista or Windows 7, this starts:
1. Click the Start menu in the lower left corner.
2. Click All Programs
3. Open the Python folder
4. Double-click the Idle Interpreter
If you use Windows 8, this starts:
1. Click on the lower left corner of the Start menu
2. In the search box, enter the idle
3. Click on the Idle (Python GUI)
No matter how you start the interpreter, you should make sure it works, enter the following command in the terminal, or enter the following commands in the Windows command prompt and press ENTER:
Print "Hello world!"
It doesn't look like it, but you've already finished your first Python program! When you are learning most languages, printing out Hello, world is considered a starting point.
The ' python ' command instructs the computer to output the following characters on the screen--not to print on your printer! Note that "Hello world" is surrounded by quotes, and anything in quotes is treated as regular text and is not interpreted as an instruction.
Variable
Variables are a way to store data in your computer's memory, and you will often use them in your programs. In some languages, variables have specific types that indicate which of these variables belong to those classes.
In Python, you don't need to declare the type of the variable. There is no need to worry about these details for the time being, and you will learn about this in the chapters later in this tutorial.
Enter the following command in the interpreter and press ENTER:
Hello = "Hello world!"
This declares the Hello variable and assigns the Hello world class to it. Now, you don't need to enter this string in the application where "Hello World" is needed, instead, you can use the Hello variable.
Enter the following command in the interpreter and press ENTER:
Print Hello
This command produces the same result as the Hello World example, but it prints out the value of the Hello variable.
Variables can also be used to store numbers. Enter the following command in the interpreter:
x = 5print XY = 10z = x + yprint Z
Note: From now on, you may want to enter multiple lines of statements, just enter the carriage return at the end of each line * *
First guess the above code will do some of the above, and then look at the following answer:
This code prints 5 and then prints 15. The first ' print ' statement prints the variable x that you assigned to 5. It then prints the results of the y+x. Because Y is assigned a value of 10,x is 5, it prints 15.
Most of the program variables in your life are the core. As you study this tutorial, you will become very familiar with variables.
Variable type
You have encountered a variable in the previous tutorial, but we did not introduce it carefully. Different variable types store different types of values.
Note: For all built-in types, see the official Python documentation
So far, you've only dealt with two basic types in Python: integer (' integers ') and string (' strings '), you'll also encounter a Boolean type (' Boolean ') that you can use to store ' True ' or ' False '.
The following is a little introduction to these variable types:
Integral type
An integral number, which is an integer. The range of integers is 2147483648 to 2147483647 on a 32-bit machine and -9223372036854775808 to 9223372036854775807 on a 64-bit machine.
You can simply enter a number like this to create an integral type, without any quotation marks:
Foo = 5
String type
Strings are a string of characters; You can use strings to represent a lot of things, from any text on the screen to the entire page request.
Create a string by including a string of characters in quotation marks, as follows:
Boolean type
The Boolean type represents true or false.
You create a Boolean type by using True or FALSE, starting with uppercase, without the need for quotation marks, as follows:
' Isfoo = True '
There is no quotation mark on either side of the variable; If you enclose true in quotation marks, you create a string type!
String joins and integer additions
Python makes it easy to hook up two strings together, which we also call string connections. You can use ' str () ' To convert an integer type to a string, instead, you can use ' int () ' to convert a string to an integral type.
Enter the following command in your interpreter:
"1" + "1" 1 + one + int ("1")
The following explains what the above code does:
-The first statement joins two strings; the quotation marks ensure that the two numbers are treated as strings except. The result is "11″."
-The second statement adds two numbers as integers, and the result is 2.
-The last statement adds an integer and another string that is converted to an integer, and the result is 2.
If statement
The IF statement checks if a condition is true, and if so, executes a piece of code. A conditional statement is usually the form of ' value-operator-value ', which is typically a comparison of two values.
For example, you can use ' x = = 0 ' To evaluate whether a value is equal to 0, ' = = ' is equal to the operator.
Here are some common comparisons in Python
A = = B: #Checks If A and B are equala! = B: #Checks If A and B are not Equala > B: #Checks If A is greater than BA < B: #Checks If A is less than BA >= B: #Checks If a was greater than or equal to BA <= B: #Checks If a was less than O R equal to B
The IF statement is in the following form:
If Conditional:do_statements_here
Notice how to ' execute some statements here ' to indent the line. This is how you declare blocks of code in Python. Each line in the same block of code must be indented with the same tab or space as all other lines, which is mandatory for the language. In other words, do not mix tabs and spaces. Create an If statement and enter the following command in the interpreter:
Welcome to you is the mysterious prompt ' ... '; this means that the interpreter is waiting for you to enter the contents of the code block, press the TAB key, and enter the second line:
Press ENTER again, and your cursor is back to the far left of the console. To enter a code block statement again, just press TAB again. If you have finished typing, press ENTER to tell the interpreter that your code block is complete.
Take a look at the following example:
x = 10y = 10if x = = 10:print "x equals 10!" if x = = Y:print "x equals y!"
The first statement determines if x is equal to 10, and if so, prints ' x equals 10! '. Another if statement determines if x is equal to Y, and if so, prints ' x equals y! ' `.
For loop
The For loop then iterates through the items in the list and assigns the current item to the variable. A list can almost be a collection of anything!
Enter the following code, and indent as follows:
For x in range: Print X
In this example, ' range (10) ' generates a list of numbers 0 through 9. The For loop assigns a number in the range to x at a time. Just like the IF statement, the FOR Loop executes each statement in the indentation below it. In the example above, the indented code block contains only a single statement.
Because print is called 10 times and is called once for each item in the list, the program prints numbers from 0 to 9.
Function
A function is a code block that can be reused to complete a particular block of code. For example, you can write a function that adds two numbers or prints a string. You can define and invoke the function as shown in the following example.
def hello (): print "Hi" for X in range (3): Hello ()
Before running, can you guess what the output of this program is? The answers are given below:
It prints "Hi" three times, because the for loop calls this Hello function three times.
The indented code block defines the statement to execute when you call the function. Because ' print ' Hi ' is the only indented statement in this function, it is the only statement that is executed when the function is called, not the following lines.
You can call the function by typing the function name with a pair of parentheses at the end, as shown earlier, ' Hello () ' invokes the function you called above. The function is a bit like a walled garden: they can't see the world of their acres of three-point surprises. This is called the ' variable scope '. If you want a function to work with outside data, you need to pass the data to the function.
This can be achieved with ' parameters ' (arguments)-No, no, there is no quarrel between the functions (argue)!
A parameter is a variable that you pass to the function, and the function can use the value of the parameter internally.
You can declare a parameter function as follows:
def add (A, B): print A + b
The above function defines two parameters, A and B, enclosed in parentheses, separated by commas. When you call this function, the interpreter will set the value of a and B to the value you passed in the variable.
Take a look at the following example:
def add (A, B): Print A + badd # Prints 3!
In the example above, the ' add ' statement sets a and B to 1 and 2 respectively. The function then prints the number of the two numbers you passed in. The above example prints the results of the calculation--but what if you want to do something with this calculation? What if you want to add a different value to the result of this function?
To do this, you need to add a ' return statement ' to your function.
Consider the following code:
def add (A, B): Return a + bprint Add (2, 2) + 1
In the example above, your function adds two numbers as before, but the ' return ' statement puts two numbers and returns the function call statement.
This means that the ' print ' statement above gets the value returned by Add (2,2) and adds 1 to it, and the result is 5.
While loop
The while loop is similar to the For loop. The For loop continues until the end of the list is reached, but the while loop loops until the value of the given condition equals false. The typical structure of a while loop is the following:
while (conditional): run_statement
Typically, the condition variable is updated during the loop run. Enter the following program in the interpreter to see the process:
x = 0while x < 10:print x x + = 1
This program behaves like the for loop above, but uses a while loop. This is what the above program does:
1. Assign a value of 0 to X
2. Check if ' x < 10 ' is met
3. If the value of ' X < 10 ' is ' True ', execute the following code block. If ' False ' exits the loop
4. print ' x '
5. Add the ' x ' value to 1
One thing to be aware of when using a while loop is to not create a dead loop.
Enter the following program in the interpreter to see what the look dead loop looks like:
x = 0while True:print x x + = 1
WOW--The terminal is crazy, right? Press CTRL + C to terminate the program.
What just happened? If you look closely, you will find that the condition of the while loop, true can never become false, so this code will print the number as fast as the CPU can perform.
The story tells us: Always be careful when writing while loops, because the infinite loops in your code are not very good for the real world!
It is possible to use true as the condition of the while loop, especially if you do not know how many times to loop. But you need some tricks to get out of this loop.
Enter the following code in the interpreter:
x = 0while True:print x + = 1 if x >: Break
That's better! The code above prints 0 to 10 and then exits. The technique used here is the break statement, which jumps directly out of the loop. For whatever reason, you can use this technique if you want to jump early in the for loop.
Capturing user input
One of the cool things about Python is that it's very easy to get input user input in text form. Input refers to any data that is provided externally to the program, such as text or other instructions that affect the behavior of the program.
Enter the following code in your interpreter:
Name = Raw_input ("What is your name?") Print "Hello," + Name
The above code first lets you enter, and once the user enters the answer to the question, the program assigns it to the name variable. After this process is complete, the program connects the string "Hello," and the contents of the variable name.
The Raw_input () function is a python built-in function that finishes printing the input string from the console, captures the user's input text, and returns them as function values.
Using the techniques captured above, you can create a simple calculator. Enter the following code in your interpreter:
A = Raw_input ("Number 1:") b = Raw_input ("Number 2:") print int (a) + int (b)
First, you capture two user input values and assign them to A and B, respectively. Then you convert them into integral types and add them together.
Why do you have to convert this step? Just because all the input in the interpreter is in the form of a string, and you want to add the value of the two integers.
If you don't convert these strings to integers, what do you think? Yes, the program will connect the string you entered, which is not what you want!
Import
Before we dive into the import, it is necessary to introduce a Python module. A module is a set of Python functions that you want to reuse in different programs. Importing a module is equivalent to removing all the code from a module and putting it into your own program so you can use them at any time, but you don't have to cut and copy, even one line of code!
There are a lot of modules in the Python community, but for now, you will only be exposed to the random modules.
To import the module, enter the following code in the interpreter:
Import Random
Once the module is imported, you can use it as follows:
Print random.randint (0, 100)
This will print 0 to 100 random integers; very intuitive stuff. So far you have learned a lot of knowledge, enough to rub them in a small program to practice what you have learned now!
Guessing games
This will be a reward for your hard work learning Python programming. You will create your own guessing game!
First, you need a better way to execute a program directly than in the interpreter.
In order to do this, you need to create a python file.
Mac
Create a python file under your Mac system and enter the following command in the terminal:
$ Touch guess.py$ open-t guess.py
This will use the ' Touch ' command to create an empty ' guess.py ' file and then open it with the ' open-t ' command, using the default text editor,
Once you have some content in your Python file, you can enter ' Python guess.py ' in the terminal to execute it.
Windows
Under Windows System, click the File button in the idle to find the new file. You will find a text editor in sight and you can enter your new program inside.
Click the File button again to select Save. Name the file name ' guess.py ' and save it where you want to save it.
Run your program, select Runrun in the menu, like this:
Game time!
Guessing games will generate a random number, and then in a loop, repeatedly ask the player their guesses. If the user guesses, end the loop, or the program will alert the user that their guesses are too high or too low and continue to ask for results until they are guessed.
Import randomnumber = random.randint (0, 100)
The above program will import the random number module, then generate a random number between 0 and 100 and store it in the variable numbers.
Next, you need to ask the players their answers. Add the code to the back of the program:
Guess = Raw_input ("Guess the number:")
This code, as you guessed, lets the user enter their answer and save it in the Guess variable. Remember, now that this variable is a string, you need to convert it to an integer type.
Add the following code to the program, which is appended to the code above:
guess_int = Int (guess)
This code converts a user-entered string to an integer and assigns a value to the Guess_int variable.
Below you need to compare the user guessing value and the size of the random number.
Add the following code at the end of the program:
If number > guess_int:print "Too low!" If number < Guess_int:print "Too high!" If number = = Guess_int:print "You got it!"
Click the Runrun module of the menu button or enter ' Python guess.py ' in the terminal to run the program, and when the program prompts you, enter a number. What happened? After you enter a number, the program displays the results on the screen and then stops. Oh!
You want the program to loop through your results until you guess. You need to add this function with a running variable.
running = True
Running will be used in the while loop to control the loop of your program. When the user enters the correct answer, the program assigns the running variable a value of false and the while stops.
Add the following code before you let the user enter the result:
While running:guess = Raw_input ("Guess the number:") ... etc
Below, indent the remaining code to the same layer so that the while loop recognizes that they are blocks of code in the loop.
Finally, you need to add a statement that assigns the running value to False when the user wins:
If number = = Guess_int:print "You got it!" Running = False
Make sure that the two lines of code below the If are indented two levels.
Run your program and try again now. How many times do you need to guess the right answer?
Your final program looks like this:
Import randomrunning = Truenumber = Random.randint (0, +) while running:guess = Raw_input ("Guess the number:") gues s_int = Int (guess) if number > Guess_int: print "Too low!"? If number < guess_int: print "Too high!" if Number = = Guess_int: print "You got it!" Running = False
Congratulations-you've written your first Python program. It's not that hard, is it?
From here, to where?
Now that you have completed the new Python tutorial, I bet you will be eager for a challenge. Try adding the following functionality to your program:
- Guess Count Statistics
- Larger random number generation range
- A computer-controlled game opponent
If you want to make a slightly more complicated game, see my other Tutorial: Beginning game Programming for teens with Python