Python learning [while] loop

Source: Internet
Author: User

Syntax for While loop:

While conditional statement

Loop code block

# #break Interrupt this layer while loop

# #跳出本次循环进入下一次循环

Else

# #循环结束后可以打印的内容

Here are a few small exercises:

1. Use the while loop to determine whether the number entered is prime.

Num=int (Input ("Please enter a number"))
M=1
If Num==0 or num==1:
Print ("Please enter a number greater than 1")
Else
While M<num-1:
M+=1
If num%m==0:
Print ("This number is not prime")
Break
Else
Print ("This number is prime")
2. Guess the number game:

The Li-While statement writes out a guess?? 's Game:
Set an ideal number, such as: 66, let the household lose the number, if the 66?, the guess is displayed
The result of, if? 66?, the result of the guess is displayed, and only equals 66, showing the Guess results
Correct, and then exit the loop.

num=66

While True:
Type = input ("Please enter the number you guessed:")
Type=int (Type)
If Type >66:
Print ("The number you entered is too large")
Elif type<66:
Print ("The number you entered is too small")
Else
Print ("The number you entered is correct")
Break
3.
All numbers of the 1-100 are calculated and
Count=0
Sum=0
While count<100:
Count+=1
Sum+=count
Print (sum)

4. All odd numbers in the output 1-100
‘‘‘
# count=1
# Sum=1
# while count<99:
# count+=2
# Sum=count+sum
# Print (SUM)

5. All even numbers in the output 1-100
‘‘‘
# count=0
# sum=0
# while COUNT<100:
# count+=2
# Sum+=count
# Print (SUM)
6. Ask 1-2+3-4+5 ... The and of all numbers of 99.
‘‘‘
Count1=1
Sum1=1
While count1<99:
count1+=2
Sum1+=count1
Print (SUM1)
Count2=0
Sum2=0
While count2<100:
count2+=2
Sum2+=count2
Print (SUM2)
Print (SUM1-SUM2)

Python learning [while] loop

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.