Python basics 2-basic control statements

Source: Internet
Author: User

What needs to be done to basically access every language: 1. print a "Hello world! "2. Understand basic data types. 3. Learn control statements.

When we learn control statements, we generally cannot do without if, for, while, switch (case ). In this article, we will make a simple introduction to the basic control statements of python, where we use if while to make a classic "Guess digital game", if for to make a "output perfect number ".
Before that, if you are familiar with c/c ++ and use {} as the block, you must note that python uses indentation to block the block, however, it is acceptable to get used to it for a period of time. The advantage is that the Code is basically the same format, which is called simple and easy to read.

The trouble of indentation is a concern for beginners.

a=3b=5if a>b:   print aelse:   print b print a+b  
The above code outputs the largest of a and B, and finally Outputs a + B. It is noted that the last row of print a + B does not have a ceiling, so the error occurs and the indentation problem occurs.

After that, let's take a look at the benefits of indentation. If you have written something similar to C/C ++

Have you ever committed this?Error

# Include <iostream> # include <cstdio> # include <cstring> using namespace std; int main () {int a = 160, B = 170; // Case 1, when a is larger than B, if a is odd, a is output; otherwise, an Error is output. if (a> B) if (a & 1) cout <; else cout <"Error"; else cout <B; // Case 2: When a is larger than B, if a is odd, output, when B Outputs a less than a, this is the so-called hanging else // The second case of this program is no output, not 170. In python, this problem will not occur! If (a> B) if (a & 1) cout <a; else cout <B; return 0 ;}


 
 

Okay. This article mainly describes the basic control statements.

First of all, the output a and B producers written by everyone, in the opinion of pseudocode, are

if a>b   print aelse   print bendif
Here we use the most basic if Condition Statement and the use of if in python.

If expression: # Note ":". if it is missing, it will not work. if_suit is a common small error during script writing.
Example

age=19if age>18:     print 'You are  adult!'
Result

You are  adult!

Of course, if yes, else

if expression:      if_suitelse:    else_suit
Example

IQ=250if IQ>250:    print "Your IQ is very high!"else:    print "Normal guy!"

Result

Normal guy!

Else if is not enough, but elseif of python is the same as elfi of shell.

Example

IQ=250if IQ>250:    print "Your IQ is very high!"elif IQ==250:    print "You are 250!" else:    print "Normal guy!"
Result

You are 250!

(The content of the above example is for entertainment only. Don't be careful. The foundation is always boring. You can have fun with yourself !)

NextWhileThe basic usage is

while expression:        while_suit
Exmple

cnt=0while cnt<5:    print cnt    cnt+=1
Result

01234


In addition, for the while clause, we must also mention break. break breaks the cycle, which is basically the same as c ++. For example

cnt=1while cnt<10:    print cnt    if cnt%2==0:         break;    cnt+=1
The result is

12
Guess numberEveryone knows that a random number is set as the answer (you can also manually set it), and then enter a number to identify the system. If the number is equal, the system jumps out of the loop.

Code

#!/usr/bin/env python# coding=utf-8import randoma=1b=1000ans=random.randint(a,b)cnt=0while True :    num=int(raw_input('Guess the number:'))    cnt+=1    if num==ans:          print "Great!%d is the answer!"%num          print "You guessed %d times"%cnt          break     elif num>ans:          print "%d is greater than the ans"%num     else:          print "%d is less than the ans"%num


Random is used to generate a random number between a and B. 

Result

Guess the number:00 is less than the ansGuess the number:10001000 is greater than the ansGuess the number:500500 is greater than the ansGuess the number:250250 is greater than the ansGuess the number:125125 is less than the ansGuess the number:185185 is greater than the ansGuess the number:155155 is less than the ansGuess the number:170170 is less than the ansGuess the number:177177 is greater than the ansGuess the number:173173 is greater than the ansGuess the number:172172 is greater than the ansGuess the number:171Great!171 is the answer!You guessed 12 times

This second point is still good ^ _ ^. programmers who know the second point are very valuable. Looking back to the Guangdong Provincial competition in May, we died on a second point, and there were too many penalties! Sorry.

For

In fact, the for of python is different from that of c ++. It is more like for each iteration. The basic usage is:

for iterating_var in sequence:   statements(s)

For example.

ProLan=['C','CPP','JAVA','PYTHON']for item in ProLan:       print item
The output result is as follows:

CCPPJAVAPYTHON
If you do not want to wrap the line, add "," to the end of the item ","

That is

ProLan=['C','CPP','JAVA','PYTHON']for item in ProLan:       print item,
The result is

C CPP JAVA PYTHON
What else do we want to do?

for(int i=0;i<100;i++)    printf ("%d ",i);

This is the case in python.

for i in range(0,100):       print i,
So far, we can do things and output 0 ~ 10000 Perfect number

First, let's take a look at the perfect number. The perfect number is the sum of all non-essential factors. For example, 6 is a perfect number, and 6 is a non-essential factor of 1, 2, 3, 1 + 2 + 3 = 6.

We can use for and if to implement

A very rough method is not an algorithm.

#!/usr/bin/env python# coding=utf-8for i in range(1,10000):    fact=0    for j in range(1,i):        if i%j==0:            fact+=j    if fact==i:        print i

A slightly improved nlogn. Everyone knows this.

#!/usr/bin/env python# coding=utf-8import mathfor i in range(1,10000):    fact=1    end=int(math.sqrt(i))+1    for j in range(2,end):        if i%j==0:            fact+=j            if j*j!=i:                fact+=i/j;    if fact==i:        print i

Result

16284968128

In addition, it is worth mentioning that For... else, While... else

For those who write C/C ++ in this habit, it is very "fresh "! But I don't think it should be good ~ Write more to avoid confusion! Dear user!

For example

for i in range(1,10):   if i&1:       breakelse:   print "for-else"
In this way, the break will not go through else, that is, the normal end will go through else. In fact, I understand that

For I in range (1, 10)

// Do somting

If I = 10

// Do else

That is, if

for i in range(1,10):   if i>250:       breakelse:   print "for-else"
This will output

for-else
The same applies to while... else.

At this point, the control statements are basically finished.

There is no case in python 2.x. I don't know whether it is good or bad. We can only use

If... elif... else is replaced!

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.