பாடம் 3 / 6 · Modules, Standard Library · படிக்க 2 min · புதுப்பிக்கப்பட்டது
math, random
Built-in number உதவிகள், math module, random-ஆ தேர்ந்தெடுக்கிறது.
Built-in, import தேவையில்ல
print(abs(-7), pow(2, 5), divmod(17, 5))
print(round(7.456, 1), min(4, 9, 2), max([3, 8, 1]))
7 32 (3, 2)
7.5 2 8
math module
import math
print(math.ceil(4.1), math.floor(4.9))
print(math.sqrt(2))
print(math.pi)
print(math.gcd(12, 18), math.factorial(5))
print(math.isclose(0.1 + 0.2, 0.3))
5 4
1.4142135623730951
3.141592653589793
6 120
True
ceil எப்பவுமே மேல round பண்ணும், floor கீழ. Floats-ஐ compare பண்ண சரியான வழி math.isclose() — 0.1 + 0.2 == 0.3 False-ன்னு ஞாபகம் வெச்சுக்குங்க.
random module
import random
print(random.randint(1, 6)) # a dice roll: 1 to 6, both included
print(random.random()) # a float from 0 up to 1
print(random.choice(["idli", "dosa", "poori"]))
cards = [1, 2, 3, 4, 5]
random.shuffle(cards) # shuffles the list itself
print(cards)
print(random.sample(range(1, 50), 6)) # 6 different numbers
ஒவ்வொரு தடவையும் output மாறும் — அதுதான் நோக்கம், அதனால இங்க நிலையான output காட்டல. range() மாதிரி இல்லாம, randint(1, 6) 6-ஐயும் சேர்க்கும்.
Note
முதல்ல random.seed(42) கூப்பிட்டா ஒவ்வொரு தடவையும் அதே "random" எண்கள் வரும் — program-ஐ test பண்ண உதவும். Passwords, security tokens-க்கு secrets module use பண்ணுங்க; random design-படியே ஊகிக்கக்கூடியது.
random.randint(1, 3) என்ன தரலாம்?
இப்போ இதை செஞ்சு பாருங்க
- எண் ஊகிக்கிற game எழுதுங்க: computer 1-100-ல ஒண்ணை தேர்ந்தெடுக்கும், நீங்க கண்டுபிடிக்கிற வரைக்கும் "higher" இல்லன்னா "lower"-ன்னு சொல்லும்.
- 600 தடவை dice உருட்டுற மாதிரி simulate பண்ணி, ஒவ்வொரு முகமும் எத்தனை தடவை வருதுன்னு எண்ணுங்க.
- User type பண்ற radius-க்கு வட்டத்தோட பரப்பளவை 2 இடத்துக்கு round பண்ணி கண்டுபிடிங்க.
Create a free account to save your progress, or sign in.