python basics
python basics
Python Basics
1.1 Python:
Python is a popular programming language known for its simplicity
and readability. It is used for creating applications, websites, and
handling data.
1.2 Syntax:
The set of rules that defines how a Python program is written and
interpreted.
4. Operators
• Arithmetic Operators: Used for mathematical operations (+, -,
*, /, etc.).
• Comparison Operators: Used to compare values (==, !=, >, <,
etc.).
• Logical Operators: Used to combine conditions (and, or, not).
5. Conditional Statements
These are used to make decisions in a program.
• if: Executes a block of code if a condition is true.
Example:
python
CopyEdit
if x > 0:
print("Positive number")
• else: Executes a block of code if the condition is false.
• elif: Checks multiple conditions.
6. Loops
Loops are used to repeat actions.
• for loop: Repeats a block of code for a specific number of times.
Example:
python
CopyEdit
for i in range(5):
print(i)
• while loop: Repeats a block of code as long as the condition is
true.
Example:
python
CopyEdit
while x > 0:
print(x)
x -= 1
7. Functions
A function is a block of reusable code that performs a specific task.
Example:
python
CopyEdit
def greet(name):
print("Hello, " + name)
greet("Alice")
8. Lists
A list is a collection of items in a particular order.
Example:
python
CopyEdit
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Outputs "apple"
9. Strings
A string is a sequence of characters. Strings are enclosed in quotes.
Example:
python
CopyEdit
greeting = "Hello"
print(greeting.upper()) # Outputs "HELLO"
1. Hello, World!
Code:
print("Hello, World!")
Output:
Hello, World!
5. Simple Interest
Code:
P = 1000 # Principal amount
R=5 # Rate of interest
T=2 # Time in years
SI = (P * R * T) / 100
print("The Simple Interest is:", SI)
Output:
The Simple Interest is: 100.0
6. Factorial of a Number
Code:
num = 5
factorial = 1
for i in range(1, num + 1):
factorial *= i
print("Factorial of", num, "is", factorial)
Output:
Factorial of 5 is 120
if is_prime:
print(num, "is a Prime Number")
else:
print(num, "is not a Prime Number")
Output:
11 is a Prime Number
9. Reverse a String
Code:
string = "Python"
reversed_string = string[::-1]
print("Reversed string is:", reversed_string)
Output:
Reversed string is: nohtyP