[go: up one dir, main page]

0% found this document useful (0 votes)
1 views3 pages

Python Beginner Examples Advanced

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

Python Beginner Examples Advanced

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

■ Python Deeper Beginner Programming

Examples
1. List Operations
Lists are used to store multiple values. This example demonstrates adding, removing, and
iterating through a list.

fruits = ["apple", "banana", "mango"]


fruits.append("orange")
fruits.remove("banana")

print("Fruit list:", fruits)

for fruit in fruits:


print("I like", fruit)

2. Function Example
Functions are reusable blocks of code. This program defines a function that calculates the
square of a number.

def square(num):
return num * num

print("Square of 5:", square(5))


print("Square of 10:", square(10))

3. File Handling
This program writes text to a file and then reads it back.

# Writing to a file
with open("example.txt", "w") as f:
f.write("Hello, Python file handling!")

# Reading from the file


with open("example.txt", "r") as f:
content = f.read()
print("File content:", content)

4. Dictionary Example
Dictionaries store data in key-value pairs.

person = {"name": "Alice", "age": 25, "city": "Colombo"}

print("Name:", person["name"])
print("Age:", person["age"])

# Adding a new key-value pair


person["job"] = "Engineer"
print("Updated dictionary:", person)

5. Simple Class
A class is a blueprint for objects. This example shows a simple class with attributes and a
method.

class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model

def display(self):
print("Car:", self.brand, self.model)

mycar = Car("Toyota", "Corolla")


mycar.display()

6. Prime Number Checker


Check whether a given number is prime or not.

num = int(input("Enter a number: "))


is_prime = True

if num <= 1:
is_prime = False
else:
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
is_prime = False
break

if is_prime:
print(num, "is a prime number")
else:
print(num, "is not a prime number")

7. Fibonacci Sequence
Generate Fibonacci numbers up to a given limit.

n = int(input("Enter how many Fibonacci numbers: "))

a, b = 0, 1
for _ in range(n):
print(a)
a, b = b, a + b

8. Student Marks Average


A program to calculate the average marks of students using a list.

marks = [75, 80, 92, 60, 85]


total = sum(marks)
average = total / len(marks)

print("Marks:", marks)
print("Average marks:", average)

You might also like