import sys, os, ast, time, json, random, builtins, traceback, linecache, re
class _CoNeedInput(BaseException):
def __init__(self, prompt=''):
BaseException.__init__(self, prompt)
self.prompt = prompt
class _CoStop(BaseException):
def __init__(self, why=''):
BaseException.__init__(self, why)
self.why = why
_co_state = {'inputs': [], 'pos': 0, 'deadline': 0.0, 'limit': 6.0, 'chars': 0, 'mpl': False}
_CO_MAX_CHARS = 150000
class _CoWriter:
def __init__(self, kind):
self.kind = kind
self.encoding = 'utf-8'
def write(self, s):
if not isinstance(s, str):
s = str(s)
st = _co_state
st['chars'] += len(s)
if st['chars'] > _CO_MAX_CHARS:
raise _CoStop('output')
_co_emit(self.kind, s)
return len(s)
def writelines(self, lines):
for line in lines:
self.write(line)
def flush(self):
pass
def isatty(self):
return False
def readable(self):
return False
def writable(self):
return True
def seekable(self):
return False
def _co_input(prompt=''):
p = '' if prompt is None else str(prompt)
if p:
sys.stdout.write(p)
st = _co_state
if st['pos'] < len(st['inputs']):
v = st['inputs'][st['pos']]
st['pos'] += 1
_co_emit('in', v + '\n')
return v
raise _CoNeedInput(p)
def _co_tick():
if time.time() > _co_state['deadline']:
raise _CoStop('time')
class _CoTx(ast.NodeTransformer):
"""Adds a time-limit check at the top of every loop body."""
def _loop(self, node):
self.generic_visit(node)
call = ast.Expr(value=ast.Call(func=ast.Name(id='__co_tick__', ctx=ast.Load()), args=[], keywords=[]))
ast.copy_location(call, node)
ast.fix_missing_locations(call)
node.body.insert(0, call)
return node
visit_While = _loop
visit_For = _loop
visit_AsyncFor = _loop
def _co_syntax(e):
out = sys.stderr
out.write('%s on line %s\n' % (type(e).__name__, e.lineno if e.lineno else '?'))
if e.text:
out.write(' ' + e.text.rstrip('\n').rstrip('\r') + '\n')
if e.offset:
out.write(' ' + ' ' * max(0, int(e.offset) - 1) + '^\n')
out.write('%s\n' % (e.msg or ''))
def _co_tb(exc):
_co_state['chars'] = 0
tb = exc.__traceback__
if tb is not None:
tb = tb.tb_next
txt = ''.join(traceback.format_exception(type(exc), exc, tb))
txt = re.sub(r' File "<student>", line (\d+), in <module>\n', r' Line \1 of your program\n', txt)
txt = re.sub(r' File "<student>", line (\d+), in ([^\n]+)\n', r' Line \1, inside \2\n', txt)
txt = txt.replace('Traceback (most recent call last):', 'Your program stopped with an error:')
sys.stderr.write(txt)
def _co_files():
out = []
try:
for name in sorted(os.listdir('.')):
if name.startswith('.'):
continue
if os.path.isfile(name):
out.append({'name': name, 'size': os.path.getsize(name)})
except Exception:
pass
return out
def _co_read_file(name):
try:
with open(name, 'r', errors='replace') as f:
return f.read()
except Exception as e:
return 'Could not read %s: %s' % (name, e)
def _co_clear_files():
n = 0
for info in _co_files():
try:
os.remove(info['name'])
n += 1
except Exception:
pass
return n
def _co_mpl():
if _co_state['mpl']:
return
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import io, base64
def _show(*a, **k):
nums = plt.get_fignums()
if not nums:
sys.stderr.write('Nothing to show - draw something before calling plt.show().\n')
for num in nums:
fig = plt.figure(num)
buf = io.BytesIO()
fig.savefig(buf, format='png', dpi=108, bbox_inches='tight', facecolor='white')
_co_emit('img', base64.b64encode(buf.getvalue()).decode('ascii'))
plt.close('all')
plt.show = _show
_co_state['mpl'] = True
def _co_run(src, inputs_json, limit, seed):
st = _co_state
try:
st['inputs'] = [str(x) for x in json.loads(inputs_json)]
except Exception:
st['inputs'] = []
st['pos'] = 0
st['chars'] = 0
st['limit'] = float(limit)
sys.stdout = _CoWriter('out')
sys.stderr = _CoWriter('err')
builtins.input = _co_input
src = src.replace('\r\n', '\n').replace('\r', '\n')
linecache.cache['<student>'] = (len(src), None, src.splitlines(True), '<student>')
try:
tree = ast.parse(src, '<student>', 'exec')
except SyntaxError as e:
_co_syntax(e)
return json.dumps({'status': 'error'})
try:
tree = _CoTx().visit(tree)
ast.fix_missing_locations(tree)
code = compile(tree, '<student>', 'exec')
except SyntaxError as e:
_co_syntax(e)
return json.dumps({'status': 'error'})
ns = {'__name__': '__main__', '__doc__': None, '__builtins__': builtins, '__co_tick__': _co_tick}
random.seed(seed)
st['deadline'] = time.time() + st['limit']
t0 = time.time()
status = 'ok'
try:
exec(code, ns)
except _CoNeedInput as e:
return json.dumps({'status': 'input', 'prompt': e.prompt})
except _CoStop as e:
st['chars'] = 0
if e.why == 'time':
sys.stderr.write('\nStopped: the program was still running after %g seconds.\n'
'A loop may never be ending - check its condition.\n' % st['limit'])
else:
sys.stderr.write('\nStopped: the program printed far too much text.\n'
'An endless loop with print() inside it is the usual reason.\n')
status = 'error'
except SystemExit:
pass
except BaseException as e:
_co_tb(e)
status = 'error'
return json.dumps({'status': status, 'ms': int((time.time() - t0) * 1000), 'files': _co_files()})
# My first Python program. Lines starting with # are comments.
print("Hello, ClassHud!")
print("Welcome to Python 3")
# print can show more than one thing, separated by commas
print("2 + 3 =", 2 + 3)
print("Python finds 15 x 12 =", 15 * 12)
# an empty print() leaves a blank line
print()
print("Now change the words above and press Run again!")
name = "Simran" # str (text)
roll = 14 # int (whole number)
marks = 87.5 # float (decimal number)
present = True # bool (True / False)
print("Name :", name, type(name))
print("Roll no :", roll, type(roll))
print("Marks :", marks, type(marks))
print("Present :", present, type(present))
# variables can be changed any time
marks = marks + 2.5
print("New marks:", marks)
# several variables in one line
a, b, c = 10, 20, 30
print("a, b, c =", a, b, c)
# a name is just a label, so this works too
total = a + b + c
print("Total =", total, " Average =", total / 3)
name = input("What is your name? ")
cls = input("Which class are you in? ")
# an f-string puts variables straight inside the text
print(f"Hello {name}! Class {cls} is going to be a great year.")
print(f"Your name has {len(name)} letters and starts with '{name[0]}'.")
# the old way of joining text (notice the + signs and the spaces)
print("Good luck, " + name + "!")
a = input("Enter first number : ")
b = input("Enter second number: ")
# input() ALWAYS gives a string, so + just joins the two strings
print("Joined as text :", a + b)
x = int(a) # now they are real numbers
y = int(b)
print("Real addition :", x + y)
print("Subtraction :", x - y)
print("Division :", x / y)
print("As decimals :", float(x), float(y))
print("Back to text :", str(x) + " and " + str(y))
print("Types :", type(a), type(x))
print("A", "B", "C") # default separator is a space
print("A", "B", "C", sep=" | ") # change the separator
print("2026", "04", "01", sep="-")
print("Loading", end="") # end="" keeps the cursor on the same line
for i in range(5):
print(".", end="")
print(" done")
pi = 3.14159265358979
print("round(pi, 2) :", round(pi, 2))
print("f-string 3 dp :", f"{pi:.3f}")
print("width 10, 4 dp :", f"{pi:10.4f}")
print("percent style :", "%s scored %d marks" % ("Aman", 92))
print("Big number :", f"{1234567:,}")
a = 17
b = 5
print("a =", a, " b =", b)
print("a + b =", a + b, " (addition)")
print("a - b =", a - b, " (subtraction)")
print("a * b =", a * b, " (multiplication)")
print("a / b =", a / b, " (true division, always a float)")
print("a // b =", a // b, " (floor division, whole part only)")
print("a % b =", a % b, " (modulus, the remainder)")
print("a ** b =", a ** b, " (a to the power b)")
print()
print("Order of operations: 2 + 3 * 4 =", 2 + 3 * 4)
print("Brackets first : (2 + 3) * 4 =", (2 + 3) * 4)
print("Is 48 divisible by 6?", 48 % 6 == 0)
age = 15
marks = 82
print("age > 12 :", age > 12)
print("marks >= 90 :", marks >= 90)
print("marks != 82 :", marks != 82)
print("and :", age > 12 and marks >= 80) # both must be True
print("or :", age > 12 or marks >= 90) # at least one must be True
print("not :", not (marks >= 90)) # flips True and False
print("'a' in 'class' :", "a" in "class")
print("5 in [1, 3, 5] :", 5 in [1, 3, 5])
x = 5
y = 5.0
print("x == y :", x == y, " (same value)")
print("x is y :", x is y, " (same object? no - one is int, one is float)")
a = int(input("Enter a: "))
b = int(input("Enter b: "))
print("Before swap : a =", a, ", b =", b)
a, b = b, a # Python can swap in one line
print("After swap : a =", a, ", b =", b)
print()
p, q = 3, 9
print("Using a third variable")
print(" before:", p, q)
temp = p
p = q
q = temp
print(" after :", p, q)
import math
n = 50
print("Number:", n)
print("math.sqrt(n) :", math.sqrt(n))
print("round to 3 dp :", round(math.sqrt(n), 3))
print("math.ceil :", math.ceil(7.2), " (always up)")
print("math.floor :", math.floor(7.8), " (always down)")
print("math.pi :", math.pi)
print("math.factorial :", math.factorial(6))
print()
print("abs(-9) :", abs(-9))
print("pow(2, 10) :", pow(2, 10))
print("divmod(17, 5) :", divmod(17, 5), " (quotient, remainder)")
print("max / min :", max(4, 9, 2), min(4, 9, 2))
print("sum([1,2,3,4]) :", sum([1, 2, 3, 4]))
print("Area of circle r=7 :", round(math.pi * 7 * 7, 2))
n = int(input("Enter a whole number: "))
if n % 2 == 0:
print(n, "is EVEN")
else:
print(n, "is ODD")
# the same idea written in one line
print("One-liner says:", "even" if n % 2 == 0 else "odd")
# positive, negative or zero needs elif
if n > 0:
print(n, "is positive")
elif n < 0:
print(n, "is negative")
else:
print("The number is zero")
a = float(input("First number : "))
b = float(input("Second number: "))
c = float(input("Third number : "))
if a >= b and a >= c:
largest = a
elif b >= a and b >= c:
largest = b
else:
largest = c
print("Numbers entered:", a, b, c)
print("The largest is :", largest)
print("The smallest is:", min(a, b, c))
print("Check with max():", max(a, b, c))
print("Sorted order :", sorted([a, b, c]))
marks = float(input("Enter marks out of 100: "))
if marks < 0 or marks > 100:
print("Marks must be between 0 and 100.")
else:
if marks >= 91:
grade = "A1"
elif marks >= 81:
grade = "A2"
elif marks >= 71:
grade = "B1"
elif marks >= 61:
grade = "B2"
elif marks >= 51:
grade = "C1"
elif marks >= 41:
grade = "C2"
elif marks >= 33:
grade = "D"
else:
grade = "E"
print("Marks :", marks)
print("Grade :", grade)
if marks >= 33:
print("Result: PASS")
else:
print("Result: Needs improvement (below 33)")
year = int(input("Enter a year: "))
if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
print(year, "is a LEAP year - February has 29 days")
else:
print(year, "is NOT a leap year - February has 28 days")
print()
print("Century years are special:")
for y in [1900, 2000, 2024, 2025, 2100]:
leap = y % 400 == 0 or (y % 4 == 0 and y % 100 != 0)
print(" ", y, "->", "leap" if leap else "not leap")
n = int(input("Table of which number? "))
for i in range(1, 11):
print(n, "x", i, "=", n * i)
print()
print("Neatly lined up with an f-string:")
for i in range(1, 11):
print(f"{n:2} x {i:2} = {n * i:3}")
n = int(input("How many numbers (n)? "))
total = 0
for i in range(1, n + 1):
total = total + i
print("Numbers 1 to", n)
print("Sum =", total)
print("Formula n(n+1)/2 =", n * (n + 1) // 2)
print("Average =", total / n)
# sum of even and odd numbers separately
even = 0
odd = 0
for i in range(1, n + 1):
if i % 2 == 0:
even += i
else:
odd += i
print("Sum of even numbers:", even)
print("Sum of odd numbers :", odd)
n = int(input("Find the factorial of: "))
fact = 1
i = 1
while i <= n:
fact = fact * i
print(" after multiplying by", i, "fact =", fact)
i = i + 1
print(n, "! =", fact)
# the same job with a for loop
answer = 1
for k in range(1, n + 1):
answer *= k
print("for loop gives :", answer)
n = int(input("How many Fibonacci terms? "))
a = 0
b = 1
print("Fibonacci series:")
for i in range(n):
print(a, end=" ")
a, b = b, a + b
print()
# as a list, so we can use it later
series = []
x, y = 0, 1
for i in range(n):
series.append(x)
x, y = y, x + y
print("As a list:", series)
print("Sum of the series:", sum(series))
n = int(input("Enter a number: "))
num = n
rev = 0
digit_sum = 0
count = 0
while num > 0:
digit = num % 10 # last digit
rev = rev * 10 + digit # build the reverse
digit_sum += digit
count += 1
num = num // 10 # throw the last digit away
print("Number :", n)
print("Reversed :", rev)
print("Sum of digits :", digit_sum)
print("How many digits:", count)
print("Palindrome number?", n == rev)
print("Quick way with strings:", int(str(n)[::-1]))
n = int(input("Enter a number to test: "))
if n < 2:
print(n, "is not a prime number")
else:
is_prime = True
for d in range(2, int(n ** 0.5) + 1):
if n % d == 0:
is_prime = False
print(n, "divides exactly by", d, "so it is not prime")
break
if is_prime:
print(n, "is a PRIME number")
print()
print("Primes up to 50:")
for x in range(2, 51):
prime = True
for d in range(2, int(x ** 0.5) + 1):
if x % d == 0:
prime = False
break
if prime:
print(x, end=" ")
print()
print("continue skips multiples of 3, break stops after 15")
for n in range(1, 21):
if n % 3 == 0:
continue # jump to the next number
if n > 15:
print()
print("break at", n)
break
print(n, end=" ")
else:
print("the loop finished without a break")
print()
print("Searching for 7 in a list")
data = [2, 4, 7, 9]
for x in data:
if x == 7:
print(" found it!")
break
else:
print(" 7 is not in the list")
print()
print("pass does nothing - it is just a placeholder")
for i in range(3):
pass
print("done")
n = int(input("Number of rows: "))
print("Right triangle")
for i in range(1, n + 1):
print("*" * i)
print()
print("Upside down")
for i in range(n, 0, -1):
print("*" * i)
print()
print("Using an inner loop instead of * repetition")
for i in range(1, n + 1):
for j in range(i):
print("*", end=" ")
print()
n = int(input("Rows: "))
print("Pyramid")
for i in range(1, n + 1):
spaces = " " * (n - i)
stars = "*" * (2 * i - 1)
print(spaces + stars)
print()
print("Diamond")
for i in range(1, n + 1):
print(" " * (n - i) + "*" * (2 * i - 1))
for i in range(n - 1, 0, -1):
print(" " * (n - i) + "*" * (2 * i - 1))
print()
print("Hollow square")
for i in range(n):
for j in range(n):
if i == 0 or i == n - 1 or j == 0 or j == n - 1:
print("*", end="")
else:
print(" ", end="")
print()
n = 5
print("Number triangle")
for i in range(1, n + 1):
for j in range(1, i + 1):
print(j, end=" ")
print()
print()
print("Same number in each row")
for i in range(1, n + 1):
print((str(i) + " ") * i)
print()
print("Floyd's triangle")
c = 1
for i in range(1, n + 1):
for j in range(i):
print(str(c).rjust(3), end="")
c += 1
print()
print()
print("Pascal's triangle")
row = [1]
for i in range(n):
line = " ".join(str(x) for x in row)
print(line.center(4 * n))
new_row = [1]
for j in range(len(row) - 1):
new_row.append(row[j] + row[j + 1])
new_row.append(1)
row = new_row
marks = [78, 92, 55, 88, 64]
print("The list :", marks)
print("First item :", marks[0], " Last item:", marks[-1])
print("Slice [1:4]:", marks[1:4])
print("Every 2nd :", marks[::2])
print("Reversed :", marks[::-1])
print("Length :", len(marks))
marks.append(100) # add at the end
marks.insert(0, 45) # add at a position
marks.remove(55) # remove by value
popped = marks.pop() # remove and return the last item
print()
print("After changes:", marks, " (popped", popped, ")")
print("Sum :", sum(marks))
print("Highest :", max(marks), " Lowest:", min(marks))
print("Average :", round(sum(marks) / len(marks), 2))
print("Sorted :", sorted(marks))
marks.sort(reverse=True)
print("Sorted high to low:", marks)
print("Count of 88:", marks.count(88), " Index of 88:", marks.index(88))
print("Doubled with a comprehension:", [m * 2 for m in marks])
n = int(input("How many students? "))
marks = []
for i in range(n):
m = float(input("Marks of student " + str(i + 1) + ": "))
marks.append(m)
average = sum(marks) / len(marks)
print()
print("Marks entered :", marks)
print("Highest :", max(marks))
print("Lowest :", min(marks))
print("Average :", round(average, 2))
print("Above average :", [m for m in marks if m > average])
print("How many passed (33+):", len([m for m in marks if m >= 33]))
print("Sorted :", sorted(marks, reverse=True))
nums = [64, 25, 12, 22, 11, 90]
print("Original:", nums)
for i in range(len(nums) - 1):
swapped = False
for j in range(len(nums) - 1 - i):
if nums[j] > nums[j + 1]:
nums[j], nums[j + 1] = nums[j + 1], nums[j]
swapped = True
print("Pass", i + 1, ":", nums)
if not swapped:
print(" nothing moved, the list is already sorted")
break
print("Sorted :", nums)
print("Python's own sort would do it in one line: sorted(nums)")
data = [11, 12, 22, 25, 64, 90]
key = int(input("Which number should we look for? "))
print("List:", data)
print()
print("Linear search - check every item")
found = -1
for i in range(len(data)):
print(" comparing with", data[i])
if data[i] == key:
found = i
break
print(" result: index", found)
print()
print("Binary search - the list must be sorted")
low = 0
high = len(data) - 1
pos = -1
while low <= high:
mid = (low + high) // 2
print(" checking index", mid, "which holds", data[mid])
if data[mid] == key:
pos = mid
break
elif data[mid] < key:
low = mid + 1
else:
high = mid - 1
print(" result: index", pos)
nums = [12, 45, 2, 45, 67, 23, 67, 12]
print("List:", nums)
unique = []
for x in nums:
if x not in unique:
unique.append(x)
print("Without duplicates:", unique)
print("Using set() :", sorted(set(nums)))
print()
ordered = sorted(unique, reverse=True)
print("Largest :", ordered[0])
print("Second largest:", ordered[1])
print("Third largest :", ordered[2])
print()
print("Which numbers repeat?")
for x in sorted(set(nums)):
if nums.count(x) > 1:
print(" ", x, "appears", nums.count(x), "times")
student = ("Simran", 10, "A", 92.5)
print("Tuple:", student)
name, cls, section, percent = student # unpacking
print("Name:", name, "| Class", cls, section, "|", percent, "%")
print("Length:", len(student))
print("Index of 'A':", student.index("A"), " Count of 10:", student.count(10))
print("Slice [1:3]:", student[1:3])
# a tuple cannot be changed - this proves it
try:
student[0] = "Aman"
except TypeError as e:
print("Cannot change a tuple ->", e)
print()
maths = {"Simran", "Aman", "Harleen", "Simran"} # the repeat disappears
science = {"Aman", "Gurleen"}
print("Maths club :", sorted(maths))
print("Science club:", sorted(science))
print("In either (union) :", sorted(maths | science))
print("In both (intersection) :", sorted(maths & science))
print("Only maths (difference) :", sorted(maths - science))
print("Is Aman in maths club?", "Aman" in maths)
student = {
"name": "Simran",
"class": 10,
"marks": {"Maths": 92, "Science": 88, "English": 79, "SST": 85, "Hindi": 90},
}
print("Name :", student["name"])
print("Class:", student.get("class"))
print("Section (missing key with a default):", student.get("section", "not given"))
print()
print("Subject-wise marks")
total = 0
for subject, mark in student["marks"].items():
print(f" {subject:<10}{mark:>4}")
total += mark
count = len(student["marks"])
print(" " + "-" * 14)
print(f" {'Total':<10}{total:>4} / {100 * count}")
print("Percentage:", round(total / count, 2), "%")
print("Best subject:", max(student["marks"], key=student["marks"].get))
student["marks"]["Computer"] = 95 # add a new key
student["class"] = 11 # change a value
del student["marks"]["Hindi"] # remove a key
print()
print("Keys :", list(student.keys()))
print("Marks :", student["marks"])
text = input("Type a sentence: ")
words = text.lower().split()
freq = {}
for w in words:
freq[w] = freq.get(w, 0) + 1
print()
print("Word count")
for w in sorted(freq):
print(" ", w, "->", freq[w])
print("Different words:", len(freq), "out of", len(words))
letters = {}
for ch in text.lower():
if ch.isalpha():
letters[ch] = letters.get(ch, 0) + 1
pairs = sorted(letters.items(), key=lambda kv: (-kv[1], kv[0]))
print()
print("Top 5 letters")
for ch, c in pairs[:5]:
print(" ", ch, "*" * c, c)
s = " ClassHud "
print("Original :", repr(s))
print("strip() :", repr(s.strip()))
print("upper() :", s.upper())
print("lower() :", s.lower())
print("title() :", s.strip().title())
print("replace() :", s.strip().replace("App", "Tools"))
print("split() :", s.split())
print("find('ON') :", s.find("ON"))
print("count('s') :", s.count("s"))
print("len() :", len(s))
print("join :", "-".join(["C", "B", "S", "E"]))
word = "Python"
print()
print("word :", word)
print("word[0] :", word[0], " word[-1]:", word[-1])
print("word[1:4] :", word[1:4])
print("word[::-1] :", word[::-1])
print("word * 2 :", word * 2)
print("word + '3' :", word + "3")
print("startswith :", word.startswith("Py"), " endswith:", word.endswith("on"))
print("isalpha :", word.isalpha(), " '123'.isdigit():", "123".isdigit())
print("Loop over it :", end=" ")
for ch in word:
print(ch, end=".")
print()
s = input("Enter a word or sentence: ")
clean = ""
for ch in s.lower():
if ch.isalnum():
clean += ch
print("Cleaned :", clean)
print("Reversed :", clean[::-1])
if clean == clean[::-1]:
print("It IS a palindrome")
else:
print("It is NOT a palindrome")
vowels = 0
consonants = 0
digits = 0
spaces = 0
for ch in s:
if ch.isdigit():
digits += 1
elif ch == " ":
spaces += 1
elif ch.isalpha():
if ch.lower() in "aeiou":
vowels += 1
else:
consonants += 1
print()
print("Vowels :", vowels)
print("Consonants :", consonants)
print("Digits :", digits)
print("Spaces :", spaces)
print("Words :", len(s.split()))
print("Characters :", len(s))
line = "india is my country and i love it"
print("Original :", line)
print("Title case :", line.title())
print("Capitalised :", line.capitalize())
print("Upper :", line.upper())
words = line.split()
print()
print("Words :", words)
print("How many :", len(words))
print("Reversed order:", " ".join(words[::-1]))
print("Each reversed :", " ".join(w[::-1] for w in words))
print("Longest word :", max(words, key=len))
print("Shortest word :", min(words, key=len))
print("Words with 2+ letters:", [w for w in words if len(w) >= 2])
print()
print("First letter of every word (initials):")
initials = ""
for w in words:
initials += w[0].upper()
print(" ", initials)
def greet(name, greeting="Good morning"):
"""Return a greeting line for one person."""
return greeting + ", " + name + "!"
def area_rectangle(length, breadth):
return length * breadth
def stats(numbers):
"""Return the lowest, highest and average - three values at once."""
return min(numbers), max(numbers), sum(numbers) / len(numbers)
def table(n, upto=10):
for i in range(1, upto + 1):
print(" ", n, "x", i, "=", n * i)
print(greet("Simran"))
print(greet("Sir", "Namaste"))
print(greet(greeting="Hi", name="Aman")) # keyword arguments
print("Area 5 x 3 =", area_rectangle(5, 3))
low, high, avg = stats([45, 78, 92, 66])
print("Low", low, "| High", high, "| Average", round(avg, 2))
print("Table of 9, first 5 rows:")
table(9, 5)
print()
print("The docstring of greet():", greet.__doc__)
def total(*numbers):
"""Any number of values arrive as a tuple."""
s = 0
for n in numbers:
s += n
return s
def show_details(**info):
"""Named values arrive as a dictionary."""
for key, value in info.items():
print(" ", key, "=", value)
visits = 0
def visit():
global visits # without 'global' this would make a new local variable
visits += 1
print("total(1, 2, 3) :", total(1, 2, 3))
print("total(4, 5, 6, 7, 8) :", total(4, 5, 6, 7, 8))
print("Details:")
show_details(name="Simran", cls=10, section="A")
visit()
visit()
visit()
print("visits =", visits)
square = lambda x: x * x
print()
print("lambda square(7) :", square(7))
print("map (square each) :", list(map(square, [1, 2, 3, 4])))
print("filter (even only) :", list(filter(lambda x: x % 2 == 0, range(10))))
print("sorted by last letter:", sorted(["banana", "kiwi", "mango"], key=lambda w: w[-1]))
def fact(n):
if n <= 1: # base case - stops the recursion
return 1
return n * fact(n - 1) # recursive case
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
def digit_sum(n):
if n < 10:
return n
return n % 10 + digit_sum(n // 10)
def power(a, b):
if b == 0:
return 1
return a * power(a, b - 1)
print("5! =", fact(5))
print("Steps: 5! = 5 x 4! = 5 x 4 x 3! = 5 x 4 x 3 x 2 x 1")
print("10! =", fact(10))
print()
print("First 12 Fibonacci numbers:", [fib(i) for i in range(12)])
print("digit_sum(49876) =", digit_sum(49876))
print("power(2, 10) =", power(2, 10))
def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
def hanoi(n, source, helper, target):
if n == 0:
return
hanoi(n - 1, source, target, helper)
print(" Move disc", n, "from", source, "to", target)
hanoi(n - 1, helper, source, target)
print("gcd(48, 18) =", gcd(48, 18))
print("gcd(270, 192) =", gcd(270, 192))
print("lcm(48, 18) = 48 x 18 / gcd =", 48 * 18 // gcd(48, 18))
print()
discs = 3
print("Tower of Hanoi with", discs, "discs:")
hanoi(discs, "A", "B", "C")
print("Total moves needed:", 2 ** discs - 1)
# This file lives in a private sandbox inside the browser tab,
# so nothing is written to your real computer.
f = open("marks.txt", "w") # "w" creates the file (and erases an old one)
f.write("Simran,92\n") # \n starts a new line
f.write("Aman,78\n")
f.write("Harleen,85\n")
f.close() # always close what you open
print("File written.")
print()
print("--- read() gives the whole file as one string ---")
f = open("marks.txt", "r")
print(f.read())
f.close()
print("--- line by line with 'with' (it closes the file for you) ---")
with open("marks.txt") as f:
for line in f:
name, mark = line.strip().split(",")
print(f"{name:<10}{mark:>4}")
with open("marks.txt") as f:
lines = f.readlines()
print()
print("readlines() gives a list:", lines)
print("Number of records:", len(lines))
total = 0
for line in lines:
total += int(line.strip().split(",")[1])
print("Class total:", total, " average:", round(total / len(lines), 2))
with open("diary.txt", "w") as f:
f.write("Monday: learnt Python loops\n")
with open("diary.txt", "a") as f: # "a" = append
f.write("Tuesday: wrote my first function\n")
f.write("Wednesday: file handling is easy\n")
f.write("Thursday: tried a dictionary\n")
with open("diary.txt") as f:
text = f.read()
print(text)
lines = text.strip().split("\n")
words = text.split()
print("Lines :", len(lines))
print("Words :", len(words))
print("Characters :", len(text))
print("Lines starting with T:", sum(1 for l in lines if l.startswith("T")))
print()
print("Longest line:")
print(" ", max(lines, key=len))
print()
print("Word frequency of 'a':", text.lower().count("a"))
with open("diary.txt") as f:
first = f.readline()
print("readline() reads just one line:", repr(first))
try:
a = int(input("Numerator : "))
b = int(input("Denominator: "))
answer = a / b
except ValueError:
print("Please type whole numbers only.")
except ZeroDivisionError:
print("A number cannot be divided by zero.")
else:
print("Answer =", answer) # runs only when nothing went wrong
finally:
print("-- calculation attempted --") # always runs
print()
print("One except can catch several errors:")
for value in ["10", "abc", "0", "4"]:
try:
print(" 100 /", value, "=", 100 / int(value))
except (ValueError, ZeroDivisionError) as e:
print(" cannot use", value, "->", type(e).__name__, ":", e)
class MarksError(Exception):
"""Our own exception type."""
pass
def check_marks(m):
if m < 0 or m > 100:
raise MarksError(str(m) + " is not between 0 and 100")
return "valid"
for m in [85, 120, -5]:
try:
print(m, "->", check_marks(m))
except MarksError as e:
print(m, "-> MarksError:", e)
print()
try:
age = int(input("Enter your age: "))
assert age > 0, "Age must be more than 0"
print("Next year you will be", age + 1)
except AssertionError as e:
print("AssertionError:", e)
except ValueError:
print("That was not a whole number.")
print()
print("Looking up a missing dictionary key:")
marks = {"Maths": 90}
try:
print(marks["Science"])
except KeyError as e:
print(" KeyError - there is no key", e)
p = float(input("Principal (rupees) : "))
r = float(input("Rate % per year : "))
t = float(input("Time in years : "))
si = p * r * t / 100
print()
print("SIMPLE INTEREST")
print(" SI = P x R x T / 100 =", round(si, 2))
print(" Amount to be paid =", round(p + si, 2))
amount = p * (1 + r / 100) ** t
ci = amount - p
print()
print("COMPOUND INTEREST (yearly)")
print(" A = P(1 + R/100)^T =", round(amount, 2))
print(" CI = A - P =", round(ci, 2))
print()
print("Difference CI - SI =", round(ci - si, 2))
print()
print("Year by year")
for year in range(1, int(t) + 1):
a = p * (1 + r / 100) ** year
print(f" year {year}: amount = {round(a, 2)}")
import math
print("1. Square")
print("2. Rectangle")
print("3. Circle")
print("4. Triangle")
choice = input("Choose a shape (1-4): ")
if choice == "1":
s = float(input("Side: "))
print("Area =", s * s)
print("Perimeter =", 4 * s)
elif choice == "2":
l = float(input("Length : "))
b = float(input("Breadth: "))
print("Area =", l * b)
print("Perimeter =", 2 * (l + b))
elif choice == "3":
r = float(input("Radius: "))
print("Area =", round(math.pi * r * r, 2))
print("Circumference =", round(2 * math.pi * r, 2))
elif choice == "4":
b = float(input("Base : "))
h = float(input("Height: "))
print("Area =", 0.5 * b * h)
else:
print("Please choose 1, 2, 3 or 4.")
c = float(input("Temperature in Celsius: "))
f = c * 9 / 5 + 32
k = c + 273.15
print(f"{c} C = {f} F = {round(k, 2)} K")
print()
print("Celsius to Fahrenheit table")
print(" C F")
for t in range(0, 101, 10):
print(f"{t:3} {t * 9 / 5 + 32:6.1f}")
print()
print("Water facts")
for t, label in [(0, "freezes"), (37, "body temperature"), (100, "boils")]:
print(f" {t} C ({t * 9 / 5 + 32} F) - water {label}")
def grade(percent):
if percent >= 91:
return "A1"
if percent >= 81:
return "A2"
if percent >= 71:
return "B1"
if percent >= 61:
return "B2"
if percent >= 51:
return "C1"
if percent >= 41:
return "C2"
if percent >= 33:
return "D"
return "E"
students = {
"Simran": {"Maths": 92, "Science": 88, "English": 79, "SST": 85, "Hindi": 90},
"Aman": {"Maths": 56, "Science": 61, "English": 72, "SST": 48, "Hindi": 66},
"Harleen": {"Maths": 78, "Science": 95, "English": 88, "SST": 91, "Hindi": 84},
"Gurleen": {"Maths": 34, "Science": 41, "English": 52, "SST": 38, "Hindi": 45},
}
print("CLASS 10 - A : TERM 1 RESULT")
print("=" * 40)
print(f"{'Name':<10}{'Total':>7}{'%':>8}{'Grade':>7}")
print("-" * 40)
results = []
for name, marks in students.items():
total = sum(marks.values())
percent = total / len(marks)
results.append((percent, name))
print(f"{name:<10}{total:>7}{percent:>8.2f}{grade(percent):>7}")
results.sort(reverse=True)
print("-" * 40)
print("Class topper :", results[0][1], "with", round(results[0][0], 2), "%")
print("Class average:", round(sum(p for p, n in results) / len(results), 2), "%")
print()
print("Subject averages")
subjects = list(students["Simran"].keys())
for sub in subjects:
avg = sum(students[s][sub] for s in students) / len(students)
bar = "#" * int(avg / 5)
print(f" {sub:<9}{avg:6.1f} {bar}")
import matplotlib.pyplot as plt
subjects = ["Maths", "Science", "English", "SST", "Hindi"]
marks = [92, 88, 79, 85, 90]
plt.figure(figsize=(6.4, 3.6))
plt.bar(subjects, marks, color="#DC2626")
plt.title("My marks - Term 1")
plt.ylabel("Marks out of 100")
plt.ylim(0, 105)
for i in range(len(marks)):
plt.text(i, marks[i] + 2, str(marks[i]), ha="center")
plt.tight_layout()
plt.show()
print("Average:", round(sum(marks) / len(marks), 2))
import matplotlib.pyplot as plt
x = list(range(1, 11))
squares = [n * n for n in x]
cubes = [n ** 3 for n in x]
print("n :", x)
print("squares:", squares)
print("cubes :", cubes)
plt.figure(figsize=(6.4, 3.6))
plt.plot(x, squares, marker="o", color="#2563EB", label="n squared")
plt.plot(x, cubes, marker="s", color="#DC2626", label="n cubed")
plt.title("Squares and cubes of 1 to 10")
plt.xlabel("n")
plt.ylabel("value")
plt.legend()
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
# Welcome to the ClassHud Python Playground.
# Press Ctrl + Enter (or click Run) to run this program.
print("Hello, ClassHud!")
name = input("What is your name? ")
print("Nice to meet you,", name)
print()
print("Table of 7")
for i in range(1, 11):
print(7, "x", i, "=", 7 * i)