python basic code
Python A–Z — 01 Basics
Beginner problems with answers. Copy any code and run in your IDE.
1) Print Hello World
print("Hello, World!")
2) Comments (Single & Multi-line)
# This is a single-line comment
"""
This is a multi-line comment / docstring.
Use it for module, function, or class docs.
"""
3) Variables & Basic Data Types
# Creating variables
age = 21 # int
height = 1.72 # float
name = "Indranil" # str
is_student = True # bool
print(type(age), type(height), type(name), type(is_student))
4) Take User Input (str, int, float)
name = input("Your name: ") # str
age = int(input("Your age: ")) # int
score = float(input("Your score: ")) # float
print(f"Hi {name}! Age: {age}, Score: {score}")
5) Type Casting
a = "25"
print(int(a) + 5) # 30
print(str(99) + " bottles")
print(bool(0), bool(3), bool(""), bool("x"))
6) Arithmetic Operators
a, b = 7, 3
print(a + b, a - b, a * b)
print(a / b) # true division
print(a // b) # floor division
print(a % b) # remainder
print(a ** b) # power
7) Assignment Operators
x = 10
x += 5 # 15
x *= 2 # 30
x //= 3 # 10
print(x)
8) Relational & Logical Operators
a, b = 5, 9
print(a < b, a == b, a != b) # True, False, True
print(a < b and b < 10) # True
print(a > b or a == 5) # True
print(not (a == 5)) # False
9) If / Else (Decision Making)
n = int(input("Number: "))
if n > 0:
print("Positive")
elif n < 0:
print("Negative")
else:
print("Zero")
10) One-Line If (Ternary)
n = int(input("N: "))
print("Even" if n % 2 == 0 else "Odd")
11) For Loop with range()
for i in range(5):
print(i)
12) While Loop (Countdown)
n = 3
while n > 0:
print(n)
n -= 1
13) break / continue / pass
for x in range(10):
if x == 5:
break # stop loop
if x % 2:
continue # skip odds
print(x)
if True:
pass # placeholder
14) String Basics & Slicing
s = "hello python"
print(len(s)) # 12
print(s[:5]) # hello
print(s.upper()) # HELLO PYTHON
print(s.find("py")) # 6
15) f-Strings (Formatting)
name = "Riya"
score = 95.678
print(f"{name} scored {score:.2f}") # Riya scored 95.68
16) Lists — Create & Modify
a = [10, 30, 20]
a.append(40)
a.insert(1, 99)
a.remove(20)
last = a.pop()
a.sort()
print(a, last)
17) Tuple & Unpacking
pt = (10, 20)
x, y = pt
print(x, y)
18) Dictionary — CRUD & Access
user = {"name":"Ana","age":21}
user["city"] = "Kolkata"
print(user.get("name"))
print(list(user.keys()))
user.update({"age":22})
print(user)
19) Set — Unique Elements
s = {1,2,2,3}
s.add(4)
s.discard(2)
print(s, 3 in s)
20) List Comprehension (Squares & Evens)
squares = [x*x for x in range(6)]
ev = [x for x in range(10) if x % 2 == 0]
print(squares, ev)
21) Define Function + Default Arg
def greet(name="friend"):
return f"Hello, {name}!"
print(greet("Rahul"))
print(greet())
22) Lambda (Small Function)
add = lambda a,b: a+b
print(add(2,3))
23) Try / Except (Handle Errors)
try:
x = int(input("Number: "))
print(10 / x)
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError:
print("Please enter a valid number")
24) File Write & Read
with open("sample.txt","w") as f:
f.write("Hello file!\n")
with open("sample.txt") as f:
print(f.read())
25) Using math Module
import math
print(math.sqrt(16), math.pi)
26) Mini: Simple Calculator (Two Numbers)
a = float(input("A: "))
b = float(input("B: "))
print("+:", a+b)
print("-:", a-b)
print("*:", a*b)
print("/:", a/b if b!=0 else "Infinity")
27) Swap Two Numbers (No Temp)
a, b = 3, 5
a, b = b, a
print(a, b)
28) Largest of Two Numbers
a = int(input("A: "))
b = int(input("B: "))
print(a if a > b else b)
29) Sum of Numbers from One Line Input
nums = list(map(int, input("Enter numbers: ").split()))
print(sum(nums))
30) Filter Evens from List (Comprehension)
nums = [1,2,3,4,5,6]
ev = [x for x in nums if x % 2 == 0]
print(ev)
End of Basics • Next file: Operators
Can you provide leetcode question answer
ReplyDelete