0% found this document useful (0 votes)
10 views

Basic Python Programs

Uploaded by

vinothkumar0743
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Basic Python Programs

Uploaded by

vinothkumar0743
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

1.

Variables and Data


Types:
Python
name = "Alice"
age = 30 # Integer
pi = 3.14 # Float
is_coding = True #
Boolean

2. User Input:
Python
user_name =
input("What's your name?
")
print(f"Hello,
{user_name}!")

3. Comments:
Python
# This program calculates
the area of a rectangle
length = 5
width = 3
area = length * width
print(f"The area is
{area}.")

4. Arithmetic Operators:
Python
result = 10 + 5
difference = 15 - 7
product = 4 * 6
quotient = 12 / 3

5. Comparison
Operators:
Python
x = 10
y = 20
is_equal = x == y # False
is_greater = x > y # False
6. String Manipulation:
Python
text = "Hello World!"
upper_case = text.upper()
# HELLO WORLD!
lower_case = text.lower()
# hello world!
split_words = text.split()
# ['Hello', 'World!']
7. Conditional
Statements (if-else):
Python
grade = 85
if grade >= 90:
print("Excellent!")
else:
print("Good job!")

8. Loops (for):
Python
numbers = [1, 2, 3, 4, 5]
for number in numbers:
print(number * 2)

9. List Operations:
Python
fruits = ["apple",
"banana", "orange"]
fruits.append("grape") #
Add element
fruits.remove("banana")
# Remove element
print(fruits) # Output:
['apple', 'orange', 'grape']

10. Tuples (immutable


lists):
Python
coordinates = (10, 20)
# coordinates[0] = 30 #
Tuples are immutable
(cannot change elements)
11. Dictionaries (key-
value pairs):
Python
person = {"name": "Bob",
"age": 45, "city": "New
York"}
print(person["name"]) #
Output: Bob

12. Functions:
Python
def greet(name):
print(f"Hello, {name}!")
greet("Charlie")

13. Returning Values


from Functions:
Python
def add(x, y):
return x + y

result = add(3, 7)
print(result) # Output: 10
14. Modules and
Packages:
Python
import math

# Use math functions like


pi and sqrt
print(math.pi) # Output:
3.14159...
print(math.sqrt(16)) #
Output: 4.0

15. Reading Files (text):


Python
with open("data.txt", "r")
as file:
content = file.read()
print(content)

16. Writing Files (text):


Python
with open("output.txt",
"w") as file:
file.write("This is written
to a file.")

17. Simple Calculator:


Python
def calculate(num1,
operator, num2):
if operator == "+":
return num1 + num2
elif operator == "-":
return num1 - num2
# Add more operators as
needed...

result = calculate(10, "-",


5)
print(result) # Output: 5
18. Guessing Game:
Python
import random

secret_number =
random.randint(1, 10)
guesses = 0
while True:
guess = int(input("Guess
a number between 1 and
10: "))
guesses += 1
if guess ==
secret_number:
print(f"You guessed it
in {guesses} tries!")
break
elif guess <
secret_number:
print("Guess higher.")
else:
print("Guess lower.")

20. Password Validator


(continued):
Python
def
is_valid_password(passw
ord):
has_uppercase =
any(char.isupper() for
char in password)
has_lowercase =
any(char.islower() for
char in password)
has_digit =
any(char.isdigit() for char
in password)
has_symbol = any(not
char.isalnum() for char in
password)
return len(password) >=
8 and has_uppercase and
has_lowercase and
has_digit and has_symbol

password = input("Enter
your password: ")
if
is_valid_password(passw
ord):
print("Strong
password!")
else:
print("Password must be
at least 8 characters and
include uppercase,
lowercase, digits, and
symbols.")

21. List
Comprehensions:
Python
numbers = [x * 2 for x in
range(1, 6)] # Creates a
list with doubled numbers
(2, 4, 6, 8, 10)
even_numbers = [x for x
in range(1, 11) if x % 2 ==
0] # Creates a list with
even numbers (2, 4, 6, 8,
10)
22. Tuples Unpacking:
Python
fruits = ("apple",
"banana", "cherry")
name1, name2, name3 =
fruits # Unpack elements
into variables
print(name1) # Output:
apple

23. Sets (unordered


collections of unique
elements):
Python
my_set = {1, 2, 3, 2} #
Duplicates are removed
(set will contain {1, 2, 3})
print(len(my_set)) #
Output: 3
24. Lambdas
(anonymous functions):
Python
add = lambda x, y: x + y
result = add(4, 6)
print(result) # Output: 10

25. Exception Handling


(try-except):
Python
try:
num = int(input("Enter a
number: "))
result = 10 / num
print(result)
except ZeroDivisionError:
print("Cannot divide by
zero!")

You might also like