top of page

Search CSNewbs

286 items found for ""

  • 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: Friday 16th August 2024 Over 470,000 visits in the last year! About CSNewbs

  • Python | 8a - Using Lists | CSNewbs

    top Python 8a - Using Lists Lists A list is a temporary data structure . Any changes made to the list while the program is running will not be saved the next time it is run . Data can be added to and removed from lists so they can change in size (unlike an array which is fixed and not used in Python). ​ It is important to note that each data element in a list has an index so that it can be specifically referenced (to delete it for example) and that indexes start at 0 . A list of the rainbow colours in order would start at 0 like this: Creating & Printing Lists Lists use square brackets in Python. Separate list items with commas . Strings must use speech marks and integers do not use speech marks. people = [ "Alan" , "Jesse" , "Max" , "Jack" ] years = [ 2010, 2019, 2001, 2016 ] There are many different ways to print items from a list depending on how you want it to look . Print all items on one line Type the list name into a print command to output the complete list . Typing an asterisk * before the list name removes punctuation . cities = [ "Shanghai" , "Sao Paolo" , "Bishkek" , "Asmara" ] print (cities) cities = [ "Shanghai" , "Sao Paolo" , "Bishkek" , "Asmara" ] print (*cities) ['Shanghai', 'Sao Paolo', 'Bishkek', 'Asmara'] Shanghai Sao Paolo Bishkek Asmara Print each item on a separate line To print a list line-by-line use a for loop to cycle through each item. ​ 'city ' is just a variable name and can be replaced with the traditional 'i ' or anything relevant to the context, such as 'colour ' in a list of colours or 'name ' in a list of people. cities = [ "Shanghai" , "Sao Paolo" , "Bishkek" , "Asmara" ] for city in cities: print (city) Shanghai Sao Paolo Bishkek Asmara Print separated items on one line To print separated data elements on the same line then you can use the end command which defines what should go after each item . ​ The example below uses slashes but end = " , " would add comma and space between each element. cities = [ "Shanghai" , "Sao Paolo" , "Bishkek" , "Asmara" ] for city in cities: print (city, end = " / " ) Shanghai / Sao Paolo / Bishkek / Asmara / Print specific list items To print an element with a certain index , put the index in square brackets . But remember that the index starts at 0 not 1. cities = [ "Shanghai" , "Sao Paolo" , "Bishkek" , "Asmara" ] for city in cities: print ( "The first city is" , cities[0]) print (cities[2], "is the third city" ) The first city is Shanghai Bishkek is the third city Create a list of five different of foods . ​ Print all list items on one line . ​ Then print each item on a different line . ​ Finally print just the first and fifth items . Example solution: lettuce yoghurt tomato artichoke tuna lettuce yoghurt tomato artichoke tuna The first item is lettuce The fifth item is tuna Lists Task 1 (Five Foods ) Lists Task 2 (Four Numbers ) Create a list of four integer values . ​ ​ Print all list items on one line separated by colons . Example solutions: 345:123:932:758: 812:153:783:603: Add (Append / Insert) to a List Append items to the end of a list To add a new item to the end of a list use the .append() command. ​ ​ Write .append() after the name of your list, with the new data in brackets . pets = [ "dog" , "cat" , "hamster" ] pets.append( "rabbit" ) print (*pets) fillings = [ "ham" , "cheese" , "onion" ] extra = input ( "Enter another filling: " ) fillings.append(extra) print ( "Your sandwich:" , *fillings) dog cat hamster rabbit Enter another filling: lettuce Your sandwich: ham cheese onion lettuce Insert items to a specific index Use the insert command to place an item in a specific position within the list. Remember that Python counts from 0 so the medals example below puts "silver" as index 2 , which is actually the 3rd item . medals = [ "platinum" , "gold" , "bronze" ] medals.insert(2, "silver" ) print (*medals) names = [ "Stacy" , "Charli" , "Jasper" , "Tom" ] name = input ( "Enter a name: " ) position = int ( input ( "Enter an index: " )) names.insert(position,name) print (*names) platinum gold silver bronze Enter a name: Lena Enter an index: 0 Lena Stacy Charli Jasper Tom Enter a name: Pat Enter an index: 3 Stacy Charli Jasper Pat Tom Use a loop to add items to a list A for loop can be used to add a certain number of items to a list. A while loop can be used to keep adding values until a certain value (e.g. ' stop ' or ' end ') is input. animals = [ ] ​ for i in range (4): animal = input ( "Enter an animal: " ) animals.append(animal) ​ print ( "\nAnimals:" , *animals) animals = [ ] while True : animal = input ( "Enter an animal: " ) if animal == "stop" : break else : animals.append(animal) print ( "\nAnimals:" , *animals) Enter an animal: lion Enter an animal: horse Enter an animal: hyena Enter an animal: squirrel ​ Animals: lion horse hyena squirrel Enter an animal: rhino Enter an animal: gazelle Enter an animal: deer Enter an animal: stop ​ Animals: rhino gazelle deer Example solution: Lists Task 3 (Favourite Musicicans ) Create a list of three musicians or bands you like . ​ ​ Print the list . ​ ​ ​ Then append two new bands using two inputs . ​ ​ ​ Print the list again. ​ Use the sandwich filling example for help. Musicians I like: Lana Del Rey Devon Cole Elly Duhé ​ Enter another musician: Charli XCX Enter another musician: Kenya Grace ​ Musicians I like: Lana Del Rey Devon Cole Elly Duhé Charli XCX Kenya Grace Lists Task 4 (Missing 7 ) Create a list of numbers in order from 1 to 10 but miss out 7 . ​ Use the insert command to add 7 in the correct place . ​ Print the list before and after you insert 7. Example solution: 1 2 3 4 5 6 8 9 10 1 2 3 4 5 6 7 8 9 10 Lists Task 5 ('Land' Countries ) Use a while True loop to input countries that end in 'land' until the word 'finish ' is input . ​ Print the list at the end. ​ Note: You do not need to check if the countries entered are correct. There are also more than four. Example solution: Enter a country ending in 'land': Iceland Enter a country ending in 'land': Poland Enter a country ending in 'land': Switzerland Enter a country ending in 'land': Thailand Enter a country ending in 'land': finish ​ Country list: Iceland Poland Switzerland Thailand Delete (Remove/Pop) from a List Delete items with a specific value To delete data with a certain value use the .remove() command, with the value in brackets . trees = [ "fir" , "elm" , "oak" , "yew" ] trees.remove( "elm" ) print (*trees) fir oak yew trees = [ "fir" , "elm" , "oak" , "yew" ] tree = input ( "Select a tree to remove: " ) trees.remove(tree) print (*trees) Select a tree to remove: oak fir elm yew Delete items with a specific index To delete data in a specific position in your list use the .pop() command, with the position in the brackets . ​ Remember that indexes start at 0 so .pop(0) removes the first item . Negative values start from the end of the list , so -1 is the final item and -2 is the second last item and so on. kitchen = [ "plate" , "cup" , "spoon" , "jug" ] kitchen.pop(0) print (*kitchen) kitchen = [ "plate" , "cup" , "spoon" , "jug" ] kitchen.pop(-2) print (*kitchen) kitchen = [ "plate" , "cup" , "spoon" , "jug" ] index = int ( input ( "Select an index: " )) kitchen.pop(index) print (*kitchen) cup spoon jug plate cup jug Select an index: 1 plate spoon jug Delete all items in a list To delete data in a list use the .clear() command. insects = [ "ant" , "bee" , "wasp" ] insects.clear() insects.append( "hornet" ) print (*insects) hornet Lists Task 6 (Day Off ) Example solution: Create a list with the five week days . ​ Ask the user to input a weekday and remove that day from the list. ​ Print the list. Which day do you want off? Tuesday Your new days of work: Monday Wednesday Thursday Friday Lists Task 7 (May and October ) Create a list with the twelve months in order . ​ ​ Delete May and then October using the pop command by referring to their indexes in the list. Print the list. ​ Note: Be aware the index of each month after May will change when May is popped from the list. Example solution: January February March April June July August September November December Finding the Length of a List To find the length of a list use the len function. You can create a separate variable for the length (shown in the first example below) or use the len command directly (second example). states = [ "Maine" , "Utah" , "Ohio" , "Iowa" ] length = len (states) print ( "There are" , length , "states in the list." ) states = [ "Maine" , "Utah" , "Ohio" , "Iowa" ] print ( "There are" , len (states), "states in the list." ) There are 4 states in the list. Lists Task 8 (Q Words ) Use a while True loop to input words beginning with q until the word ' stop ' is entered. ​ Then use len to find the length of the list and print this value. ​ Note: You do not need to check if the entered words actually start with q. Example solution: Input a Q word: question Input a Q word: quick Input a Q word: quiet Input a Q word: quandry Input a Q word: stop ​ You wrote 4 Q words! Cycle Through List Items A for loop can be used to cycle through each item in a list. The following examples present some ways that this may be used. ​ ​ This program uses a for loop to add a word (David) before each list item. davids = [ "Beckham" , "Attenborough" , "Schwimmer" , "Tennant" , "Lynch" ] for i in range (5): print ( "David" , davids[i]) David Beckham David Attenborough David Schwimmer David Tennant David Lynch An if statement can be used within a for loop to check the value of each item . The example below checks how many items are 'medium'. sizes = [ "small" , "medium" , "small" , "large" , "medium" , "small" ] count = 0 ​ for i in range (6): if sizes[i] == "medium" : count = count + 1 print ( "There were" ,count, "medium choices." ) There were 2 medium choices. The program below uses a while loop to allow entries until 'stop ' is input then a for loop to check the value of each item . ​ Because the final length of the list is not known when the program starts, the len command is used in the range of the for loop . sports = [] fcount = 0 rcount = 0 ​ while True : option = input ( "Choose football or rugby: " ) sports.append(option) if option == "stop" : break for i in range ( len (sports)): if sports[i] == "football" : fcount = fcount + 1 elif sports[i] == "rugby" : rcount = rcount + 1 ​ print ( "\nResults:" ,fcount, "people chose football and" ,rcount, "chose rugby." ) Choose football or rugby: rugby Choose football or rugby: rugby Choose football or rugby: football Choose football or rugby: rugby Choose football or rugby: football Choose football or rugby: stop ​ Results: 2 people chose football and 3 chose rugby. Lists Task 9 (Over 25 ) Create a list with the following eight numbers: 13, 90, 23, 43, 55, 21, 78, 33 ​ Use a for loop to cycle through the list and check if each item is over 25 . Use a count variable to increase by 1 if the number is over 25. ​ At the end print how many numbers are over 25 - there are five . Example solution: 5 numbers are over 25. Lists Task 10 (Favourite Lesson ) Use a while True loop to keep inputting school subjects until ' done ' is entered. ​ Keep a count of how many times ' Maths ' is entered. ​ Print the total number of people who entered maths. Example solution: Enter a subject: English Enter a subject: Maths Enter a subject: Art Enter a subject: Maths Enter a subject: History Enter a subject: done ​ There were 2 people who chose maths. Sorting Lists The .sort() command will sort elements in a list into alphabetical order (if a string ) or numerical order (if a number ). names = [ "Robb" , "Jon" , "Sansa" , "Arya" , "Bran" , "Rickon" ] print ( "Original:" , *names) ​ names.sort() print ( "Sorted:" , *names) Original: Robb Jon Sansa Arya Bran Rickon Sorted: Arya Bran Jon Rickon Robb Sansa numbers = [56,98,23,12,45] numbers.sort() print (*numbers) 12 23 45 56 98 The .sort() command can be used to sort values in descending order by including reverse = True in the brackets. names = [ "Robb" , "Jon" , "Sansa" , "Arya" , "Bran" , "Rickon" ] print ( "Original:" , *names) ​ names.sort(reverse = True ) print ( "Sorted:" , *names) Original: Robb Jon Sansa Arya Bran Rickon Sorted: Sansa Robb Rickon Jon Bran Arya numbers = [56,98,23,12,45] numbers.sort(reverse = True ) print (*numbers) 98 56 45 23 12 Lists Task 11 (Sorted Fruit ) Example solution: Use a for loop to append six fruits to an empty list. ​ Sort the list into alphabetical order and print it. Enter a fruit: strawberry Enter a fruit: kiwi Enter a fruit: lemon Enter a fruit: pear Enter a fruit: orange Enter a fruit: mango Sorted fruit: kiwi lemon mango orange pear strawberry Searching Through Lists A simple if statement can be used to see if a certain value appears within a list. names = [ "Alex" , "Bill" , "Charlie" , "Darla" ] ​ name = input ( "Enter a name: " ) if name in names: print ( "Yes," , name , "is in the list." ) else : print ( "Sorry," , name , "is not in the list." ) Enter a name: Bill Yes, Bill is in the list. Enter a name: Sadie Sorry, Sadie is not in the list. Lists Task 12 (Packed Suitcase ) Example solutions: Create a list with five items to take on holiday. ​ Ask the user to input an item and use an if statement to check if it is or isn't in the list. What should I pack? sun cream I've already packed sun cream What should I pack? tootpaste Whoops! I forgot to pack tootpaste Calculating the Sum of a List To calculate the sum of a list of numbers there are two methods. Using Python's built-in sum function : numbers = [1,4,2,3,4,5] print ( sum (numbers)) Both methods will result in the same output : 19 Using a for loop to cycle through each number in the list and add it to a total . numbers = [1,4,2,3,4,5] ​ total = 0 for number in numbers: total = total + number print (total) Lists Task 13 (Sum and Average ) Example solution: Use a for loop to ask the user to input 5 numbers and append each to a list. ​ Use the sum command to output the total and use it calculate the average . Enter a number: 6 Enter a number : 7 Enter a number : 6 Enter a number : 9 Enter a number : 4 The total is 32 The average is 6.4 Extending a List .extend() can be used in a similar way to .append() that adds iterable items to the end of a list . ​ This commands works well with the choice command (imported from the random library ) to create a list of characters that can be randomly selected. ​ The code below adds a lowercase alphabet to an empty list and then, depending on the choice of the user, adds an uppercase alphabet too. The choice command is used in a loop to randomly select 5 characters. Using .extend() to make a random 5-character code from random import choice list = [] list. extend ( "abcdefghijklmnopqrstuvwxyz" ) ​ upper = input ( "Include uppercase letters? " ) if upper == "yes" : list. extend ( "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ) ​ code = "" for number in range (5): letter = choice (list) code = code + letter print ( "Your five character code is" , code) Possible outputs: Include uppercase letters? yes Your five character code is yPfRe Include uppercase letters? yes Your five character code is GJuQw = Include uppercase letters? no Your five character code is gberv Extend treats each character as an indidual item whereas append adds the whole string as a single entity . ​ Most of time append would be used, but extend is suitable for a password program as additional individual characters can be added to a list depending on the parameters (e.g. lowercase letters, uppercase letters, numbers and special characters). list = [] list. extend ( "ABCD" ) list. extend ("EFGH" ) print (list) list = [] list. append ( "ABCD" ) list. append ("EFGH" ) print (list) ['A','B','C','D','E','F','G','H'] ['ABCD' , 'EFGH'] = = Practice Task 14 Use the code above (for a 5-character code ) to help you make a password generator . ​ Ask the user if they want uppercase letters , numbers and special characters and use the extend command to add them to a list of characters if they type yes (you should extend lowercase characters into an empty list regardless, like in the code above). ​ Use a for loop and the choice command (imported from the random library) to randomly generate a 10-character password . Example solutions: Include uppercase letters? yes Include numbers? yes Include special characters? yes Your new password is RjWSbT&gW5 Include uppercase letters? no Include numbers? yes Include special characters? no Your new password is hdf8se9y2w ⬅ Section 7 Practice Tasks 8b - 2D Lists ➡

  • Python | Setting up Python | CSNewbs

    Setting up Python Downloading Python If you are using Python in Computer Science lessons, then your school should already have it downloaded and installed on the school computers. ​ It is a good idea to download it on a home computer too so you can practice outside of lessons. Python is free and can be downloaded from the official website. You should download the most up-to-date version of Python 3. ​ Save the file and then run it to start installing. Official Download Page Using Python When you run the Python application, it will open the shell. This window will display the outputs of any program you have created. ​ Do not type into the shell . ​ Click on the File tab then New File to open the editor. Python Shell - This displays the outputs of your program. Do not write directly into the shell . Python Editor - All code is written into the editor. When you want to test a program press the F5 key (or click the Run tab then Run Module ). The first time you test a program, it will prompt you to save the file. Make sure you save it somewhere you will remember - it is a good idea to create a folder named 'Python' where you can keep all your practice programs. The next page looks at actually creating a program but above shows how code has been typed into the editor and then displayed in the shell. ​ You never need to save the shell window. Also, the editor saves automatically every time you run the program. Opening a Saved Program When you want to re-open and edit a file you have created previously double-clicking on it won't work . ​ Right-click on the file and select Edit with IDLE : https://trinket.io/python/76b41b35c5 1 a - Printing ➡

  • Python | Section 6 Practice Tasks | CSNewbs

    top Python - Section 6 Practice Tasks Task One: Odd Numbers Use a for loop to print all odd numbers between 50 and 70 . ​ You will need to use three values in the range brackets, including a step . ​ Requirements for full marks: A comment at the start to explain what a for loop is. Use just two lines of code. Example solution: 51 53 55 57 59 61 63 65 67 69 Task Two: Fish Rhyme Use two separate for loops and some additional print lines to output this nursery rhyme: "1, 2, 3, 4, 5, Once I caught a fish alive, 6, 7, 8, 9, 10 then I let it go again" in the format shown . ​ Requirements for full marks: ​ Two for loops and two additional print lines (6 lines total). Example solution: 1 2 3 4 5 Once I caught a fish alive. 6 7 8 9 10 Then I let it go again. Task Three: Username & Password Create a program using a while loop that keeps asking a user to enter a username and a password until they are both correct . It may be easier to use a while True loop . ​ You will need to use the and command in an if statement within the loop. ​ ​ Requirements for full marks: A comment at the start to explain what a while loop is. Example solution: Enter username: Ben43 Enter password: hamster Incorrect, please try again. Enter username: Ben44 Enter password: ben123 Incorrect, please try again. Enter username: Ben43 Enter password: ben123 Correct Correct login. Welcome Ben43 Task Four: Colour or Number Use a while True loop to let the user enter either A , B or C . ​ A lets them guess a secret colour . ​ ​ ​ B lets them guess a secret number . ​ C breaks the loop , ending the program. Example solution: Enter A to guess a colour, B to guess a number, C to quit: A Guess the colour: green Incorrect! Enter A to guess a colour, B to guess a number, C to quit: A Guess the colour: pink Correct! Enter A to guess a colour, B to guess a number, C to quit: B Guess the number: 4 Incorrect! Enter A to guess a colour, B to guess a number, C to quit: C Quitting program... ⬅ 6b - W hile Loops 7a - Procedures ➡

  • Python | Section 5 Practice Tasks | CSNewbs

    top Python - Section 5 Practice Tasks Task One: Random Numbers Ask the user to input 4 different numbers . ​ Put the four variables in a list with square brackets and use the choice command from section 5a to randomly select one. Example solutions: Enter number 1: 10 Enter number 2: 20 Enter number 3: 30 Enter number 4: 40 The computer has selected 30 Enter number 1: 2023 Enter number 2: 2024 Enter number 3: 2025 Enter number 4: 2026 The computer has selected 2026 Task Two: Logging In You will make a program for logging into a system. Print a greeting then ask the user for their name . Wait 2 seconds then print a simple login message with the user’s name . Then print the current time (current hour and minute ). Example solutions: Welcome to Missleton Bank Please enter your name: Steve Steveson Logging you in Steve Steveson The time is 08:02 Welcome to Missleton Bank Please enter your name: Gracie Jones Logging you in Gracie Jones The time is 15:53 Task Three: Random Wait Generate a random number between 3 and 10 to represent seconds . Print this number then print the current hour, minute and second . ​ Wait for the random number of seconds then print the current time again. Example solutions: The random wait will be 6 seconds. The time is 08:17:57 The time is 08:18:03 The random wait will be 3 seconds. The time is 08:21:39 The time is 08:21:42 Task Four: Independence Checker Create a program that displays how many days three specific countries have been independent for. The user will choose either Fiji , Samoa or Australia and the difference between today's date and the day they become independent will be displayed. ​ Fiji became independent on 10th October 1970 . Samoa became independent on 13th December 1962 . Australia became independent on 1st January 1901 . ​ Use the 'Today's Date ' and 'Between Dates ' parts of Section 5c to help you get today's date , make the other three dates and find the difference . Making Samoa's independence date would be samoadate = date(1962,12,13) for example. Example solutions: Enter FIJI, SAMOA or AUSTRALIA to check how long it has been independent for: AUSTRALIA Australia has been independent for 44822 days. Enter FIJI, SAMOA or AUSTRALIA to check how long it has been independent for: FIJI Fiji has been independent for 19338 days. Task Five: Square Root Create a program that asks the user to enter a whole number . Calculate the square root of the number. Round the answer down to the nearest whole number using the floor command. Example solutions: Enter a number: 156 The rounded down square root is 12 Enter a number: 156 The rounded down square root is 12 ⬅ 5e - More Librarie s 6a - For Loops ➡

  • Python | 6a - For Loops | CSNewbs

    top Python 6a - For Loops Types of Loop The third construct of programming (after Sequence and Selection) is Iteration . If you iterate something, then you repeat it. ​ There are two key loops to use in Python: for loops and while loops . ​ A for loop is count controlled – e.g. “For 10 seconds I will jump up and down”. The loop will continue until the count (e.g. 10 seconds) has finished . ​ A while loop is condition controlled – e.g. “While I am not out of breath, I will jump up and down.” The loop will continue as long as the condition remains true . Simple For Loops (1 Range Value) for i in range (5): print ( "This is a loop!" ) This is a loop! This is a loop! This is a loop! This is a loop! This is a loop! for i in range (8): print ( "Jaffa Cakes aren't biscuits" ) Jaffa Cakes aren't biscuits Jaffa Cakes aren't biscuits Jaffa Cakes aren't biscuits Jaffa Cakes aren't biscuits Jaffa Cakes aren't biscuits Jaffa Cakes aren't biscuits Jaffa Cakes aren't biscuits Jaffa Cakes aren't biscuits The i is a count variable , it is used to measure each iteration (turn) of the loop. ​ In the range brackets write the number of times to loop the indented code. ​ Don’t forget the colon at the end and remember that everything you want to repeat must be indented (press tab key once). For Loops Task 1 (Repeat Your Name ) Example solutions (shortened): Create a simple for loop that prints your name twenty times. For Loops Task 2 (Are We There Yet? ) Christopher Christopher Christopher ... Create a simple for loop that prints the sentence 'Are we there yet?' 150 times. Are we there yet? Are we there yet? Are we there yet? ... Counting Using i (2 Range Values) For loops can be used to count by referring to the iteration inside the loop itself using i : for i in range (5): print ( "Loop number" , i) Loop number 0 Loop number 1 Loop number 2 Loop number 3 Loop number 4 for i in range (1,6): print ( "Loop number" , i) Loop number 1 Loop number 2 Loop number 3 Loop number 4 Loop number 5 There are two important things to know about how Python counts using for loops. ​ Python will automatically start counting at 0 rather than 1. The second value in the range is an exclusive limit - it will stop 1 before this value. ​ For example, if you wanted to count 1 to 10 you would need to write range(1,11) . For Loops Task 3 (100 to 150 ) Create a for loop that prints all numbers from 100 to 150 . You don't need to print any additional text, just the i variable. Example solution (shortened): 100 101 102 ... ... 148 149 150 Using a Step (3 Range Values) A third value can be added to the range brackets of a for loop to define a step . A step is the number to go up (or down ) with each iteration . for i in range (2,11,2): print ( i) 2 4 6 8 10 for i in range (18,0,-3): print ( i) 18 15 12 9 6 3 In most programs defining a step is not essential , Python will assume it is +1 if you don't include it. For Loops Task 4 (Even Numbers 10 to 30 ) Example solution for Task 4 (shortened): Create a for loop that prints all even numbers from 10 to 30 . Use a step . For Loops Task 5 (Countdown ) Use a for loop with a negative step to print a countdown from 10 to 1 . 10 12 14 ... ... 26 28 30 Using Variables with For Loops Variables can be used to make for loops suitable for a range of different purposes. ​ loopnum = int ( input ( "Times to repeat: " )) for i in range (loopnum): print ( "Hello!" ) Times to repeat: 4 Hello! Hello! Hello! Hello! The loop above uses a variable in the range brackets to repeat the loop the specific number of times that the user enters . ​ loopnum = int ( input ( "Times to repeat: " )) word = input ( "Word to repeat: " ) ​ for i in range (loopnum): print (word ) Times to repeat: 3 Word to repeat: velociraptor velociraptor velociraptor velociraptor The loop above uses two variables that are input by the user ; one to define the range and another that is printed . For Loops Task 6 (Many Happy Birthdays ) Example solution for Task 6 (shortened): Ask the user to input their age then print 'Happy Birthday! ' that many times. For Loops Task 7 (House Number and Name ) Ask the user to enter their house number (e.g. 15 if they lived at 15 Cherry Road) and their name . Print their name as many times as their house number . For example, if Hannah lived at 103 Apple Lane then Hannah would be printed 103 times . Enter your age: 5 Happy Birthday! Happy Birthday! Happy Birthday! Happy Birthday! Happy Birthday! ⬅ Section 5 Practice Task s 6 b - While Loops ➡

  • Python | CSNewbs

    Pyt hon Follow the instructions in each section and try the practice tasks on every page . At the end of each section are larger problems to solve. ​ Pyt hon Sections 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 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 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 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 | 6b - While Loops | CSNewbs

    top Python 6B - While Loops Types of Loop The third construct of programming (after Sequence and Selection) is Iteration . If you iterate something, then you repeat it. ​ There are two key loops to use in Python: for loops and while loops . ​ A for loop is count controlled – e.g. “For 10 seconds I will jump up and down”. The loop will continue until the count (e.g. 10 seconds) has finished . ​ A while loop is condition controlled – e.g. “While I am not out of breath, I will jump up and down.” The loop will continue as long as the condition remains true . Simple While Loops A while loop keeps repeating as long as the starting condition is true . If the condition of the while loop becomes false , the loop ends . ​ ​ In this example, the number variable is increased by 1 inside of the loop until it is no longer less than or equal to 10 . number = 1 while number <= 10: print (number) number = number + 1 1 2 3 4 5 6 7 8 9 10 Comparison Operators == equal to != not equal to < less than <= less than or equal to > greater than >= greater than or equal to It is important to give the variable a value before you start the while loop . I have assigned number as 1. ​ The last line increases the number by 1 otherwise the number would stay at 1 and the loop would repeat forever . While Loops Task 1 (Countdown from 100 ) Example solution (shortened): Create a simple while loop that starts at 100 and prints each number down to 1 . Think about the comparison operator you will need to check you have reached 1. 100 99 98 ... ... 3 2 1 Inputs Inside While Loops If you want the user to keep entering an input until they give a certain answer then you need to put the input inside the while loop : age = 0 while age < 18: print ( "Only adults allowed to the casino." ) age = int ( input ( "Enter your age: " )) print ( "Welcome and enjoy your visit." ) Only adults allowed to the casino. Enter your age: 14 Only adults allowed to the casino. Enter your age: 18 Welcome and enjoy your visit. month = " " while month != "July" : month = input ( "Guess the month I'm thinking of: " ) print ( "Correct! It was July!" ) Guess the month I'm thinking of: August Guess the month I'm thinking of: June Guess the month I'm thinking of: July Correct! It was July! Notice that the variable in the condition (age or month in these examples) has to be given a value first before it can be used in a while condition. The program will crash if the variable is not declared and assigned a value - for example, the age cannot be checked to see if it less than 18 if there is no age variable! ​ ​ For string variables like month in the example above then a blank default value like " " can be used. For integer variables often 0 will be used. While Loops Task 2 (Guess the Colour ) Example solution: Use a variable named colour and a while loop that allows the user to keep entering colours until a specific one (your choice) has been input. Guess the colour: blue Guess the colour: purple Guess the colour: yellow Correct! It was yellow! While Loops Task 3 (Integer Trivia ) Use a while loop to ask a question that has an integer (whole number) as an answer , such as "How many James Bond films did Daniel Craig appear in?" or "In which year did Wigan Athletic win the FA Cup?". ​ Remember that integers do not use speech marks , e.g. year = 0 Example solution: Which year was the first Iron Man movie? 2010 Which year was the first Iron Man movie? 2009 Which year was the first Iron Man movie? 2008 Correct! It was 2008! While True Loops A while True loop will repeat indefinitely , only stopping when the break command is used to end the loop . ​ While True loops are often preferred because you do not need to set default values for any variables before the loop begins. while True : password = input ( "Enter the password: " ) if password == "icecream21" : print ( "Correct Password!" ) break Enter the password: vanilla32 Enter the password: chocolate83 Enter the password: strawberry100 Enter the password: icecream21 Correct Password! The program below has been adapted to record the number of attempts made . The value is increased by 1 each time the loop restarts. guesses = 0 while True : guesses = guesses + 1 password = input ( "Enter the password: " ) if password == "goat7" : print ( "Correct Password! It took" ,guesses, "attempts!" ) break else : print ( "Incorrect. Try again!" ) Enter the password: sheep3 Incorrect. Try again! Enter the password: cow4 Incorrect. Try again! Enter the password: horse5 Incorrect. Try again! Enter the password: goat7 Correct Password! It took 4 attempts! The continue command will move to the next iteration (it can be considered as starting the loop again ). ​ The program below allows numbers to be entered and keeps track of a running total. Entering 1 inputs a number, 2 displays the total and 3 stops the program. total = 0 while True : choice = input ( "\nType 1 to enter, 2 for a total and 3 to stop: " ) if choice == "1" : number = int ( input ( "Enter a number: " )) total = total + number continue elif choice == "2" : print ( "The total is" , total) continue elif choice == "3" : break print ( "\nProgram finished." ) Type 1 to enter, 2 for the total and 3 to stop: 1 Enter a number: 40 Type 1 to enter, 2 for the total and 3 to stop: 1 Enter a number: 35 Type 1 to enter, 2 for the total and 3 to stop: 2 The total is 75 Type 1 to enter, 2 for the total and 3 to stop: 3 Program finished. While Loops Task 4 (Guess the Planet ) Example solution: Use a while True loop to keep asking a user to input a planet . Keep track of the number of guesses that have been made and output the total when they input the correct planet. Use the second example in the 'While True Loops ' section above to help you. Enter a planet: Mars Incorrect guess, try again! Enter a planet: Mercury Incorrect guess, try again! Enter a planet: Neptune Correct it was Neptune! While Loops Task 5 (Up to 100 ) Create a while True loop that asks the user to enter a number . Add the number to a total variable and print it. When the total reaches 100 or more , stop the program. ​ Don't forget to set the total variable to 0 at the start and to add the number entered by the user to the total. Example solution: Enter a number: 34 The current total is: 34 Enter a number: 29 The current total is: 63 Enter a number: 18 The current total is: 81 Enter a number: 22 The current total is: 103 Over 100! ⬅ 6a - F or Loops Section 6 Practice Tasks ➡

  • 1.5 - Performance - Eduqas GCSE (2020 spec) | CSNewbs

    1.5: Performance Exam Board: Eduqas / WJEC Specification: 2020 + The performance of a computer system is affected by three main factors: Cache Memory: Size & Levels What is cache memory? ​ Cache memory is temporary storage for frequently accessed data . ​ Cache memory is very quick to access because it is closer to the CPU than other types of memory like RAM . What are the 3 levels of cache memory? Level 1 cache is the smallest level but it is also the fastest . Level 2 cache is larger than level 1 but slightly slower. Level 3 cache is located outside of the CPU core which makes it slower than the first two levels but it is much larger . How does cache memory work? ​ When the CPU searches for data , it looks first in level 1 cache, then level 2 and then level 3 . If the data has been found , this is called a 'cache hit '. If the data is not found then the CPU searches in RAM instead which takes more time - this is called a 'cache miss '. How does cache memory improve performance? Cache memory is closer to the CPU than RAM , meaning that it can provide data and instructions to the CPU at a faster rate . ​ A computer with more cache memory (e.g. 8MB instead of 4MB) should have a higher performance because repeatedly used instructions can be stored and accessed faster . ​ Larger level 1 and level 2 cache sizes will improve a computer's performance as data can be accessed extremely quickly . What is the limitation of cache memory? Cache memory is costly, so most computers only have a small amount . ​ Multiple cache misses will result in data latency (delay) as information is accessed from RAM which is further away from the CPU. Clock Speed What is clock speed? Clock speed is the measure of how quickly a CPU can process instructions . ​ Clock speed is measured in Gigahertz (GHz) . A typical desktop computer might have a clock speed of 3.5 GHz . This means it can perform 3.5 billion cycles a second . How does clock speed improve performance? ​ The faster the clock speed, the faster the computer can perform the FDE cycle resulting in better performance because more instructions can be processed each second . How does overclocking and underclocking affect performance? Typical clock speed: 3.5 GHz Underclocking Overclocking 3.9 GHz 3.1 GHz Overclocking is when the computer's clock speed is increased higher than the recommended rate. ​ This will make the computer perform faster, but it can lead to overheating and could damage the machine . Underclocking is when the computer's clock speed is decreased lower than the recommended rate. ​ This will make the computer perform slower but will increase the lifespan of the machine . Number of Cores What is a core? ​ A core is a complete set of CPU components (control unit, ALU and registers). Each core is able to perform its own FDE cycle . ​ A multi-core CPU has more than one set of components within the same CPU. How does the number of cores improve performance? ​ In theory, a single-core processor can execute one instruction at a time , a dual-core processor can execute two instructions, and a quad-core can execute four instructions simultaneously . ​ Therefore, a computer with more cores will have a higher performance because it can process more instructions at once . What are the limitations of having more cores? ​ If one core is waiting for another core to finish processing, performance may not increase at all. ​ Some software is not written to make use of multiple cores , so it will not run any quicker on a multi-core computer. Q uesto's Q uestions 1.5 - Performance: ​ Cache Size & Levels 1a. What is cache memory ? [ 2 ] 1b. Describe the three levels of cache memory . [ 3 ] 1c. Describe what is meant by a ' cache hit ' and a ' cache miss '. [ 2 ] 1d. Describe two ways that more c ache memory will mean performance is higher . [ 4 ] 1e. Explain why most computers only have a small amount of cache memory. [ 1 ] Clock Speed 2a. What is clock speed ? What is it measured in? [ 2 ] 2b. Explain how a higher clock speed improves performance . [ 2 ] 2c. Explain the terms 'overclocking ' and 'underclocking ' and explain the effects of both on the performance of a computer. [ 4 ] ​ Number of Cores 3a. What is a core ? [ 2 ] 3b. Explain why a quad-core processor should have a higher performance than a dual-core processor . [ 3 ] 3c. Explain two reasons why having more cores doesn't necessarily mean the performance will be better . [ 2 ] 1.4 - Secondary Storage 1.6 - Additional Hardware Theory Topics

  • 3.2a - Wired & Wireless Networks - OCR GCSE (J277 Spec) | CSNewbs

    3.2a: Wired & Wireless Networks Exam Board: OCR Specification: J277 Wired Connections Wireless Connections Wireless connections, such as WiFi or Bluetooth , use no cables but require a wireless network interface card (WNIC ). Wireless connections generally have a slower speed and can be affected by the computer's distance from the wireless router as well as obstacles like walls or bad weather. Wired connections use physical cables , such as copper or fibre optic wires , and require a network interface card (NIC ) to connect to a network. These wired connections use a wired connection protocol - most commonly Ethernet . Restricted Movement Faster More Secure NIC Required Freedom of Movement Slower Less Secure WNIC Required Q uesto's Q uestions 3.2a - Wired & Wireless Networks: ​ 1. Briefly compare wired and wireless networks in terms of movement , transmission speed , security and required hardware . You could answer this in the form of a table. [ 8 ] 3.1b - Network Hardware & Internet Theory Topics 3.2b - Protocols & Layers

  • 2.1 - Information Styles | Unit 2 | OCR Cambridge Technicals | CSNewbs

    2.1 - Information Styles Exam Board: OCR Specification: 2016 - Unit 2 There are many different ways that information can be styled and presented , both on-screen and physically . ​ There are many more benefits and limitations to using each information style but some key ideas have been described below. T Text Text is a written (or typed ) format of information. ​ ✓ Text provides detailed summaries and explanations . ✓ The format of text can be changed to suit its purpose (e.g. include bullet points or different colours). ✓ Text can be written in different languages so that all literate people can understand. ​ X Large amounts of text can be difficult and time-consuming to read. It is generally less engaging than most other methods. X Text may include spelling errors or be factually incorrect . Graphics Graphics are a visual form of information. Examples include logos , photographs and diagrams . ​ ✓ Graphics are multilingual - they can be understood by anybody regardless of their spoken language. Companies like IKEA will use the same graphics globall y . ✓ Graphics can present an idea or message immediately and can use associations (e.g. the colour red is associated with temperature or anger). ✓ Graphics are a more engaging method of presenting information than text. ​ X Images may take longer to load over a data-restricted network, for example, images in an email may not be automatically downloaded. Video Videos are visual formats of information, often with audio . ​ ✓ More engaging and easier to follow than reading large amounts of text. ✓ Videos can be used to convey a message in a short space of time , e.g. television adverts. ✓ Audio can be added to videos such as music for engagement or narration to explain a process. ​ X Videos usually take up a relatively large amount of storage space , longer videos may take time to upload / download / transfer along a network. X Videos take a long time to create including filming, editing and narration. Animated Graphics Animated graphics are images with multiple frames , such as an animation of the heart showing individual steps that a user can pause and step through in their own time. ​ ✓ Can be used to show a process and is easier to understand than reading text. ✓ Can be understood by all ages and language speakers . ​ X Creating an animated graphic takes time to create , especially educational resources with multiple frames and annotation. 9 Numerical Numerical information is represented by numbers . This can include a wide array of different information including statistics, financial data, dates, ages and distances . ​ ✓ Statistical data is easier to understand and manage in a numerical format than standard text - 234,567 is simpler to work with than "two hundred and thirty-four thousand, five hundred and sixty-seven". ✓ Numerical data can be exported into spreadsheets and presented as graphs to visualise the dat a . ​ X Long numbers can be entered by humans incorrectly and lead to incorrect results . X Formatted data like telephone numbers cannot be stored as numerical because numerical does not allow spaces and does not allow the number to start with 0 . Audio Audio is an information type using sound waves. A common form of audio is music , such as the millions of tracks stored in music libraries like Spotify and YouTube. Non-music examples include spoken instructions and podcasts . ​ ✓ Users can listen to information when they are otherwise busy and could not read, such as when walking or driving. ✓ Visually impaired users who are unable to read can still hear audio and interact with voice recognition software . ✓ Some users prefer listening to instructions rather than reading text . ​ X Audio may not be suitable in some environments e.g. noisy areas . X Words may be misheard and misunderstandings made, possibly due to pronunciations or accents. Tactile Images Tactile images are a form of physical information that can be interpreted by touch . Specialist software is used to create raised lines on paper that people can experience by touching . Geographers can create 3D physical objects of environments such as valleys or volcanoes. This allows researchers and land surveyors to have a better understanding of a geographic area. ​ ✓ Users can better understand a physical environment or prospective design if it is physically built. ✓ Visually-impaired users can feel the object instead of being able to see it. ✓ The tactile image can be used as a prototype for a target audience to feel and comment on. ​ X It is difficult to share a tactile image without physically moving it, unlike digital or paper information styles. X Creating a tactile image requires specialist equipment like a 3D printer. *screams* Subtitles Subtitles are a textual form of information that can be shown along with visual data such as a video. Subtitles are written to transcribe audio , such as speech, into words . ​ ✓ Hearing-impaired users can access audio information formats such as video by reading the subtitles. ✓ Subtitles can be used in noisy environments or when sound cannot be played. ✓ Subtitles can be used for translated speech , such as in promotional videos or television programmes. ​ X Auto-generated subtitles are often incorrect . X Subtitles written by a human take a long time to type up and sync in time with the audio. Tables & Spreadsheets Tables and spreadsheets can store both numerical and textual data ready for analysis . Examples include simple database tables and financial spreadsheets of a company's profits this year. Microsoft Access is an example of database software that uses tables and Microsoft Excel is an example of spreadsheet software. ​ When using spreadsheets (or databases) records can be locked ('record locking' ) so that only one person can make edits at any one time . Edits will be saved before unlocking the file. This will stop data being incorrectly overwritten and will ensure that the data in the spreadsheet is up-to-date , accurate and fit for purpose . Spreadsheets can be linked to other documents such as forms to directly import data from. This data can be ordered into different groups and conditional formatting can be used to automatically organise and style the data. Graphs and charts can be created using values stored in a spreadsheet to easily visualise the data . Modelling can be used to see the effect of variable changes (e.g. will raising the price of one product affect overall profit?). ​ Database tables use queries (advanced searches) to find and display data based on given criteria (such as all males under 35). Mail merge can be used to automatically send emails to the customers highlighted in the query . ​ A report can be generated from the query results to display the information in a structured format . This can be used to make decisions and analyse data . Boolean Boolean is a data type that can only have one of two specified values . These values are most commonly 'True' and 'False' or sometimes 'yes' and 'no'. Braille Braille is an example of a tactile image that can be physically touched . Braille characters represent letters or numbers that can be 'read' by touch - used primarily by those with visual impairments . Devices like braille terminals convert characters on a screen into braille, line-by-line so that blind people can understand the information through touch . A braille printer is used to output braille dots onto paper. ​ ✓ Allows visually impaired users to interact with a computer system using a braille terminal . ✓ A braille printer can print documents written using braille to be given to blind people to 'read'. ​ X Braille terminals can only display a limited amount of information at a time. X Braille is not used by many people except visually impaired people so few resources are written using braille. Charts & Graphs Charts and graphs can be used to present numerical data in a format that is easier to visualise and understand . They can be labelled to show different data values and they make it easier for viewers to identify trends and make comparisons between data. Large quantities of data, like census results, are easier to visualise in a graph than reading huge tables of numbers. ​ ✓ Charts present numerical data in a format that is easier to visualise and understand . ✓ Charts and graphs can summarise information into one image data that would take paragraphs to explain in text. ✓ Displaying information in a graph allows users to easily identify trends and make comparisons between data . ​ X Charts can be misleading or can display incorrect information if the numerical data is wrong. Q uesto's Q uestions 2.1 - Information Styles: ​ 1. Describe the following information styles : a. Tactile Images [2 ] b. Braille [2 ] c. Boolean [2 ] ​ 2. Describe two advantages and two disadvantages for each of the following information styles : a. Text [8 ] b. Graphics [8 ] c. Video [8 ] d. Animated Graphics [8 ] e. Numerical [8 ] f. Audio [8 ] g. Tactile Images [8 ] h. Subtitles [8 ] i. Braille [8 ] j. Charts & Graphs [8 ] ​ 3a. Spreadsheets and database tables can be record locked . Explain what record locking is and why it is used . [4 ] 3b. Describe different ways that spreadsheets can be used. [6 ] 3c. Describe different ways that databases can be used. [6 ] 1.7 & 1.8 - Internet Pros & Cons 2.2 - Information Classification Topic List

  • OCR CTech IT | Unit 1 | 1.3 - Computer System Types | CSNewbs

    1.3 - Computer System Types Exam Board: OCR Specification: 2016 - Unit 1 Different types of computer system are available to purchase and use, each with their own benefits , drawbacks and typical functions . Desktop A computer suitable for use at an ordinary desk. They are bulky and not so easy to move . Individual components (e.g. graphics card) can be upgraded over time . Desktops are versatile , they allow the user to carry out a range of activities , including document creation, data manipulation, game playing, design and communication facilities for personal or business purposes. Tablet / Laptop A portable type of computer. Many modern laptops can also fold back, effectively turning them into a tablet with a screen-based virtual keyboard. They can perform many of the functions of the traditional PC, but the screen size can be restrictive , especially if several documents need to be open at the same time. Because it can be transported through public spaces, loss or theft is more likely. Smartphone Embedded Systems Smartphones can be used to run a range of applications including email, social media, videos and music. However, they can negatively affect social interaction (e.g. by using them and ignoring people around you) and reduce spatial awareness when being used. Security is another issue as they can be easily lost or stolen . Security software for phones is not as secure as other computer systems so sensitive data should not be held on smartphones. An embedded system is when a smaller computer system is installed within a larger device , such as a washing machine, traffic light or car. Embedded systems have a dedicated purpose and often run in real-time . The internet of things (IoT) describes a global network of connected objects that were previously 'dumb', such as smart bulbs, smart plugs and thermostats. Mainframe Mainframes are huge and very powerful computers that are reliable . Mainframes are used to process large amounts of data and can be used to solve scientific and engineering problems that require complex calculations with large datasets (e.g. weather forecasting or scientific simulations). ​ Mainframes are reliable and secure because they have large backup capabilities . Mainframes are very expensive and require teams of experts to oversee them, and so are used only by organisations that need to process very large amounts of data quickly, such as banks and airlines . Quantum These are still experimental and in development . They work with quantum bits (qubits) which, unlike binary, are not limited to just two states (0 or 1). Qubits represent atomic particles, which can be in several different states at the same time . ​ A fully working quantum computer would potentially be able to process data and perform calculations millions of times faster than currently available computers. Q uesto's Q uestions 1.3 - Computer System Types: ​ 1. For each type of computer system , make a list of benefits , drawbacks and possible uses . a. Desktop [6 ] b. Tablet / Laptop [6 ] c. Smartphone [6 ] d. Embedded System [6 ] e. Mainframe [6 ] f. Quantum Computer [6 ] ​ 2. Suggest and justify which type of computer system is most suitable for the following scenarios: a. Updating a spreadsheet while on a train. [3 ] b. Forecasting the next week’s weather. [3 ] c. A PE teacher recording sports day race times. [3 ] d. Playing a new video game on maximum settings. [3 ] 1.2 - Computer Components Topic List 1.4 - Connectivity

bottom of page