0% found this document useful (0 votes)
4 views2 pages

Essential Python Code Snippets

Uploaded by

pavanbarma777
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)
4 views2 pages

Essential Python Code Snippets

Uploaded by

pavanbarma777
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

Python Code Snippets

Hello World

print('Hello, World!')

Factorial Function

def factorial(n):

if n == 0:

return 1

return n * factorial(n - 1)

print(factorial(5)) # Output: 120

Check Prime Number

def is_prime(num):

if num < 2:

return False

for i in range(2, int(num ** 0.5) + 1):

if num % i == 0:

return False

return True

print(is_prime(13)) # Output: True

Fibonacci Sequence

def fibonacci(n):

Page 1
Python Code Snippets

a, b = 0, 1

for _ in range(n):

print(a, end=' ')

a, b = b, a + b

fibonacci(10) # Output: 0 1 1 2 3 5 8 13 21 34

List Comprehension

squares = [x**2 for x in range(10)]

print(squares) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Read File Content

with open('[Link]', 'r') as file:

content = [Link]()

print(content)

Write to a File

with open('[Link]', 'w') as file:

[Link]('Hello, File!')

Sort a List

numbers = [5, 2, 9, 1]

[Link]()

print(numbers) # Output: [1, 2, 5, 9]

Page 2

You might also like