Basic Python Programs
Basic Python Programs
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']
12. Functions:
Python
def greet(name):
print(f"Hello, {name}!")
greet("Charlie")
result = add(3, 7)
print(result) # Output: 10
14. Modules and
Packages:
Python
import math
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.")
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