1. Fibonacci series
Fibonacci series, the first two items of the series are 1, and each item after is the sum of the first two items.
#!/usr/bin/env python3 a, b = 0, 1 while b < 100: print(b) a, b = b, a + b
The default print output will automatically wrap the line. If you do not want to wrap the line, you can replace the line break with another parameter end
print(a, end=' ')
2. Power series.
Write a program to calculate power series: e ^ x = 1 + X + x ^ 2 / 2! + x ^ 3 / 3! +... + x ^ n / N! (0 < x < 1).
#!/usr/bin/python3 x = float(input("Enter the value of x:")) n = term = 1 result = 1.0 while n <= 100: term *= x/n result += term n += 1 if term < 0.0001: break print("No of Times={} and Sum = {}".format(n, result))
3. Multiplication table
Print multiplication tables up to 10.
#!/usr/bin/env python3 i = 1 print('-' * 60) while i < 11 n = 1 while n <= 10: print("{:d}*{:d}={:d}".format(n, i, i * n), end=" ") n += 1 print() i += 1 print('-' * 60)
- print('-' * 60): a string repeated 60 times for output
4. Print asterisk
Print asterisks of various shapes
- Up right triangle
#!/usr/bin/env python3 n = int(input('Enter the number of rows:')) i = 1 while i <= n: print('*' * i) i += 1
- Right triangle down
#!/usr/bin/env python3 n = int(input('Enter the number of rows:')) i = n while i > 0: x = '*' * i y = " " * (n - i) print(y + x) i -= 1
- diamond
#!/usr/bin/env python3 n = int(input('Enter the number of rows:')) i = 1 while i < n: x = '*' * (2 * i - 1) y = " " * (n - i) print(y + x) i += 1 while i > 0: x = " " * (n - i) y = '*' * (2 * i - 1) print(x + y) i -= 1
5. Stick game
There are 21 sticks. The user selects 1-4 sticks, and then the computer selects 1-4 sticks. Whoever chooses the last stick will lose. (the total number of sticks selected by users and computers in one round can only be 5)
#!/usr/bin/env python3 sticks = 21 while True: print("Sticks left: ", sticks) sticks_token = int(input("Take sticks(1-4):")) if sticks == 1: print("Failed!") break if sticks_token >= 5 or sticks_token <= 0: print("Choose wrong number! continue:") continue print("computer took:", 5-sticks_token, "\n") sticks -= 5
Note: there is no doubt that you will lose. Ha ha!