From entry to prison-operator and branch structure (2)

Getting started three day

There are two types of loops in python: for loops and while loops

1.for loop
for variable in sequence:
loop body

Description:
a.for/in keywords, fixed writing
b. Variables, arbitrary variables, generally write a new variable name
c. Sequence of container data types in python, for example: string, list, tuple, set, iterator, Generator, range, etc.
D. Colon: Fixed writing
e. Loop body and for keep one or more statements indented:
Loop body is the code block that needs to be executed repeatedly.
Execution process:
Let variables get values ​​in sequence, one by one Fetch, until fetched: execute the loop body every time a value is fetched.
(The number of for loops is the number of elements in the sequence)

Usage of while loop
while True:
the operation that needs to be repeated.
The condition for the end of the if loop:
break



# 执行5次'hello'
for i in 'abcde':
    print(i, 'hello')

# range(N)     产生一个 0 ~ N-1 的数字序列:0,1,2,3,...,N-1
# range(x,y)   产生一个 x ~ y-1 的数字序列:x,x+1,x+2,...,y-1
#              (x,y都是整数,x < y)
# 打印10次‘hello’

for i in range(0, 10):
    print(i, 'hello')

# range(x,y,step)  step(步长),控制每次增加的值,默认是1

for i in range(0, 10, 3):
    print(i, 'hello')  # '3 hello' "6 hello"'9 hello'

# 产生100到1所有的数字对应的数列
for i in range(100, 0, -1):
    print(i)

for i in range(-100, 0):
    print(-i)

# 求1+2+3~+100的和
sum = 0
for i in range(0, 101):
    sum += i
    print(sum)

# 统计0~100中能被3整除的偶数的个数
# 方法一
count = 0
for i in range(0, 101, 3):
    if i % 2 == 0:
        count += 1
print(count)

# 方法二
count = 0
for i in range(0, 101, 6):
    count += 1
print(count)

# 练习1:求1000以内能被7整除但是不能被3整除的数的和

sum = 0
for i in range(0, 1000, 7):
    if i % 3 != 0:
        sum += i
print(sum)

# 练习2:统计1000以内十位数加上个位数的和等于5的数的个数

sum1 = 0
for i in range(0, 1000):
    if (i % 100 // 10) + (i % 10) == 5:
        sum1 += 1
print(sum1)


sum = 1
while sum != '0':
    sum = input('请输入: ')

print('循环结束')

# 九九乘法表
b=0
for x in range(1, 10):
    for y in range(1, x+1):
        print(y, '*', x, '=', x * y,end="  ",sep='')
    b+=1
    print('\n',b, sep=" ")
    
    

while loop
Syntax:
while conditional statement:
loop body

Explanation:
while-keyword; fixed writing
conditional statement-any expression that has a result except assignment statement
Colon:-fixed writing
loop body-and while one or more statements
that maintain an indentation loop body needs to be executed repeatedly Code
execution process:
first judge whether the conditional statement is True, execute the loop body if it is True,
and then judge the conditional statement after executing the loop body...
until the result of the judgment conditional statement is False, the entire loop body will end

The choice of for loop and while
Use for loop:
traverse the sequence (take out the elements in the sequence one by one) to
determine the number of cycles

Use while loop:
infinite
loop, the number of loops is uncertain

continue and break can only be used in the loop body to
end a loop
if continue is encountered when the loop body is executed, then the current loop borrows directly into the next loop

break ends the entire loop.
If break is encountered when executing the loop body, then the entire loop ends

‘’’

Use of continue (skip the current loop and execute the next one)

randint (m,n) Generate a random integer from m to n
Randomly generate a number from 0-100: num, the user keeps inputting the number until the input value
is equal to the generated random number and the game is over

 count = 0
for i in range(10):
    if i % 3 == 0:
        continue
    count += 1
print(count)

print('欢迎来到猜数字游戏....................')
num = randint(0, 100)
a=0
while True:
    a+=1
    num1 = int(input('请输入一个10以内的整数:'))
    print('第',a,"次")
    if num == num1:
        print('恭喜恭喜猜对了也没有奖励') 
      	break
    elif num1 < num:
        print('猜小了')
    else:
        print('猜大了')
print("游戏结束")

Basic questions

  1. Print according to the range of grades entered 及格or 不及格.

    grade = int(input('请输入你的成绩: '))
    if grade < 60:
        print("爪巴爪巴,不及格")
    else:
        print('及格')
    
  2. Print according to the entered age range 成年or 未成年if the age is not within the normal range (0~150) 这不是人!.

    age = int(input('请输入你的年龄: '))
    if 0 <=  age < 18:
        print("爪巴爪巴,未成年!")
    elif 18 <= age <= 150:
        print('成年了!')
    else:
        print('老妖怪')
    
  3. Enter two integers a and b. If the result of ab is odd, the result will be output, otherwise a prompt message will be output a-b的结果不是奇数.

    a=int(input('请输入整数: '))
    b=int(input('请输入整数: '))
    if (a-b) & 1 :
        print(a-b,'是奇数')
    else:
        print("结果不是奇数")
    
  4. Use the while loop to output all multiples of 3 from 0 to 100.

    num = 100
    while num >= 0:
        if num % 3 == 0:
            print(num)
        num -= 1
    
  5. Use the while loop to output all the even numbers from 0 to 100.

    num = 100
    while num > 0:
        if not(num & 1):
            print(num,'是偶数')
        num -= 1
    

Advanced questions

  1. Use 1*2*3*4*...*10the result of the loop calculation .

    count=1
    for i in range(1,11):
        count *= i
    print(count)
    
  2. Count the number of numbers within 100 whose single digit is 2 and divisible by 3.

    sum=0
    for i in range (0,101,3):
        if i % 10 == 2:
            sum+=1
    print(sum,i)
    
  3. Enter any positive integer, how many digits is it?

    注意: 这儿不能使用字符串,只能用循环

    sum = int(input("请输入一个正整数: "))
    a=0
    whlie True:
    	if sum //(10**a) != 0:
    		a+=1
    	else:
    		break
    print(a)
    
    
    num = int(input("请输入一个正整数: "))
     a=0
     while True:
     	num //= 0
     	a+=1
     	if num==0:
     		break
     print(a)
    
    
    
  4. Print out all the daffodil numbers. The so-called daffodil number refers to a three-digit number whose square sum is equal to the number itself. For example: 153 is

    ⼀ a water resistant number Xianhua, because 1³ + 5³ + 3³equal to 153.

    for i in range(100,1000):
        if (i // 100)**3+(i%100//10)**3+(i%10)**3==i:
            print("水仙花数是:",i)
    

Challenge

  1. Determine whether the specified number is a prime number (a prime number is a prime number, that is, a number that cannot be divisible by other numbers except 1 and itself)
num= int(input("请输入一个数:"))
if num != 0:
    for i in range(2,int(num**0.5)+1):
        if num % i==0:
            print("不是质数")
            break
    else:
        print('是质数')
else:
    print('不是质数')
  1. Find the value of the nth number in the Fibonacci sequence: 1, 1, 2, 3, 5, 8, 13, 21, 34... (Here n can be any positive integer, which can be determined by input)
num = int(input("请输入一个数:"))
a1 = 1
a2 = 1
for i in range(1,num):
    a1, a2 = a2, a1+a2
print(a1)
  1. Output 9*9 formulas. Program analysis: Considering the rows and columns, a total of 9 rows and 9 columns, i control row, j control column.

    for i in range(1,10):
        for j in range(1,i+1):
            print(j,'*',i,'=',j*i,end='  ',sep='')
        print('\n')
    
  2. This is the classic "100 horses and 100 dans" problem. There are 100 horses, 100 dans, 3 big horses, 2 middle horses, 2 small horses, 1 dan. There are big, medium, How many ponies? (You can directly use the exhaustive method)

bd = 100
n = 0
m = 0
for big in range(0, 100 // 3 + 1):
    n += 1
    print('big第', n, '次循环')
    for mid in range(0, 100 // 2 + 1 - big):
        sm = 100 - big - mid
        m += 1
        print("mid第", m, "次循环")
        if big * 3 + mid * 2 + sm * 0.5 == bd:
            print('大马:', big, '中马:', mid, "小马:", sm)

Guess you like

Origin blog.csdn.net/weixin_44628421/article/details/108789235