0% found this document useful (0 votes)
36 views6 pages

Python Basics: 30 Simple Examples

Uploaded by

harshaggar278
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)
36 views6 pages

Python Basics: 30 Simple Examples

Uploaded by

harshaggar278
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

1.

Print Hello World


Code:
print("Hello, World!")
Output:
Hello, World!

2. Add Two Numbers


Code:
a=5
b=3
print(a + b)
Output:
8

3. Check Even or Odd


Code:
n=4
print("Even" if n % 2 == 0 else "Odd")
Output:
Even

4. Find Square of a Number


Code:
n=6
print(n * n)
Output:
36

5. Swap Two Variables


Code:
a, b = 3, 7
a, b = b, a
print(a, b)
Output:
73

6. Simple Interest
Code:
p=1000; r=5; t=2
print((p*r*t)/100)
Output:
100.0

7. Area of Circle
Code:
r=3
print(3.14*r*r)
Output:
28.26

8. Largest of Two Numbers


Code:
a=4; b=9
print(max(a,b))
Output:
9

9. Factorial Using Loop


Code:
n=5
f=1
for i in range(1,n+1):
f*=i
print(f)
Output:
120

10. Multiplication Table


Code:
n=3
for i in range(1,6):
print(n*i)
Output:
3
6
9
12
15

11. Reverse a String


Code:
s="hello"
print(s[::-1])
Output:
olleh

12. Check Palindrome


Code:
s="madam"
print(s==s[::-1])
Output:
True

13. Sum of List


Code:
lst=[1,2,3]
print(sum(lst))
Output:
6

14. Max in List


Code:
lst=[3,7,1]
print(max(lst))
Output:
7

15. Min in List


Code:
lst=[3,7,1]
print(min(lst))
Output:
1

16. Count Vowels


Code:
s="hello"
v=sum(c in 'aeiou' for c in s)
print(v)
Output:
2

17. Fibonacci Series


Code:
a,b=0,1
for _ in range(5):
print(a)
a,b=b,a+b
Output:
0
1
1
2
3

18. Check Positive or Negative


Code:
n=-4
print("Positive" if n>0 else "Negative")
Output:
Negative

19. Length of String


Code:
s="python"
print(len(s))
Output:
6

20. Convert Celsius to Fahrenheit


Code:
c=0
print((c*9/5)+32)
Output:
32.0

21. Armstrong Number


Code:
n=153
s=sum(int(d)**3 for d in str(n))
print(s==n)
Output:
True

22. Prime Number Check


Code:
n=7
f=True
for i in range(2,n):
if n%i==0:
f=False
print(f)
Output:
True

23. Create Dictionary


Code:
d={"a":1,"b":2}
print(d)
Output:
{'a':1,'b':2}
24. List Comprehension
Code:
lst=[x*x for x in range(4)]
print(lst)
Output:
[0,1,4,9]

25. Tuple Example


Code:
t=(1,2,3)
print(t)
Output:
(1,2,3)

26. Set Example


Code:
s={1,2,2,3}
print(s)
Output:
{1,2,3}

27. String to Uppercase


Code:
print("hello".upper())
Output:
HELLO

28. Simple For Loop


Code:
for i in range(3):
print(i)
Output:
0
1
2

29. While Loop


Code:
i=0
while i<3:
print(i)
i+=1
Output:
0
1
2
30. Dictionary Keys
Code:
d={"a":1,"b":2}
print(list([Link]()))
Output:
['a','b']

You might also like