Simple programming 0 Basics of Python Introductory guide _python

Source: Internet
Author: User
Tags variable scope

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. A task here can be a simple addition of two numbers, or a complex task like putting a spaceship into orbit!

In a program, the smallest component is called a statement (statement)--represents an instruction to a computer.

When you have finished your program, the compiler converts the code you write into machine code-the lowest level of the computer language. The machine code indicates that the CPU is working (central processing Unit), or CPU, where the bread contains steps such as loading a value or doing mathematical arithmetic.

If you've ever heard someone say, "I compiled my program," that means they've converted the code to machine code.

Why don't you 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 3c 5c 2a 2b 2a 5c 3c 5c 2a 2b 2a 5c 3c 5c
28 5c 2a 2b 2a 5c 3c 5c 2a 2b 2a 5c 3c 5c 2a 2b 2a 5c 3c 5c 2a 2b 2a 5c 3c 5c 2a 2b 2a
2a 5c 3c 5c 2a 2b 2a 5c 3c 5c 2a 2b 2a 5c 3c for the most-a-a-
00
00 00 00 00 00 00 00 (in) All of the "a" (+)) (+) (+)
00 00 00 00 00 00 00 00 00 00 00 00 in all of the "a" (+)). I '
6c 6c 6f 2c to 6f to the 00
    

   

It's obvious why you don't want to write machine code directly. But there are some people who are going to write machine code--the carrot and the cabbage.

We have overlooked a small problem above. Python is an interpreted language; you don't compile it directly into machine code, as we implied above.

In fact, Python uses a thing called an interpreter. An interpreter is another program that compiles code into something called binary code and then converts it to machine code when it runs. You'll learn more about the interpreter in a minute.

When you finally run the program, the machine code that you just compiled will be loaded into memory, and the CPU will read it and execute the program.

However, when you first learn to use Python programming, you don't need to fully understand how the compiler works internally, but you have to make sure that you have Python installed.
ready to start

If you're using a Mac, you're lucky--python is already pre-installed in the Mac. Using the Python interpreter in the Mac, open the * * Terminal * * (**terminal.app**), you can find it under the application/Tools folder, or enter it in the spotlight, like this:

After opening the terminal, enter the following instruction and press ENTER:

$ python

You will see results similar to the following:

Note: If you do not get the results above, copy the output to the forum, 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 windows!. On:]

First, visit the Python website download page in the browser.

The scrolling page skips over all Python 3.x.x versions, directly to Python 2.7.x. Download the Windows Installer package (Windows Installer), run, follow the instructions, and accept the default options.
Once the installation package is complete, you can start it up.

On Windows Vista or Windows 7, this starts:

1. Click on the Start menu in the lower left corner.
2. Click on 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 Start menu
2. Enter idle in the search box
3. Click 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 instruction at the command prompt in Windows and press ENTER:

Print "Hello world!"

Although it doesn't look like it, you've already finished your first Python program! When learning most languages, print Hello, world is considered a starting point.

The ' python ' command instructs the computer to print back characters on the screen-not on your printer! Notice the quotes on both sides of "Hello world", and anything in the quotation marks is considered a regular text and is not interpreted as an instruction.
Variable

Variables are a way to store data in your computer's memory; you will use them frequently in your programs. In some languages, variables have specific types that indicate which classes belong to those variables.

In Python, you don't need to declare the type of a variable. There is no need to pay attention to these details for the time being, and you will learn about this in later chapters of 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 to its class. Now, you don't need to enter this string in the program "Hello World", and instead, you can use the variable hello.

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 variable hello.

Variables can also be used to store numbers. Enter the following command in the interpreter:

x = 5
print x
y = ten
z = x + y
print Z

Note: From now on, you may want to enter a multiline statement, just enter a carriage return at the end of each line * *

First guess the above code will do some 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 at the core. As you learn this tutorial, you will become very familiar with variables.
Variable Type

You have encountered variables in the previous tutorial, but we did not introduce them carefully. Different variable types store different types of values.

Note: For all builtin types, check the official Python documentation

So far, you've only dealt with two basic types in Python: integer (' integers ') and string (' strings '), and you'll also encounter a Boolean type (' Boolean ') that you can use to store ' True ' or ' False '.

The following is a brief introduction to these variable types:

Integral type
An integer that is a whole number. The range of integers is 2147483648 to 2147483647 on a 32-bit machine and -9223372036854775808 to 9223372036854775807 on 64-bit machines.

You can simply enter a number like this to create an integral type without any quotes:

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 in quotation marks, just like the following:

Boolean type

The Boolean type represents true or false.

You create a Boolean type by using either True or false at the beginning of uppercase, and you do not need quotes, as follows:

' Isfoo = True '

There is no quotation mark on either side of the variable; If you enclose true in quotes, you create a string type!
string concatenation and integer addition

Python makes it easy to hook up two strings, which we also call string concatenation. You can use ' str () ' To convert an integer type to a string, and instead, you can use ' int () ' to convert a string to an integral type.

Enter the following instruction in your interpreter:

"1" + "1"
1 + 1
1 + int ("1")

The following explains what the above code does:

-The first statement connects two strings; the quotation marks ensure that the two digits are used 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 whether a condition is true and, if so, executes a piece of code. A conditional statement is usually the form ' value-operator-value ', which is usually compared to 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 of the common comparisons in Python

A = = B: #Checks If A and B are equal
a!= B: #Checks If A and B are not equal
a > B: #Checks if A is greater th A B
< b: #Checks If A is less than B
a >= B: #Checks if a are greater than or equal to B
a <= B: # Checks If a is less than or equal to B

The IF statement is in the following form:

If conditional:
 do_statements_here

Notice how the "execute some statements here" how the line is indented. This is how you declare blocks of code in Python. Each line in the same code block must indent the same tab or space with all the other lines, which is mandatory by language. In other words, do not mix tabs and spaces. Create an If statement and enter the following command in the interpreter:

To greet you is the mystery of the prompt ' ... '; this means that the interpreter waits 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 returns to the far left of the console. To enter a code block statement again, you only need to 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 = ten
y = ten
if x = =:
 print "x equals 10!"
if x = = y:
 print "x equals y!"

The first statement determines if x is equal to 10, and if so, print ' x equals 10! '. Another if statement determines if x equals Y, and if so, prints ' x equals y! ' `.
For loop

The For loop then iterates through the items in the list in Python 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 once assigns the number in the range to X. 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, once for each item in the list, the program prints 0 to 9 digits.
Function

A function is a reusable block of code that is used to complete a particular block of code. For example, you can write a function to add two numbers, or to print a string. You can define and invoke functions 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? See below for answers:

It will print "Hi" three times, because the for loop will call this Hello function three times.

The indented code block defines the statement you want to execute when you call the function. Because ' print ' Hi ' is the only indented statement in this function, it is also the only executed statement when the function is called, not the following lines.

You can call a function by typing a function name with a pair of parentheses at the end, as shown previously, ' Hello () ' calls the function you called above. Functions are somewhat similar to walled gardens: they cannot see the accidental world of their acres of three cents. This is called ' variable scope '. If you want a function to work with external data, you need to pass the data to the function.

Use ' parameters ' (arguments) to do this--no, no, no, the functions don't quarrel with each other (argue)!

A parameter is a variable that you pass to a function, and then the function can use the value of the parameter internally.

You can declare a function with a parameter as follows:

def add (A, b):
 print A + b

The function above 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 of the variable you passed in.

Take a look at the following example:

def add (A, b):
 print a + B
Add (1,2) # prints 3!

In the above example, ' Add (1,2) ' This statement sets a and B to 1 and 2 respectively. The function then prints the number of the two numbers you pass in. The example above prints the results--but what if you want to do something with this calculation? What if you want to add another 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 + B
print Add (2, 2) + 1

In the example above, your function adds up to two numbers as before, but the ' return ' statement returns two numbers and a function call statement.

This means that the above ' print ' statement gets the value of Add (2,2) and then adds 1, and finally gives you a 5 result.
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 is equal to false. The typical structure of a while loop is the following:

while (conditional):
 run_statement

Typically, a condition variable is updated during a loop run. Enter the following procedure in the interpreter to see this process:

x = 0 While
x <:
 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 to x 0
2. Check to see 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 value of ' X ' to 1

One thing to note when using a while loop is not to create a dead loop.

Enter the following program in the interpreter to see what the view loop looks like:

x = 0 while
True:
 print x
 x + 1

Wow, is the terminal crazy? Press CTRL + C to terminate the program.

What just happened? If you look closely, you will find the condition of the while loop, true can never turn false, so this code prints the number at the fastest speed the CPU can perform.

The story tells us: be careful when writing while loops, because the infinite loops in your code are not good for the real world!

It is possible to use true as a condition for a while loop, especially if you do not know how many times to cycle. But you need some tricks to get out of the loop.

Enter the following code in the interpreter:

x = 0 while
True:
 print x
 x + 1
 if x >:
  break

That's better! The code above prints 0 to 10 and exits. The technique used here is the break statement, which jumps straight out of the loop. For whatever reason, you can use this technique if you want to jump out of the for loop ahead of time.
capturing user input

One cool thing about Python is that it's easy to get input user input in text. 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 code above first lets you input, and once the user enters the answer to the question, the program assigns it to the name variable. When this process is complete, the program connects the contents of the string "Hello," and the variable name.

The Raw_input () function is a Python built-in function that finishes printing the input string from the console, captures the text entered by the user, and returns them as function values.

Using the technology that captures the input 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. And then you convert them into integers and add them together.

Why do we have to convert this step? Just because all the input in the interpreter is in a string, you want to add the value of 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 delve into the import, it is necessary to introduce Python's modules. A module is a set of Python functions that you want to reuse in different programs. Importing a module is equivalent to taking all the code out of a module and putting it in your own program so you can use them at any time, but you don't need to cut and copy, even if it's a line of code!

There are a large number of modules in the Python community, but for now, you will only be exposed to random number modules (random module).

To import a module, enter the following code in the interpreter:

Import Random

Once you have imported the module, you can use it as follows:

Print random.randint (0, 100)

This will print 0 to 100 random integers; something very intuitive. So far you have learned a lot, enough to rub them in a small program to practice the knowledge you have learned now!
Guessing games

It 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 the program directly than in the interpreter.

To do this, you need to create a python file.

Mac

Create the Python file under the 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 use the ' open-t ' command to open it using the default text editor,

Once you have some content in your Python file, you can type ' Python guess.py ' in the terminal to execute it.

Windows

Under Windows System, click the File button in idle to locate the new file. You will find a text editor that you can enter into your new program.

Click the File button again and choose Save. Name the file name ' guess.py ' and save it where you want to keep it.

Run your program and select Runrun in the menu, just like this:

Game time!

Guessing game will generate a random number, and then in a loop, repeatedly ask the players their guess results. If the user guesses, end the loop, or the program will remind the user whether their guesses are too high or too low and continue to ask the results until they are guessed.

Import random Number
= random.randint (0, 100)

The above program will import the random number module and then generate a random number from 0 to 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, like you guess, lets the user enter their answer and save it in the Guess variable. Remember, now this variable is a string, and you need to convert it to an integral type.

Add the following code to the program, which is appended to the code above:

guess_int = Int (guess)

This code converts the string entered by the user to an integral type and assigns the 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; When the program prompts you, enter a number. What happened? The program displays the results to the screen after you enter the number and then stops. Oh!

You want the program to circulate to ask you the results until you guess. You need to use a running variable to add this functionality.

running = True

Running is 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 to 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 rest of the 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 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 random
running = True number
= Random.randint (0) while
 
running:
 guess = Raw_input ("Guess the Number: ")
 
 guess_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've completed the new Python tutorial, I bet you're longing for a challenge. Try adding the following functionality to your program:

    • Guessing Times statistics
    • Larger random number generation range
    • A computer-controlled game opponent.

If you want to do a slightly more complex game, see my other Tutorial: "Beginning Game programming for teens with Python"

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.