Divyanshiexp 2 Py
Divyanshiexp 2 Py
In [1]: # WAP to print the sum of the first n natural numbers using for loop
n=int(input("Enter the value of n:"))
s = 0
for i in range(n+1):
s+=i
print("Sum of",n,"natural numbers is:",s)
In [13]: # Write a program to check entered number is prime or not (make use of break).
def prime(n):
if n < 2:
return False
for i in range(2, n):
if n % i == 0:
return False
break
return True
n= int(input("Enter a number to check if it's prime: "))
if prime(n):
print(n,"is a prime number.")
else:
print(n,"is not a prime number.")
In [4]: # Display the Fibonacci sequence up to nth term where n is provided by the use
n = int(input("Enter the number of terms:"))
n1, n2 = 0, 1
count = 0
if n <= 0:
print("Please enter a positive integer")
elif n == 1:
print("Fibonacci sequence upto",n,":")
print(n1)
else:
print("Fibonacci sequence:")
while count < n:
print(n1,sep=" ",end=" ")
nth = n1 + n2
n1 = n2
n2 = nth
count += 1
Enter a string: 34
3
4
w
o
r
l
d
print()
for i in s2:
print(i,end=" ")
print()
# Python String Length
print("Length of first string is:",len(s1))
print("Length of second string is:",len(s2))
# String Membership Test
print("a" in s1)
print("p" not in s2)
# Methods of Python String
print(s1.upper())
print(s2.lower())
print(s1.partition('e'))
print(s2.replace('i','O'))
else:
print("No items are left")
Enter a number:23
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
No items are left
In [ ]: