Inputting & Outputting Data in Python
Outputting Data
Inputting Data
Example program 1 - Enter a Word
The code for the program below will allow the user to enter a word and store it in a variable called word. It will then use the print()function to output the word that they entered. The result when the program is run in IDLE is shown on the right.
Example program 2 - Address Program
The code for the program below will allow the user to enter various pieces of information and store them in different variables. The print() function is then used to output all of the information.
When run in IDLE:
You can concatenate (join together) variables with strings in a print() function. In the address example print("Street: " + number + " " + street + "\nTown/City: " + town) will combine the strings “Street” and “Town/City” with the variables number, street and town.
\n is used to start a new line when it is displayed on screen. |
Variables
A variable is used to temporarily store a piece of data.
For example: In the code above the variable is called number1 and the value it is storing is 10. Variables can hold any type of data. Using variables makes it easier for people to the understand what is going on.
For example: Casting Variables |
Python will automatically decide what type of data a variable should be, sometimes this isn’t right, therefore you will have to convert/cast variables to a different data type.
Integer
The program below will multiply a number by 5. When data is input from the user it will store it as a string. You will need to convert the variable number to an integer before performing a calculation. Two examples are shown below. In the first example, the input is left as a string, in the bottom example it is cast as an integer. The results of both programs are shown bottom right.
Real / Float
The program below will ask the user to enter their weight in kilograms (this could be a decimal) and convert it to pounds. You will need to convert the variable kg to a float before converting it. An example of how you do this is shown below with the result shown on the right.
Strings
Using the program above, if you wanted to improve the print message so that it said Your weight in pounds is X you would need to convert the variable pounds to a string as it is currently a float.
This is what would happen if you ran the code currently:
This is because the variable pounds is a float and to be joined with a string in the print message it needs to be converted to a string, The code is below left with the result in IDLE on the right.
Example program 1 - Water Tank Capacity Program
The code for the program below will allow the user to enter the height, width and depth of a water tank, then calculate and output the capacity.
The code above rounds the variable capacity, to round a variable you use the round() function. You write the name of the variable followed by the number of decimal places e.g. round(capacity,2).
Example program 2 - Cylinder Volume Program
The code for the program below will allow the radius and height of a circle, then calculate and output the volume and surface area.
When run in IDLE:
Selection (if, then, else)
Sometimes you will change what do you depending on the conditions.
For example: IF you wake up in the morning and it is raining THEN you will take a coat to school OTHERWISE you wont.
IF the day is a Saturday AND the alarm clock goes off THEN you might turn it off and stay in bed OTHERWISE you might get up.
Life is full of decisions that you will make depending on certain conditions, computers are no different.
For example: IF you wake up in the morning and it is raining THEN you will take a coat to school OTHERWISE you wont.
IF the day is a Saturday AND the alarm clock goes off THEN you might turn it off and stay in bed OTHERWISE you might get up.
Life is full of decisions that you will make depending on certain conditions, computers are no different.
if-else
For a computer to make decisions based on a condition, you must use an IF statement, it has the following structure:
Consider the following IF statement:
The IF statement explained:
after the if is the condition age >= 18 followed by a colon, this is checking to see if the age variable is more than or equal to 18.
after that line is code is the code that will only be run if that condition is True. If it is true it will print on screen You are an adult.
the word else then follows followed by a colon. The instructions underneath this are what will be run only if that condition is False. If it is false it will print on screen You are still a child.
after the if is the condition age >= 18 followed by a colon, this is checking to see if the age variable is more than or equal to 18.
after that line is code is the code that will only be run if that condition is True. If it is true it will print on screen You are an adult.
the word else then follows followed by a colon. The instructions underneath this are what will be run only if that condition is False. If it is false it will print on screen You are still a child.
if-elif-else
An IF statement with an else will only allow you to check a single condition, however if you have more than one condition to check you can use if..elif..elseAn IF statement with an else will only allow you to check a single condition, however if you have more than one condition to check you can use if..elif..else
Consider the following IF statement:
Consider the following IF statement:
The IF statement explained:
- the program first checks to see if the colour entered is Red and if it is will print STOP.
- if the colour entered isn’t red it will go onto the next condition where the elif is and check if the colour is Amber. If it is then it will print GET READY TO STOP
- if neither conditions are met it will go to the else part of the code and print GO
- Note: It doesn’t need to use elif to see if the colour is Green as if it isn’t Red or Amber it must be Green, therefore you can just use else if there are not other options to consider.
Example program 1 - Capital City
The code for the program below ask the user the capital city of England and display a suitable message depending on whether they enter London.
When run in IDLE:
Example program 2 - Grade Calculator Program
The code for the program below will ask the user to enter a score on a test and then decide what grade they got.
NOTE: When elif is used it will only check the next condition if the previous condition is false.
When run in IDLE:
When run in IDLE:
Example program 3 - Taxi Fare Calculator Program
The code for the program below will calculate the fare for a taxi ride depending on the distance and number of passengers. It should add 50% onto the total if there are more than 5 passengers.
When run in IDLE:
Validating Data
What is Validation?
Validation is the process of checking to see if data that is entered meets a set of requirements, this does mean it will always stop incorrect data being entered. For example if you had to enter a telephone number, you could validate it and say it needs to be 11 digits starting with a 0. The user could enter 01234567891, this meets the requirements set, but does not mean it is a valid telephone number.
There are some simple ways in which you can validate programs, these are:
There are some simple ways in which you can validate programs, these are:
- Type Check - checking the data is of a particular type before continuing
- Presence Check - checking that data is entered before continuing
- Range Check - checking that data is between two boundaries set
- Format Check - checking that data follows a set format
Type Check Example
In Python you can easily do a type check to check whether a value is a number or not a number, see the example below:
variable.isdigit() will return a value either True or False after checking to see if a variable is a number. You can then use an If to determine what to do.
When run in IDLE:
When run in IDLE:
Presence Check Example
In Python you can use the len() function to find the length of a variable or form control. You can then check to if the length is 0 and if it is this means nothing has been entered, see the example below:
When run in IDLE, first with nothing entered, then with something entered:
Range Check Example
You can also validate data by making sure it is within a certain range. For example, entering a test score you could say that it must be between 0 and 100. An example of how you could use a range check is shown below:
To perform a range check you can simply use an if and then use and to connect 2 conditions together.
This is what happens when the program is run in IDLE:
This is what happens when the program is run in IDLE:
Format Check Example
If you want to perform a format check in Python you will need to make use of a library. The Regular Expressions library allows you to set a pattern and then check to see if the data follows that pattern.
Below are some examples of Regular Expressions patterns as well as what they mean:
Below are some examples of Regular Expressions patterns as well as what they mean:
The program below will check if an email meets the right format requirements. For the purpose of this task the requirements are:
- it must start with at least one alphanumeric character
- followed by the @ sign
- followed by at least one alphanumeric character
- followed by a full stop (.)
- followed by at least one alphanumeric character.
This is what happens when run in IDLE:
Iteration - Count Controlled
Iteration is the process of repeating a process over and over. Often in programming you need to repeat a block of code several times.
FOR Loops
A for loop is known as a count controlled loop, you should use it when you want to repeat a block of code for a set number of times.
How the for loop works
- a for loop will repeat for a set number of times and it will repeat between two ranges. range(min_value,max_value) will repeat between the bottom and the top value but not include the top value.
- i is just a variable that is a counter and stores the number in the loop, this is useful if you need to use it in calculations.
Example Program 1 - Name Repeater Program
This program asks the user to enter their name and their age. It will then display their name the same number of times as their age,
The result in IDLE is shown below. As the user is 7 years old the name is repeated 7 times,
Example Program 2 - Timestable Program
This program will ask the user what timestable they want to learn, it will then calculate the timestables for that number. It makes use of the counter (x) in the loop to calculate the answer.
When run in IDLE:
Example 3 - Finding the average of numbers in a list
This program has a list that contains test scores. The program will go through the list and add together all the numbers to get a total. It then works out the average of the test scores.
When run in IDLE:
This program gives the average of 9 based on the values in the scores list. This is because 10 + 12 + 7 + 6 + 10 = 45. This is then divided by the size of the list (5) to give 9.
Iteration - Condition Controlled
Iteration is the process of repeating a process over and over. Often in programming you need to repeat a block of code several times.
WHILE Loops
A while loop is known as a condition controlled loop, you should use it when you do not know how many times the code needs to repeat as you can say repeat while a condition is True.
There are two approaches to writing code for a while loop:
1. While loop using a standard variable See the code on the right. -----> Line 1 simply creates an empty variable called quit. The next line will execute the code within the loop until the user enters y (remember != means not equal to). Line 3 is code is indented within the while loop meaning it will be executed until the user meets the condition. Line 4 shows the message which is output when the loop breaks. 2. While loop using a Boolean variable Using Boolean variables to control a while loop is very common. In the example shown we initiate a variable called quit. This is set to false as default. The while begins by checking that quit is still equal to false. The if selection allows the while loop to check for an input y. Once this happens quit becomes true and an appropriate message is printed. The screenshot is the same for a reason, they do the same thing! You will find uses for both types of loop syntax so its useful to be aware of both. |
Example of a while loop using a list
year_group = int(input('Enter your year group: '))
while year_group not in [7,8,9,10,11]: # uses an array to hold the valid options print ('Invalid input') year_group = int(input('Enter your year group: ')) Example of a while loop using 2 conditionsyear_group = int(input('Enter your year group: '))
while year_group <7 or year_group > 11: # uses comparison operators to compare the values print ('Invalid input') year_group = int(input('Enter your year group: ')) |
This video goes over sequencing, selection and iteration. |
File handling - remember that your text file and your Python file MUST be stored in the same folder.
Reading files - use the text files to practice
|
|
Writing to text files
To write to a text file you open the file but in either append "a" mode or write "w" mode.