Python programs are identified by the file extension “.py" for example HelloWorld.py would be the python file containing the Hello World program.
A python program would contain any of the elements below
- Variables: used to provide easily identifiable names to objects example of good names for variables are x, y, z, name, boy, girl, school, this_school, my_wallet, thisSchool, myWallet, etc
- Functions: used to perform evaluations on parameters e.g. sqrt(4)
- assignments statements: used to associates variables with objects e.g. x=6
- Input statements: used to request input from the user. This are easily identified by the input() function. e.g. input(“Please enter a number: “)
- Output statements: used to display items on the screen. This are given by the print() function. e.g print(“Hello world!”)
- Comments: used to provide clarity to future programmer reading your code. Any line of code preceded by # in python is regarded as a comment and would be ignored when the program is executed.
When naming your program, function or variable, you would want to not use a reserved python word such as def, del, is, in, import, while, etc. Look at the complete list of reserved word in Python and know them by heart. The following line of code does just that.
import keyword
keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
Now that you are aware of some of the elements of a program, you should be ready to start writing your own python programs. The program below calculates the average of three numbers and displays it on the screen.
This program would output#Program to display the average of three numbers on the screen
#program name: AddThreeNums.py
num1 = 1
num2 = 2
num3 = 3
total = num1 + num2 + num3
average = total/3
print(total)
print(average)
6
2
This would be considered as a bad program because it does not inform the user of the program as to what the 6 and 2 represents. It would be ideal to display total and average next to their corresponding values. The program below is an improvement to the first
The correct output would be#Program to display the average of three numbers on the screen
num1 = 1
num2 = 2
num3 = 3
total = num1 + num2 + num3
average = total/3
print(“Total”, total)
print(“Average”, average)
Total: 6
Average: 2.0
If your program gives a different output other than the one above, then you are probably not using python 3. Note that average is a double number and to convert it to an integer, enclose it like int(average) to get the output below.
Total: 6Average: 2
Share your thoughts