python-Loop (while loop, for loop)

Source: Internet
Author: User

#循环, Traverse, iterate
# for Loop, while loop

See Data types
Type (name) int

Break no matter whether the loop is complete or not, end the loop immediately
Continue end this cycle and proceed to the next cycle

One, while loop

# while loop, must have a counter

# The loop is the code inside the repeating loop body

Count = 0

While count<10:

  Print (' Hello ')

  Count = count+1

eg

# Guess the number, if the big guess, the hint is too big, guess small, the hint is small, guessed right on the end
Import Random
num = Random.randint (1,100) # generates a random number
Count = 0
While count<7:
Guess = input (' Please enter the number you guessed: ')
guess = Int (guess)
If Guess>num:
Print (' Guess big ')
Continue
Elif Guess<num:
Print (' Guess small ')
Continue
Else
Print (' Congratulations on your guess right ')
Break #立即结束循环
Count = count+1
# if count==7:
Else
Print (' ran out of times ')

Second, for Loop

Import Random
num = Random.randint (1,100)
For I in range (3):
Guess = input (' Please enter the number you guessed: ')
guess = Int (guess)
If guess > num:
Print (' Guess big ')
Continue
Elif Guess < num:
Print (' Guess small ')
Continue
Else
Print (' Congratulations on your guess right ')
Break # immediate End loop
Else
Print (' ran out of games ')

For loop class Practice-Login with the code as follows:


# Number of Errors 3 times
For I in range (3):
Username = input (' Please enter your user name: ')
PWD = input (' Please enter your password: ')
If username = = ' Nhy ' and pwd = = ' 123456 ':
Print (' Welcome, login Successful! ‘)
Break
Else
Print (' Account/Password Error! ‘)
Continue
Else
Print (' The number of errors has been exhausted, please try again tomorrow! ‘)

python-Loop (while loop, for loop)

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.