程序员文章、书籍推荐和程序员创业信息与资源分享平台

网站首页 > 技术文章 正文

Python基础 :循环、范围和代码块

hfteth 2025-02-10 12:34:50 技术文章 12 ℃



循环:

只要满足特定条件,循环就用于重复执行代码块。Python 中的循环主要有两种类型:for 循环和 while 循环。

1.for循环

for 循环用于迭代序列(例如列表、元组、字典、集合或字符串)。

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

2.while循环

只要给定条件为 true,while 循环就会重复执行代码块。

count = 0
while count < 5:
    print(count)
    count += 1

Loop Control 语句

Python 还提供了控制语句来管理循环流:

  • break:提前终止循环。
  • continue:跳过当前迭代的循环内其余代码,并移至下一个迭代。
  • else:当循环条件不再为 true 时执行一次代码块(在 forwhile 循环中很有用。

休息

for number in range(10):
    if number == 5:
        break
    print(number)
#(start: SupportsIndex, stop: SupportsIndex, step: SupportsIndex = ..., /) -> range

for num in range (1, 10, 3):   
    print(num)

continue

for number in range(10):
    if number % 2 == 0:
        continue
    print(number)

elsefor 循环:

for number in range(5):
    print(number)
else:
    print("Loop ended")

项目 1:平均身高

student_heights =  input("What is the student heights\n").split()   

for n in range(0, len(student_heights)):
    student_heights[n] = int(student_heights[n])

total_height = 0
for height in student_heights:
    total_height += height
print(f"total_height = {total_height}")


number_of_student = 0
for student in student_heights:
    number_of_student += 1

print(f"number of student = {number_of_student}")

average_height = round(total_height/number_of_student)
print(f"average_height = {average_height}")



>>

What is the student heights
120 130 152 258 58 56
total_height = 774
number of student = 6
average_height = 129
PS C:\Users\Hp\Desktop\Python>

项目 2:最高分

student_score = input("Enter the marks - ").split()

for n in range (0, len(student_score)):
    student_score[n] =  int(student_score[n])

highest_score = 0

for score in student_score:
    if score > highest_score:
        highest_score = score


print(f"The highest score is {highest_score}")


>>

Enter the marks - 25 268 258 65 2041  6228 255 2 44 
The highest score is 6228

项目 3:计算数字,1+2+3+4.......

first = int(input("What is first value - "))
second = int(input("What is second value - "))


total = 0

for num in range (first, second +1):
    total += num

print(f"The total is {total}.")

>>

What is first value - 1
What is second value - 50
The total is 1275.

项目 4:计算偶数,2+4+6+8....

target = int(input(" Enter number between 1 to 100 -  "))

even_num = 0

for number in range(2, target+1, 2):
    even_num += number

print(f"The total is {even_num}")

   

>>

Enter number between 1 to 100 -  20
The total is 110

项目 5:Fizz Buzz 游戏

FizzBuzz 游戏是一个简单的编程挑战,通常用于教授基本的控制结构和逻辑。规则是:

  1. 打印从 1 到给定限制的数字。
  2. 对于 3 的倍数,请打印 “Fizz” 而不是数字。
  3. 对于 5 的倍数,请打印 “Buzz” 而不是数字。
  4. 对于是 3 和 5 的倍数的数字,请打印 “FizzBuzz” 而不是数字。
number =  int(input("Enter number from 1 t0 100 - "))

for num in range(1, number+1):
    if num % 3 ==0 and num % 5 == 0:
        print("fizzBizz")

    elif num % 3 == 0 :
        print("Fizz")

    elif num% 5 == 0 :
        print("Buzz")
    
    else:
        print(num)



   >>

Enter number from 1 t0 100 - 15
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
fizzBizz

项目 6:密码生成器:

import random

print("-----Welcome to Password Generator!------")

letters =  int(input("How many letter you want?\n"))
symbols =  int(input("How many symbols you want?\n"))
numbers =  int(input ("How many number you want?\n"))
 
password_list = []

    # Generate letters
    #You can use "+=" or ".append"

for _ in range(letters):
    password_list.append(random.choice('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'))
    
    # Generate symbols

for _ in range(symbols):
    password_list += (random.choice('!@#$%^&*()-_=+[{]}\\|;:\'",<.>/?'))

    # Generate numbers

for _ in range(numbers):
    password_list += (random.choice('0123456789'))

    # Shuffle characters

random.shuffle(password_list)

    # Combine characters into password

password = ''.join(password_list)

print(f"Your password is: {password}")




>>

-----Welcome to Password Generator!------
How many letter you want?
10
How many symbols you want?
3
How many number you want?
5
Your password is: VjVHE18SWJ35d?3@^G

Tags:

最近发表
标签列表