標籤:put ota 經典 python rand 方法 als int 計算
#比較大小#方法1from math import maxa = (‘請輸入第一個整數:‘)b = (‘請輸入第二個整數:‘)c = (‘請輸入第三個整數:‘)d = max(a, b, c)print(‘其中最大的是%f:‘ %d)
#如何交換兩個變數值 a, b = b, a‘‘‘temp = aa = b b = temp‘‘‘a = int(input(‘a =‘))b = int(input(‘b =‘))c = int(input(‘c =‘))‘‘‘if a > b: a, b = b, aif b > c: b, c = c, bif a > b: a, b = b, aprint(a, b , c)‘‘‘(a, b) = a > b and (b, a) or (a, b)(b, c) = b > c and (c, b) or (b, c)(a, b) = a > b and (b, a) or (a, b)print(a, b, c)
#判斷一個數是否是質數a = int(input(‘請輸入一個數:‘))is_prime = Truefor b in range(2, a): c = a % b if c == 0: is_prime = False breakif is_prime: print(‘%d他是質數!‘ % a)else: print(‘%d他不是質數‘ % a)
#九九乘法表for row in range(1, 10): for col in range(1, row + 1): print(‘%d*%d=%d‘ % (row, col, row * col), end=‘\t‘)#定位字元 print()#換行用,
#百元百雞,公雞5元一隻,母雞3元一隻,小雞一元3隻,問有一百元,買一百隻雞,有幾種買法for x in range(21): for y in range(34): #for z in range(0, 100, 3): z = 100 - x - y if 5 * x + 3 * y + z // 3 == 100 and z % 3 == 0: print(x, y ,z)
print(0.1 + 0.2 + 0.3)print(0.3 + 0.2 + 0.1)#由於浮點數標記法的問題,#在實際開發的過程中請不要做浮點數的==和!=運算.#實在要用,一定要先轉換成int再計算,算完再轉換回去.
#找出 1000 以內的水仙花數。from math import powfor num in range(1000): a = num // 100
#經典的五人分魚問題fish = 1while True: totle = fish
#經典的Craps賭博遊戲from random import randintgo_on = Falsenum1 = randint(1, 6)num2 = randint(1, 6)total1 = num1 + num2print(‘玩家搖出了%d‘ % total1)if total1 == 7 or total1 == 11: print(‘玩家勝‘)elif total1 == 2 or total1 == 3 or total1 == 12: print(‘玩家輸‘)else: go_on = Truewhile go_on: num1 = randint(1, 6) num2 = randint(1, 6) total2 = num1 + num2 print(‘玩家搖出了%d‘ % total2) if total2 == total1: print(‘玩家勝!‘) go_on = False elif total2 == 7: print(‘玩家輸!‘) go_on = False
is_enough = True for _ in range(5): if (total - 1) % 5 == 0: total = (total - 1) // 5 * 4 else: break is_enough = False if is_enough: print(fish) break fish += 1
b = num // 10 % 10 c = num % 10 if num == pow(a, 3) + pow(b, 3) + pow(c, 3): print(‘%f是水仙花數!‘ %num)
#完美數from math import sqrtfor num in range(10000): sum = 0 for i in range(2, int(sqrt(num)) + 1): if num % i == 0: sum +=i if i != num // i: sum += num // i if num == sun + 1: print(‘%d是完美數‘ %num)
Python第一周習題集(二)