python循环练习

1、打印5以内不重复的三位数

count=0
for i in range(1,5):
for j in range(1,5):
    if i == j:
        continue
    for p in range(1,5):
        if i == p or j == p :
            continue
        count+=1
        print("%d%d%d " %(i,j,p))
        print("%d" %count)

2、求最小公倍数和最大公约数

while True:
a=int(input("please input first num:"))
b=int(input("please input second num:"))
Min=min(a,b)
Max=0
if Min == 0 :
    print("no gong yue shu")
else:
    for i in range(1,Min+1):
  	      if a % i ==0 and b % i == 0:
            Max =  i

        else:
            continue
print("zui da gong yue shu wei:%d" %Max)
print("zui da gong bei shu wei:%d" %(a*b/Max))

3、猜数游戏

import random
i = 0
count = 0
while i < 100:
    Random = random.randint(1, 100)
    num = int(input("please input a num:"))
    num = 10
    if num > Random:
        i += 1
        pass
    elif num < Random:
        i += 1
        pass
    else:
        count += 1
        i += 1
print (count)
### Python 循环练习题目 #### For Loop 练习 1. **打印乘法表** 编写一段程序来打印九九乘法表。 ```python for i in range(1, 10): for j in range(1, i + 1): print(f"{i}*{j}={i * j}", end=" ") print() ``` 2. **计算列表元素总和** 给定一个整数列表,使用 `for` 循环计算这些数字的总和并输出结果[^1]。 ```python numbers = [1, 2, 3, 4, 5] total_sum = 0 for num in numbers: total_sum += num print(total_sum) ``` 3. **字符串反转** 接收用户输入的一串字符,利用 `for` 循环实现该字符串倒序排列后的输出。 ```python input_string = input("Enter a string:") reversed_string = "" for char in input_string: reversed_string = char + reversed_string print(reversed_string) ``` #### While Loop 练习 1. **猜数字游戏** 创建一个小游戏,在其中随机生成一个介于1100之间的整数让玩家猜测。如果玩家猜错了,则提示太高或太低;如果猜对了则结束游戏,并显示尝试次数。 ```python import random number_to_guess = random.randint(1, 100) attempts = 0 while True: try: guess = int(input("Guess the number between 1 and 100: ")) attempts += 1 if guess < number_to_guess: print("Too low!") elif guess > number_to_guess: print("Too high!") else: print(f"Congratulations! You've guessed it after {attempts} tries.") break except ValueError: print("Invalid input, please enter an integer value.") ``` 2. **斐波那契序列** 通过 `while` 循环生成指定长度的斐波那契数列。 ```python length_of_fibonacci_series = int(input("Enter length of Fibonacci series:")) a, b = 0, 1 count = 0 fibonacci_series = [] while count < length_of_fibonacci_series: fibonacci_series.append(a) nth = a + b # 更新值 a = b b = nth count += 1 print(f"Fibonacci sequence:{fibonacci_series}") ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值