# This program prints Hello, world!
print('Hello, world!')
_______________________________________________________
# This program adds two numbers
num1 = 1.5
num2 = 6.3
# Add two numbers
sum = num1 + num2
# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
Step-by-Step Explanation
1. Comment Line
# This program adds two numbers
• This is a comment in Python.
• Comments start with # and are ignored by the Python interpreter.
• They are useful for explaining what the code does.
2. Declaring Variables
num1 = 1.5
num2 = 6.3
• num1 and num2 are floating-point numbers (decimal numbers).
• 1.5 and 6.3 are stored in these variables.
3. Adding the Numbers
sum = num1 + num2
• The + operator adds num1 and num2.
• The result is stored in the variable sum.
• In this case: sum=1.5+6.3=7.8
4. Displaying the Sum
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
• The print() function outputs text to the screen.
• format() method is used to insert values into the string:
o {0} is replaced with num1 (1.5).
o {1} is replaced with num2 (6.3).
o {2} is replaced with sum (7.8).
Formatted Output:
The sum of 1.5 and 6.3 is 7.8
# Store input numbers
num1 = input('Enter first number: ')
num2 = input('Enter second number: ')
# Add two numbers
sum = float(num1) + float(num2)
# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
_______________________________________________________________
Step-by-Step Explanation
1 Taking User Input
num1 = input('Enter first number: ')
num2 = input('Enter second number: ')
• The input() function is used to take input from the user.
• The text inside input('...') is displayed as a prompt.
• Whatever the user enters is stored as a string in num1 and num2.
Example Input (User Types in Terminal):
Enter first number: 5.5
Enter second number: 4.5
At this point:
• num1 = "5.5" (as a string)
• num2 = "4.5" (as a string)
2 Converting Strings to Floating-Point Numbers
sum = float(num1) + float(num2)
• input() always returns a string, so we need to convert it to a number.
• float(num1) converts "5.5" (string) to 5.5 (float).
• float(num2) converts "4.5" (string) to 4.5 (float).
• The + operator then adds the two numbers.
Calculation:
sum = 5.5 + 4.5
sum = 10.0
3 Displaying the Sum
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
• The print() function is used to display the result.
• .format() method replaces {0}, {1}, and {2} with actual values.
o {0} → num1 (5.5)
o {1} → num2 (4.5)
o {2} → sum (10.0)
Example Output:
The sum of 5.5 and 4.5 is 10.0