Python Basics
Python program to add two numbers
Description: Write a Python program that takes two numbers from the user and prints their sum.
Rules and hints:
- Use
input()to read the numbers. input()gives a string, so convert it withint()(orfloat()for decimals).
Python program to add two numbers
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
total = num1 + num2
print("Sum =", total)
Output:
Enter first number: 12
Enter second number: 8
Sum = 20
How it works
- The two
input()calls read what the user types, as text. int()converts the text to a whole number. Without it,"12" + "8"would give128.- The sum is stored in
totaland printed.
Learn more in Python input() Function and Python Type Casting.
Python program to swap two variables
Description: Write a Python program to swap the values of two variables.
Rules and hints:
- Do it first with a third (temporary) variable.
- Then do it the Python way, in one line.
Python program to swap two variables
a = 10
b = 20
print("Before swap: a =", a, "b =", b)
a, b = b, a
print("After swap: a =", a, "b =", b)
Output:
Before swap: a = 10 b = 20
After swap: a = 20 b = 10
How it works
- The line
a, b = b, abuilds a tuple(b, a)and unpacks it intoaandb. - In many other languages you need a third variable:
temp = a,a = b,b = temp. That also works in Python. - Swapping works with any type, not only numbers.
Python program to find the area of a circle
Description: Write a Python program to calculate the area of a circle when the radius is 5.
Rules and hints:
- Formula: area = pi x radius x radius.
- Use
math.pifor the value of pi. - Round the answer to 2 decimal places with
round().
Python program for the area of a circle
import math
radius = 5
area = math.pi * radius ** 2
print("Area of the circle:", round(area, 2))
Output:
Area of the circle: 78.54
How it works
radius ** 2means radius to the power 2.math.piis 3.141592653589793, so the exact area is 78.53981633974483.round(area, 2)keeps two digits after the decimal point.
See also Python Modules to learn about import.
Python program to convert Celsius to Fahrenheit
Description: Write a Python program to convert temperature from Celsius to Fahrenheit.
Rules and hints:
- Formula: Fahrenheit = Celsius x 9 / 5 + 32.
- Use an f-string to print the result.
Python program to convert Celsius to Fahrenheit
def to_fahrenheit(celsius):
return celsius * 9 / 5 + 32
for c in (0, 100):
f = to_fahrenheit(c)
print(f"{c} C = {f} F")
Output:
0 C = 32.0 F
100 C = 212.0 F
How it works
- The function takes a Celsius value and returns the Fahrenheit value.
- The loop tests two famous values: water freezes at 0 C (32 F) and boils at 100 C (212 F).
- The
/operator always returns a float, that is why we see32.0.
Read What are f-strings? and Python Functions.