Python basic notes
1. What is Python?
Python is a high-level, interpreted, and object-oriented programming language.
Created by Guido van Rossum.
Easy to learn and use.
2. Features of Python
Simple and readable syntax
Free and open source
Platform independent
Large standard library
Supports multiple programming styles
3. Python Tokens
Tokens are the smallest units of a program:
Keywords (if, else, while, for)
Identifiers (variable names)
Literals (numbers, strings)
Operators (+, -, *, /)
Delimiters ((), {}, [])
4. Variables
Used to store data
No need to declare type
x = 10
name = "Python"
5. Data Types
Data Type Example
int 10
float 3.14
string "Hello"
bool True
Data Type Example
list [1, 2, 3]
tuple (1, 2, 3)
set {1, 2, 3}
dict {"a": 1}
6. Operators
Arithmetic: +, -, *, /, %
Relational: >, <, ==, !=
Logical: and, or, not
Assignment: =, +=, -=
7. Conditional Statements
if x > 0:
print("Positive")
else:
print("Negative")
8. Loops
For Loop
for i in range(1, 6):
print(i)
While Loop
i = 1
while i <= 5:
print(i)
i += 1
9. Functions
def add(a, b):
return a + b
10. Input and Output
name = input("Enter name: ")
print("Hello", name)
Python basic program
1. Hello World
print("Hello World")
Output
Hello World
2. Add Two Numbers
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print("Sum =", a + b)
Input
Enter first number: 5
Enter second number: 3
Output
Sum = 8
3. Even or Odd
num = int(input("Enter a number: "))
if num % 2 == 0:
print("Even")
else:
print("Odd")
Input
Enter a number: 7
Output
Odd
4. Largest of Two Numbers
a = int(input("Enter a: "))
b = int(input("Enter b: "))
if a > b:
print("a is larger")
else:
print("b is larger")
Input
Enter a: 10
Enter b: 20
Output
b is larger
5. Print Numbers from 1 to 5
for i in range(1, 6):
print(i)
Output
1
2
3
4
5
6. Factorial of a Number
n = int(input("Enter number: "))
fact = 1
for i in range(1, n + 1):
fact *= i
print("Factorial =", fact)
Input
Enter number: 5
Output
Factorial = 120
7. Prime Number Check
num = int(input("Enter number: "))
flag = True
for i in range(2, num):
if num % i == 0:
flag = False
break
if flag and num > 1:
print("Prime")
else:
print("Not Prime")
Input
Enter number: 11
Output
Prime
8. Function Example (Square of a Number)
def square(n):
return n * n
print(square(4))
Output
16
9. Sum of Numbers in a List
numbers = [1, 2, 3, 4, 5]
print("Sum =", sum(numbers))
Output
Sum = 15
10. Simple While Loop
i = 1
while i <= 3:
print(i)
i += 1
Output
1
2
3