Search CSNewbs
227 items found for ""
- Computer Science Newbies
C omputer S cience P ros Official 2023 CSPros: Diyar Henry Rahul Hussain Alex B Sam Will Zain Iman Aidan Tomos Harry Alex H Alex I-C
- Python | Section 3 Practice Tasks | CSNewbs
top Python - Section 3 Practice Tasks Task One: Square Number Create a program that asks the user to input a number and then prints the square of that number - to do this, multiply the number by itself . Requirements for a complete program: Use only two lines. Include the user's number and the squared number in the print line. Remember: Break up variables and parts of a sentence in a print line by using commas. Example solutions: Enter a number: 12 The square of 12 is 144 Enter a number: 7 The square of 7 is 49 Task Two: Multiplying Numbers X Create a program that asks the user to input two numbers. Multiply the two numbers together and print the total. Requirements for a complete program: Only three lines. Use only one print line. Include the user's number and the squared number in the print line. Remember: Break up variables in a print line by using commas or plus signs between each part of the "sentence" . Example solution: Task Three: Turning 65 Create a program that asks the user to input their current age and then prints a guess of when they will turn 65. (Note this is more likely to be correct towards the end of the year – think about why). You could do this in just two lines but before trying that work out on paper the steps to calculating your own age you will turn 65. What steps did you take? Try to recreate those steps in Python. You might need to create another variable to make it easier. Example solution: Task Four: Multiplication Table Let the user enter a number then print the first five multiplications in its times table. Simple example solution: Better example solution: ⬅ 3b - Simple Calculations 4a - If Statements ➡
- Python | 4b - Mathematical Operators | CSNewbs
top Python 4b - Mathematical Operators Common Mathematical Operators When comparing two values , like in an if statement, there are a number of operators than can be used: In the example below the print line will only be executed if the temperature value is greater than 25: If we entered 25 then the print line beneath would not run because is not above 25. Alternatively, you can use the greater than or equal to sign ( >= ) : You can use the less than ( < ) and less than or equal to sign ( <= ) in a similar way (and implement an elif at the same time): Now there’s only one thing missing from this program – we need an else statement for any value that is inputted between: Can you work out which sentences would be printed if we entered 8, 10 and 24? The opposite of equal to ( == ) is not equal to ( != ). For example: Practice Task A school is putting on a quiz for sixth form students. Students enter their age and they will receive a ticket to the quiz if it is between (and including) 16 to 18. Example solution: Modulo Division to Find the Remainder The modulo operator - the percentage symbol % - will work out the remainder left over when one value is divided by another. print (30 % 6) = 0 print (30 % 7) = 2 30 ÷ 6 = 5, which is a whole number, so there is no remainder and 0 is output . 30 ÷ 7 = 4 remainder 2 ; so the remainder is output . You can use modulo with variables too: num1 = 33 num2 = 4 print ( "The remainder is" , num1 % num2) The remainder is 1 = A common use of modulo is to check if a number is odd or even . If a number has no remainder when divided by 2 then it is even . = num = int ( input ( "Enter a number: " )) if num % 2 == 0: print (num, "is even." ) else : print (num , "is odd." ) Enter a number: 400 400 is even. Enter a number: 191 191 is odd. = Modulo Div i sion Task 1 ( Remainder) Ask the user to input a whole number . Use the modulo operator ( % ) to check if there is a remainder when the user's number is divided by 5 . Print the re mainder. Example solution: Enter a number: 123 The remainder when divided by 5 is 3 Modulo Div i sion Task 2 ( Rollercoaster) Use the odd/even program above to help solve this problem: A rollercoaster only lets people on in groups of 4 . Ask the user to input a number for how many people are in their group. Check if that number is directly divisible by 4 using modulo division ( % ). If it is then print “Perfect groups of four!” Else print “You will be split up” . Example solutions: Welcome to the Hyper Coaster! How many in your group? 6 You will be split up! Welcome to the Hyper Coaster! How many in your group? 12 Perfect groups of four! Integer Division Integer division removes any decimal numbers when performing division , leaving just the integer (whole number ). In Python integer division is performed using // . print (20 / 3) print (20 // 3) = 6.666666666666667 6 Integer Div i sion Task 1 ( Integer Division by 5 ) Use an input line with int to ask the user to enter a number . Use integer division ( // ) to divide the number by 5 without keeping any decimal values . Challenge: Improve your solution by altering the print line to be more user friendly . Example solutions: Enter a number: 27 5 Enter a number: 27 5 goes into 27 5 times. Integer Div i sion Task 2 ( Plane Rows) A large plane has 6 seats in row. Input the number of passengers on the plane and use integer division to work out how many full rows will be filled. Example solution: How many passengers are there in total? 174 There will be 29 full rows on the plane. Exponent (Powers) An exponent is the number of times a value is multiplied by itself , for example 2 = 2 x 2 x 2 = 8 . The symbol to represent an exponent in Python is ** . For example: 4**2 represents 4 which is also 4 x 4 . 3 2 print (4**4) base = 5 exponent = 4 print (base**exponent) = 256 625 = Exponent Task 1 ( Square Number) Use an input line with int to ask the user to enter a number . Output the square of this number. Example solution: Enter a number: 12 12 squared is 144 Exponent Task 2 ( Custom Exponent) Use an input line with int to ask the user to enter a number, this will be the base . Make another input line with int to ask for the exponent . Use ** between the base and the exponent and print it. Challenge: Make your solution better by including the base and exponent in the print line. Example solutions: Enter the base: 7 Enter the exponent: 3 343 Enter the base: 7 Enter the exponent: 3 7 to the power of 3 is 343 ⬅ 4a - If Statements 4 c - Log ical Operators ➡
- Python | Section 2 Practice Tasks | CSNewbs
top Python - Section 2 Practice Tasks Task One: Food & Colour Ask a user to input their favourite colour and their favourite food and then print a response using both answers. Requirements for a complete program: Use only one print line. Include both of the user's answers in the print line. Include capital letters, full stops and no irregular spacing in the printed line. Remember: Break up variables in a print line by using commas or plus signs between each part of the "sentence" . Example solutions: What is your favourite colour? green What is your favourite food? cheese Yum! I'll have green cheese for dinner tonight! What is your favourite colour? purple What is your favourite food? ice cream Let's have purple ice cream for breakfast! Task Two: Trivia Question Create a program that asks the user to input an answer to a trivia question of your choice then prints the correct answer with their response too. Requirements for a complete program: Only two lines. Include capital letters, full stops and no irregular spacing in the printed line. Example solution: What is the capital city of Botswana? Windhoek Correct answer: Gaborone. Your answer: Windhoek What is the closest planet to Earth? Mars Correct answer: Mars. Your answer: Mars Task Three: Getting to School Create a program that asks the user how they get to school and how many minutes it takes them (using int ). Then print an appropriate response that uses both variables . Requirements for a complete program: Use only one print line. Include both of the user's answers in the print line. Include capital letters, full stops and no irregular spacing in the printed line. Example solution: How do you get to school? car How many minutes does it take you? 45 Really? It takes you 45 minutes to get here by car? How do you get to school? walking How many minutes does it take you? 20 Really? It takes you 20 minutes to get here by walking? ⬅ 2b - Inputting Numbers 3a - Data Types ➡
- Computer Science Newbies
C omputer S cience Newb ie s Popular CSNewbs topics: Programming PYTHON GCSE Computer Science OCR GCSE Computer Science EDUQAS OCR Cambridge Technicals Level 3 IT You are viewing the mobile version of CSNewbs. The site may appear better on a desktop or laptop . Programming HTML CSNewbs last updated: Wednesday 24th May 2023 Over 342,000 visits in the past year! About CSNewbs
- Python | CSNewbs
Pyt hon Follow the instructions in each section and try the practice tasks. At the end of each section are larger problems to solve. Pyt hon Sections The Trinket.io embedded Python editor has been phased out of the site. It can be accessed here . 0. Setting up Python Installing and Using Python 1. Printing and Variables a. Printing b. Comments c. Creating Variables d. Using Variables Section 1 Practice Tasks 2. Inputting Data a. Inputting Text b. Inputting Numbers Section 2 Practice Tasks 3. Data Types & Calculations a. Data Types b. Simple Calculations Section 3 Practice Tasks 4. Selection a. If Statements b. Mathematical Operators ( & MOD / DIV) c. Logical Operators Section 4 Practice Tasks 5. Importing from Libraries a. Random b. Sleep c. Date & Time d. Colorama e. More Libraries (math) Section 5 Practice Tasks 6. Loops a. For Loops b. While Loops Section 6 Practice Tasks 7. Subroutines a. Procedures b. Functions Section 7 Practice Tasks 8. Lists a. Using Lists b. 2D Lists c. Dictionaries Section 8 Practice Tasks 9. String Handling a. Basic String Handling b. Number Handling Section 9 Practice Tasks 10. File Handling a. Open & Write to Files b. Read & Search Files c. Remove & Edit Lines Section 10 Practice Tasks 11. User Interfaces a. Graphical User Interface 12. Authentication a. Error Handling Extended Tasks Extended Task 1 (Pork Pies) Extended Task 2 (Lottery) Extended Task 3 (Blackjack) Extended Task 4 (Vet Surgery) Extended Task 5 (Colour Collection) Extended Task 6 (Guess the Word) Extended Task 7 (Guess the Number)
- Python | 3b - Simple Calculations | CSNewbs
top Python 3b - Simple Calculations Simple Calculations in Python You can perform calculations on numbers in Python using the four main operators : print ( 89 + 47) print ( 89 - 47) print ( 89 * 47) print ( 89 / 47) = 136 42 4183 1.8936170212765957 For addition , use the plus sign + To subtract numbers, use the dash symbol – (but not an underscore _ ) For multiplication , use an asterisk * which can be made by pressing Shift and 8 on a typical keyboard. To divide numbers, use a forward slash / (but not a backslash \ ) Use a string and the calculation to make the output user friendly . print ( "53 x 7 =" , 53 * 7) = 53 x 7 = 371 Simple Calculations Task 1 ( + - * /) Print four different simple calculations, using a different operator ( + - * / ) for each. Make the output user friendly by also showing the calculation (not just the answer). Copy the divide symbol here using Ctrl and C : ÷ Example solution: 18 + 35 = 53 18 - 35 = -17 18 x 35 = 630 18 ÷ 35 = 0.5142857142857142 Using Variables in Calculations You can also perform calculations on variables . The example below has the values of the variables pre-written. You need to store the result in a variable . The total variable has been used to store the result of the multiplication. num1 = 12 num2 = 20 total = num1 * num2 print ( "The total is" , total) = The total is 240 The example below allows the user to input values . num1 = int ( input ( "Enter number one: " )) num2 = int ( input ( "Enter number two: " )) total = num1 + num2 print ( "The to ta l is" , total) Enter number one: 21 Enter number two: 82 The total is 103 = Don't leave the user in the dark, better user interfaces are clear and explain what outputted values mean: num1 = int ( input ( "Enter number one: " )) num2 = int ( input ( "Enter number two: " )) answer = nu m1 - num2 print (num1 , "-" , n um2 , "=" , answer) Enter number one: 83 Enter number two: 29 83 - 29 = 54 = Simple Calculations Task 2 ( Divide by 3) Use an input line with int to ask the user to enter a number . Divide the number by 3 and output the result . Example solution: Enter a number: 11 11 divided by 3 is 3.6666666666666665 Simple Calculations Task 3 ( Add 3 Numbers ) Make three input lines using int to ask the user to enter three numbers . Add the numbers together and output the total . Example solution: Enter the first number: 45 Enter the second number: 32 Enter the third number: 19 The total is 96 ⬅ 3a - Data Types Section 3 Practice Tasks ➡
- Python | 2a - Inputting Text | CSNewbs
top Python 2a - Inputting Text Inputting Text (Strings) in Python A string is a collection of characters (letters, numbers and punctuation) such as: “Wednesday” , “Toy Story 4” or “Boeing 747” . Use the input command to ask a question and let a user input data , which is automatically stored as a string . Variable to save the answer into. Give it a suitable name based on the input. name = input ( "What is your name? " ) = What is your name? Paulina Type your answer directly into the editor and press the Enter key. Statement that is printed to the screen. Leave a space to make the output look clearer. Once an input has been saved into a variable, it can be used for other purposes, such as printing it within a sentence : name = input ( "What is your name? " ) print ( "It is nice to meet you" , name) = What is your name? Jake the Dog It is nice to meet you Jake the Dog Always choose an appropriate variable name when using inputs. colour = input ( "What is your favourite colour? " ) print ( "Your favourite colour is " + colour + "? Mine is yellow." ) = What is your favourite colour? blue Your favourite colour is blue? Mine is yellow. Inputting Text Task 1 ( Holiday) Write an input line to ask the user where they last went on holiday . Write a print line that uses the holiday variable (their answer). Example solution: Where did you last go on holiday? Scotland I hope you had a nice time in Scotland Inputting Text Task 2 ( New Neighbour) Write an input line to ask the user for a title (e.g. Mr, Mrs, Dr). Write another input line for an object . Write a print line that uses both input variables (title and object ). Example solutions: Enter a title: Dr Enter an object: Fridge I think my new neighbour is Dr Fridge Enter a title: Mrs Enter an object: Armchair I think my new neighbour is Mrs Armchair Using a Variable Within an Input To use a variable you have previously assigned a value t o within the input statement you must use + (commas will not work). drink = input ( "What would you like to drink? " ) option = input ( "What would you like with your " + drink + "? " ) print ( "Getting your" , drink , "and" , option , "now...." ) = What would you like to drink? tea What would you like with your tea? biscuits Getting your tea and biscuits now... What would you like to drink? apple juice What would you like with your apple juice? cake Getting your apple juice and cake now... Inputting Text Task 3 ( Name & Game) Ask the user what their name is. Ask the user what their favourite game is. Use their name in the input statement for their game. Print a response with their name and the game they entered. Example solutions: What is your name? Rory Hi Rory, what's your favourite game? Minecraft Rory likes Minecraft? That's nice to know. What is your name? Kayleigh Hi Kayleigh, what's your favourite game? Stardew Valley Kayleigh likes Stardew Valley? That's nice to know. ⬅ Section 1 Practice Ta sks 2b - I nputting Numbers ➡
- Python | 12 - Error Handling | CSNewbs
Python 12 - Error Handling Errors When an error occurs in Python, you may see a chunk of red text like this. This is very useful when creating programs as it tells us the exact line of the error (10), and its type (NameError). However, a completed program should have code in place for when an unexpected error occurs – we call this exception handling . General Exception In this example, Python will attempt to run the code indented beneath try . If there are no errors then the code will stop just before except . If an error does occur then the Exception code will be run . If we enter a correct value then the program will execute normally: But if an error occurs (such as writing a string when an integer is expected) then the Exception code will run : You can add the else command to your code that will execute only if there are no errors : If a valid number is entered then the else code will be printed: If a code generating an error is entered then the except code will be printed: Practice Task 1 Create a program that asks the user to input their age. Don't forget to use the int command. Use try and except to print a message if a number is not inputted. Example solution: Specific Exceptions The Exception command used in the section above is for any general error that occurs. You can also use specific except commands for a variety of errors. Below is a program with two different specific exception commands for one try statement: If a Value Error occurs, such as when the wrong data type is entered , then related code will be printed: Or if the user tries to divide by zero then a Zero Division Error will be triggered which prints a relevant response: Other types of exception can be found here . Practice Task 2 Create a program that asks the user to input a number and then divides this value by 999. Create a Value Error and Zero Division Error exception and include an appropriate message in both. Example solution for Zero Division: ⬅ 11 - Graphical User Interfac e Extended Task 1 (Pork Pies) ➡
- Python | 8c - Dictionaries | CSNewbs
top Python 8C - Dictionaries Creating a Dictionary Dictionaries are used in Python to link items of data together . The example on this page uses a footballer dictionary which links a player with a team they played for. To define a dictionary, use curly brackets { } and separate linked data with a colon . A dictionary can be written on one line but the method below makes it easier to read: Printing Data from a Dictionary The first part of the linked data in a dictionary is called the key (e.g. each footballer in my example above). The second part of the linked data in a dictionary is called the value (e.g. each team). Example: key : value "Harry Kane" : "Tottenham Hotspur" A for loop can be used to cycle through each set of keys and values in the dictionary: Practice Task 1 a) Create a dictionary of your teachers and the subject they teach. b) Print their name and the subject they teach on each line. Example solution: Adding and Removing Data from a Dictionary Data can be added to a dictionary by stating the new key and value . You must use square brackets - [ ] The new data will be added to the end of the dictionary. You can print the whole dictionary to see any changes - e.g. print(playerdictionary) Data can be removed from a dictionary by stating the new key to remove in a pop command. You can print the whole dictionary to see any changes - e.g. print(playerdictionary) The whole dictionary can be cleared (reset to blank) using the clear command. Practice Task 2 a) Ask the user to enter a new teacher and their subject. b) Ask the user to remove a teacher. c) Print the list of teachers and check the new teacher has been added and the other one removed. Example solution: Searching Through a Dictionary An if statement can be used to check if a specific key is in a dictionary. If the key is in the dictionary then a message can be displayed using the key and the value . Otherwise, an else statement can output an appropriate response. To search for a value in a dictionary a for loop should be used to cycle through each key . If the value of each key matches the value that is being searched for then it will be printed. Practice Task 3 a) Create a search that allows a user to enter a teacher's name and prints the subject that they teach. b) Include an else statement to print a response if a teacher is not in the dictionary. Example solution: Changing Data & Copying a Dictionary The way to change values is similar to adding new data. The first input below is to determine the key and the second input determines the new value to be changed to. The copy command is used to make a duplicate of a dictionary . Practice Task 4 a) Create a copy of your teacher dictionary. b) Allow the user to enter a teacher and a new subject that they teach. c) Print the copy of the dictionary with the new values. Example solution: Using a Dictionary to Make a Game The code below is used to make a puzzle game where the user has to type in a footballer and the team they played for. I have added comments to explain the different parts of the code. A separate list has been created at the start to store the names of keys (players) that been correctly guessed . A while loop is used to constantly ask the user for players and teams. When they have guessed all 10 players (and the correct list reaches 10 ) the loop breaks and the game end. Instead of a further practice task here, Task 6 of the Section 8 Practice tasks page challenges you to make a similar game using a dictionary. ⬅ 8b - 2D Lists Section 8 Practice Tasks ➡
- Python | Extended Task 2 | CSNewbs
Extended Task 2 Lottery 17 8 4 13 20 Create a program to simulate a lottery draw. First, create an appropriate print line to welcome the user to your lottery draw. Then let the user enter five numbers between 1 and 20. Next, randomise five numbers between 1 and 20. Check to see how many numbers match and output an appropriate response for each scenario (e.g. “You have not matched any numbers, better luck next time!”) Once you have made the base program implement subroutines and lists . Make it as efficient as possible and professional-looking. Use pauses to reveal each number one at a time like a real lottery draw to build suspense. For this task, you will need to create a document and include the following sections (with screenshots where appropriate): An introduction to explain the Purpose of your program . A List of Requirements for a successful program. Screenshots of your code (with comments in your code to show understanding). Testing – Create a plan to show how you will test your program and then explanations of any errors that you found and how they were fixed . An Evaluation of what worked, what didn’t, and how you met each of your requirements from your original list. Also, discuss further improvements that you could have made to improve your program. Example solution: Helpful reminders for this task: Inputting Numbers Random Numbers Logical Operators Subroutines ⬅ Extended Task 1 (Pork Pies) Extended Task 3 (Blackjack) ➡
- Python | 10c - Remove & Edit Lines | CSNewbs
Python 10c - REMOVE & Edit LINES Splitting a File The split command is used to split up a line of a file into different parts . The character or string in brackets after the split command is the value that will denote each split . In the example below I have split the file at each comma . Remember that Python numbering starts at 0 so the first section is 0, not 1. 0 1 2 3 The program below splits each line of the file at each forward-slash ( / ). The printed statement is the employee's first name, surname and job position. 0 1 2 3 4 Practice Task 1 Create a file (new txt document in Notepad) called movies. Type in the movie name, main actor, genre (e.g. horror), year it was released and your rating out of 10. Print just the movie name and year it released. Example solution: Deleting Lines in a File Exact Line Name The code below shows how to remove a line from a file using the exact name of the line , which will only work for short or simple files . First open the file in read move to save each line in a variable I've named lines. Then ask the user to input the exact line they want to remove (e.g. 'plum' in my example). Then open the file in write mode and use a for loop to read each line and only write it back into the file if it isn't equal to the line the user entered - such as 'plum'. The line.rstrip() command is important as it removes any spaces or empty lines that may interfere with matching the line to the input. Deleting Lines in a File Word in the Line The code below shows how to remove a line from a file if a certain word appears in that line , although this could be dangerous with large files. In my example I have written apple which has also removed pineapple! The difference from the previous program is to change the for loop so that it checks if the inputted word appears in the line . If it does appear then nothing happens (except a print statement to acknowledge it's been found). If the word doesn't appear then that line can be safely rewritten to the file . Practice Task 2 Download the trees text file. Give the user a choice of removing a specific tree or a type of tree. If they choose a specific tree then remove the line if it is an exact match (e.g. Field Maple). If they choose to remove a type of tree remove all lines that contain the name of that tree (e.g. willow) Make sure you actually check the file to see if the lines have been removed correctly! Example solution: Download the trees file: Sorting a File Sorting a file into alphabetical (or numerical ) order is a simple process. Open the file in read mode and save the lines into a list . The sort c ommand will automatically order the list of lines. If necessary, in the brackets type reverse = True to sort the list in reverse. Practice Task 3 Expand on your tree program from the previous practice task. As well as SPECIFIC or TYPE, allow the user to enter SORT to sort the tree file either in alphabetical order or reverse alphabetical order. Check the text file to see if it has been sorted correctly. You may make this a separate program from task 2 if you wish. Example solution: Editing Lines in a File Overwriting data in a file is a tricky process. The program below uses the same Employees.txt file as above but allows the user to change the address of an employee . A temporary file is created to store the lines of the employee file, but the line with the changes is replaced specifically with the new address. I have explained each line of the program to the right: When I executed the program below I entered Thomas Wynne's details and changed his address. When I opened the employees file the address had been updated : 1: Importing os allows me to rename and remove files later in the program. 3: Opens the employee file in read mode . 5 - 8: Input lines allow the user to enter the first name, surname and the person's new address. 10: A found flag is set up and set to False . 12: The for loop cycles through each line in the file. 13: Each line is split into separate parts from each / . 15: An if statement checks if the first name and surname match an employee in the file. 16: A replacement line is created by putting the original line together but with the new address. 18: The found flag is changed to True because the employee first name and surname matched . 19: A temporary file is created and opened in write mode . 20: The seek command restarts the file at line 0 . 22: The for loop cycles through each line of the employee file from the beginning. If the first name and surname match it will write the new line to the file, otherwise it will rewrite the original line . 28 & 29: Both files are closed . 31 & 32: If the names didn't match , an appropriate message is printed. 34 - 37: If the address was changed, the original file is renamed and deleted and the temp file is renamed as the original file. Practice Task 4 Use the movie file you created for practice task 1. Ask the user to enter the name of a movie. Ask them to enter an updated rating out of 10. Update the file to change the rating to the new value. Example solution: ⬅ 10b - Read & Search Files Section 10 Practice Tasks ➡