Python Notes
1. Input and Output
Program Name: Basic Input and Output
Explanation:
- input() takes user input.
- print() displays output.
name = input("Enter your name: ")
print("Hello", name)
Data Type Conversion
Common Conversions:
- int()
- float()
- str()
Program: Convert Input to Integer and Float
age = int(input("Enter age: "))
height = float(input("Enter height: "))
print("Age:", age)
print("Height:", height)
2. If, Elif, Else
Program: Check Number is Positive or Negative
num = int(input("Enter a number: "))
if num > 0:
print("Positive")
else:
print("Negative")
3. Loops with examples
Program 1: Print Even Numbers
for i in range(2, 21, 2):
print(i)
Program 2: Iterate Through List
fruits = ["apple", "banana", "mango"]
for f in fruits:
print(f)
Program 3: Countdown
count = 5
while count > 0:
print(count)
count -= 1
4. Functions
Program: Greeting Function
def greet():
print("Hello from function")
greet()
5. Local and Global Variables
Program: Local Variable
def demo():
x = 10
print(x)
Program: Global Variable
x = 20
def show():
print(x)
show()
6. Complete Example Program
Program: Multiplication Table
def multiply_numbers():
num = int(input("Enter a number: "))
for i in range(1,6):
print(num,"x",i,"=",num*i)
7. Python Lists
List is ordered, mutable, stores multiple items.
Indexing:
0: apple
1: banana
2: mango
Programs:
1. Access Elements
fruits = ["apple","banana","mango"]
print(fruits[0])
print(fruits[1])
2. Loop Through List
for item in fruits:
print(item)
3. Add and Remove
numbers = [10,20,30]
[Link](40)
[Link](20)
4. Find Largest
nums = [5,12,3,18,7]
largest = nums[0]
for n in nums:
if n>largest: largest=n
print(largest)
5. Create List from User Input
size = int(input("How many numbers?"))
numbers=[]
for i in range(size):
[Link](int(input("Enter number: ")))
print(numbers)