EXERCISE
Write a program that calculates the area of a square and prints the area of the square.
Try your hands on this exercise before looking at the solution below.
SOLUTION
In this program, we will create two variables named length and width and store the value of our preference in the variables; in this case, I chose 4 and 6. We could have used actual variables like x and y for the length and width, but when the program becomes more complex, it may seem confusing.
Let's save our program using Command S or Control S and run our program to see if it is working.
And it is working. We can also change the value of our variables and run it by pressing F5.
You can also do similar operations using the division sign (/), addition sign (-), etc.
Our program is too static; anytime we want to change a variable, we have to change something in the code. In our next tutorial, we will learn how to make our program more dynamic. We will learn how to assign user input to a variable.
SUMMARY
print("This program calculates the area of a square") length = 6 width = 10 print("The length and width of the square are", length, "and", width, "respectively") print("The area of the square is:", length * width) Output: This program calculates the area of a square The length and width of the square are 6 and 10 respectively The area of the square is: 60 >>>
No comments:
Post a Comment