[Go to site: main page, start]

0% found this document useful (0 votes)
671 views9 pages

Python Practice Codes and Examples

The document provides instructions and examples of Python code for practicing common programming tasks like calculating sums, factorials, areas, and determining if numbers are prime. It includes 15 code snippets covering topics like arithmetic operations, conditionals, loops, functions and input/output. Links to additional online resources for more Python practice problems and solutions are also provided.

Uploaded by

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

Python Practice Codes and Examples

The document provides instructions and examples of Python code for practicing common programming tasks like calculating sums, factorials, areas, and determining if numbers are prime. It includes 15 code snippets covering topics like arithmetic operations, conditionals, loops, functions and input/output. Links to additional online resources for more Python practice problems and solutions are also provided.

Uploaded by

Sk Shahbaz Ali
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python practice codes

Instructions : Be careful while writing code syntax:

Complete all codes from the given link for more hands on with python

[Link]
[Link]
[Link]
[Link]
[Link]

1
# Python3 program to add two numbers
num1 = 15
num2 = 12
# Adding two nos
sum = num1 + num2
# printing values
print("Sum of {0} and {1} is {2}" .format(num1, num2, sum))

2
# Python3 program to add two numbers
number1 = input("First number: ")
number2 = input("\nSecond number: ")
# Adding two numbers
# User might also enter float numbers
sum = float(number1) + float(number2)
# Display the sum
# will print value in float
print("The sum of {0} and {1} is {2}" .format(number1, number2, sum))

Python Program for factorial of a number


3

Factorial of a non-negative integer, is multiplication of all integers smaller than or equal to n.


For example factorial of 6 is 6*5*4*3*2*1 which is 720.
[Link]

# Python 3 program to find

# factorial of given number

def factorial(n):

# single line to find factorial

return 1 if (n==1 or n==0) else n * factorial(n - 1);

# Driver Code

num = 5;

print("Factorial of",num,"is",

factorial(num))

4
# Python3 program to find simple interest
# for given principal amount, time and
# rate of interest.
# We can change values here for
# different inputs
P=1
R=1
T=1
# Calculates simple interest
SI = (P * R * T) / 100

# Print the resultant value of SI


print("simple interest is", SI)

5
# Python3 program to find compound
# interest for given values.
def compound_interest(principle, rate, time):

# Calculates compound interest


CI = principle * (pow((1 + rate / 100), time))
print("Compound interest is", CI)
# Driver Code
compound_interest(10000, 10.25, 5)

6
# Python program to find Area of a circle
def findArea(r):
PI = 3.142
return PI * (r*r);
# Driver method
print("Area is %.6f" % findArea(5));

7
# Python program to print all
# prime number in an interval
start = 11
end = 25
for val in range(start, end + 1):

# If num is divisible by any number


# between 2 and val, it is not prime
if val > 1:
for n in range(2, val):
if (val % n) == 0:
break
else:
print(val)

8
# Python program to check if
# given number is prime or not
num = 11
# If given number is greater than 1
if num > 1:

# Iterate from 2 to n / 2
for i in range(2, num//2):
# If num is divisible by any number between
# 2 and n / 2, it is not prime
if (num % i) == 0:
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")

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

Practice all the codes in python


[Link]

1. # Python Program to calculate the square root


2.
3. # Note: change this value for a different result
4. num = 8
5.
6. # To take the input from the user
7. num = float(input('Enter a number: '))
8.
9. num_sqrt = num ** 0.5
10. print('The square root of %0.3f is %0.3f'%(num ,num_sqrt))

10
1. # Python Program to find the area of triangle
2.
3. a = 5
4. b = 6
5. c = 7
6.
7. # Uncomment below to take inputs from the user
8. a = float(input('Enter first side: '))
9. b = float(input('Enter second side: '))
10. c = float(input('Enter third side: '))
11.
12. # calculate the semi-perimeter
13. s = (a + b + c) / 2
14.
15. # calculate the area
16. area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
17. print('The area of the triangle is %0.2f' %area)

11
1. # Python program to find the factorial of a number provided by the user.
2.
3. # change the value for a different result
4. num = 7
5.
6. # To take input from the user
7. num = int(input("Enter a number: "))
8.
9. factorial = 1
10.
11. # check if the number is negative, positive or zero
12. if num < 0:
13. print("Sorry, factorial does not exist for negative numbers")
14. elif num == 0:
15. print("The factorial of 0 is 1")
16. else:
17. for i in range(1,num + 1):
18. factorial = factorial*i
19. print("The factorial of",num,"is",factorial)

12
1. # Taking kilometers input from the user
2. kilometers = float(input("Enter value in kilometers: "))
3.
4. # conversion factor
5. conv_fac = 0.621371
6.
7. # calculate miles
8. miles = kilometers * conv_fac
9. print('%0.2f kilometers is equal to %0.2f miles' %(kilometers,miles))

1. # Python Program to convert temperature in celsius to fahrenheit


2.
3. # change this value for a different result
4. celsius = 37.5
5.
6. # calculate fahrenheit
7. fahrenheit = (celsius * 1.8) + 32
8. print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %
(celsius,fahrenheit))

13
1. # Program to check if a number is prime or not
2.
3. num = 407
4.
5. # To take input from the user
6. num = int(input("Enter a number: "))
7.
8. # prime numbers are greater than 1
9. if num > 1:
10. # check for factors
11. for i in range(2,num):
12. if (num % i) == 0:
13. print(num,"is not a prime number")
14. print(i,"times",num//i,"is",num)
15. break
16. else:
17. print(num,"is a prime number")
18.
19. # if input number is less than
20. # or equal to 1, it is not prime
21. else:
22. print(num,"is not a prime number")

14

1. # Python program to find the largest number among the three input numbers
2.
3. # change the values of num1, num2 and num3
4. # for a different result
5. num1 = 10
6. num2 = 14
7. num3 = 12
8.
9. # uncomment following lines to take three numbers from user
10. num1 = float(input("Enter first number: "))
11. num2 = float(input("Enter second number: "))
12. num3 = float(input("Enter third number: "))
13.
14. if (num1 >= num2) and (num1 >= num3):
15. largest = num1
16. elif (num2 >= num1) and (num2 >= num3):
17. largest = num2
18. else:
19. largest = num3
20.
21. print("The largest number is", largest)

15
1. # Program make a simple calculator
2.
3. # This function adds two numbers
4. def add(x, y):
5. return x + y
6.
7. # This function subtracts two numbers
8. def subtract(x, y):
9. return x - y
10.
11. # This function multiplies two numbers
12. def multiply(x, y):
13. return x * y
14.
15. # This function divides two numbers
16. def divide(x, y):
17. return x / y
18.
19. print("Select operation.")
20. print("[Link]")
21. print("[Link]")
22. print("[Link]")
23. print("[Link]")
24.
25. # Take input from the user
26. choice = input("Enter choice(1/2/3/4): ")
27.
28. num1 = float(input("Enter first number: "))
29. num2 = float(input("Enter second number: "))
30.
31. if choice == '1':
32. print(num1,"+",num2,"=", add(num1,num2))
33.
34. elif choice == '2':
35. print(num1,"-",num2,"=", subtract(num1,num2))
36.
37. elif choice == '3':
38. print(num1,"*",num2,"=", multiply(num1,num2))
39.
40. elif choice == '4':
41. print(num1,"/",num2,"=", divide(num1,num2))
42. else:
43. print("Invalid input")

Complete all codes from the given url for more hands on with python

[Link]

[Link]

[Link]

[Link]

Common questions

Powered by AI

User input handling in the temperature conversion Python script could be improved by incorporating try-except blocks to catch exceptions such as ValueError when the input cannot be converted into a float. For instance, using a try-except block will prevent the program from crashing on invalid inputs and can prompt the user to enter a correct numeric value, therefore enhancing robustness and user experience .

To accommodate high precision calculations for the area of a circle, using a more accurate representation of π (PI), such as the one provided by the math module (math.pi), would be essential instead of a hard-coded approximate value like 3.142. Additionally, transitioning from basic arithmetic operations to libraries like Decimal from Python's decimal module can further improve the precision of the computations, minimizing floating-point arithmetic errors .

To enhance the performance of the prime number finding algorithm, an algorithm such as the Sieve of Eratosthenes could be employed, which is significantly more efficient for finding all primes up to a large number. Additionally, skipping even numbers except for two, starting the divisor check from 2 up to the square root of each number, and caching already evaluated results can reduce computation time significantly .

Calculating the square root using exponentiation (num ** 0.5) is straightforward and takes advantage of Python's operator overloading for power operations. However, this approach can suffer from floating-point inaccuracies for certain input ranges. Alternative approaches, such as using the math.sqrt function, ensure higher accuracy as it is optimized at the C level for precision and performance, improving computational reliability .

Python handles input through the input() function allowing users to enter data which is read as a string. For output, Python uses the print() function to display data to the console. Strengths include simplicity and flexibility as input can be cast to any type, and print() offers easy formatting options. However, limitations arise in robust error handling as input is inherently string; developers must ensure type conversion and validation, lacking built-in mechanisms for complex format verifications without additional coding .

The recursive Python function for calculating the factorial of a number handles the cases for zero and one by using a base condition. Specifically, it returns 1 if the input number is either zero or one, as factorial(0) and factorial(1) are both defined to be 1 according to the mathematical definition of factorial .

The given Python code effectively compares three numbers to find the largest using conditional statements. Each condition checks if one number is greater than the other two, which ensures correctness. However, the code can be improved in terms of readability and efficiency using Python's built-in max() function which simplifies the logic to largest = max(num1, num2, num3), making the code more concise and eliminating branching .

Compound interest differs from simple interest in that it calculates interest on the initial principal and also on the accumulated interest of previous periods. In the given Python implementation, compound interest is calculated using the formula: CI = principle * (pow((1 + rate / 100), time)), where 'principle' is the initial amount, 'rate' is the interest rate, and 'time' is the period. The simple interest is calculated using SI = (P * R * T) / 100 where P is the principal, R is the rate, and T is the time .

Function modularization in implementing a calculator allows logical separation of operations like addition, subtraction, multiplication, and division, improving code readability and maintainability. It simplifies debugging and testing as individual functions can be tested and debugged in isolation. To structure it more efficiently, using a dictionary to map operation choices to corresponding functions can streamline extending and managing operations dynamically without altering control flow logic significantly, enhancing scalability .

The provided algorithm effectively checks for prime numbers by iterating from 2 to half of the given number (num//2) to find any divisors. If a divisor is found, it concludes the number is not prime. However, the limitation lies in its efficiency. The algorithm can be optimized to only iterate up to the square root of the number, which reduces unnecessary checks and improves performance for larger numbers .

You might also like