top of page

Search CSNewbs

304 results found with an empty search

  • Python | 3a - Data Types | CSNewbs

    Learn about the different data types used in Python. Try practice tasks and learn through text and images. Perfect for students learning GCSE Computer Science in UK schools. top Python 3a - Data Types Data Types in Python If you are a Computer Science student you need to know about the different data types that are used in programming. String – A sequence of alphanumeric characters (e.g. “Hello!” or “Toy Story 4” or “Boeing 747” ) Integer – A whole number (e.g. 1470 or 0 or -34) Float (also called Real ) – A decimal number (e.g. -32.12 or 3.14) Boolean – A logical operation (True or False) Character – A single alphanumeric character (e.g. “a” or “6” or “?”) [ Not used in Python as it would just be a string with a length of 1] Converting to Another Data Type Converting a variable from one data type to another is called casting . Casting Commands str (variable_name) converts a variable to a string . int (variable_name) converts a variable to a integer . float (variable_name) converts a variable to a float (decimal number). An integer (or float ) value may be cast into a string so that it can be used with + as part of a sentence to avoid spaces . total = 45 print ( "You owe £" , total , "in total." ) print ( "You owe £" + str (total) , "in total." ) = You owe £ 45 in total. You owe £45 in total. When dividing an integer the answer is automatically given as a decimal number (float ), even if it is .0 (e.g. 10 / 2 would give 5.0). Casting a float (also known as real) number into an integer using int() will remove the decimal . total = 100/10 print ( "The answer is" , total ) print ( "The answer is" , int(total) ) The answer is 10.0 The answer is 10 = Data Types Task 1 ( Time) Write an input line with int to ask the current hour . Write another input line with int to ask the current minute . Write a print line with str() that outputs this as a clock time. Example solution: What is the hour? 12 What is the minute? 44 The time is 12:44 Data Types Task 2 ( Decimal ) Write an input line with int to ask for any number . Use float() in a print line to output number as a decimal. Example solution: Enter any number: 456 456.0 ⬅ Section 2 Practice Tasks 3b - Simple Calculations ➡

  • 2.1 - Software Development Models | F160 | Cambridge Advanced National in Computing | AAQ

    Learn about the characteristics, diagrammatic representations, advantages, disadvantages, and suitability of software development models. These include the waterfall, rapid throwaway, incremental, evolutionary, rapid application development (RAD), spiral and agile models. Resources based on Unit F160 (Fundamentals of Application Development) for the OCR Cambridge Advanced National in Computing (H029 / H129) AAQ (Alternative Academic Qualification). Qualification: Cambridge Advanced National in Computing (AAQ) Unit: F160: Fundamentals of Application Development Certificate: Computing: Application Development (H029 / H129) 2.1 - Software Development Models Watch on YouTube : Software Development Models Waterfall Rapid Throwaway Incremental Evolutionary Rapid Application Development Spiral Agile There are seven software development models you need to know : Traditional models: Waterfall Prototype models: Rapid Throwaway , Incremental , Evolutionary Iterative models: Rapid Application Development (RAD) , Spiral , Agile For each development model , you need to know : Its characteristics . How to represent it in a diagram . Its advantages and disadvantages . The types of development it is suitable for. Software Development Models Each development model has its own video below but you also need to know the advantages and disadvantages of using development models in general. Waterfall Model The waterfall model is a linear and structured approach where each phase is completed one at a time in order . It needs all requirements to be clearly defined at the start , with little to no changes allowed once a phase is finished . This model is best suited for projects with fixed requirements and minimal risk of change . Rapid Throwaway Prototype Model The rapid throwaway prototype model involves quickly creating temporary prototypes to explore ideas and gather user feedback before building the final system . Prototypes are discarded after they help refine requirements , and are especially useful in projects where user needs are initially unclear . This model is suitable when user interaction and efficient interface design are critical . Incremental Model The incremental model develops a system in small , manageable sections with each part being designed , built and tested individually . Functionality is added step by step until the full system is complete . This approach allows for early partial deployment and easier handling of changing requirements over time. Evolutionary Prototype Model The evolutionary prototyping model involves building an initial prototype that is continuously improved based on user feedback until it becomes the final system . Unlike throwaway prototyping, the prototype is not discarded but gradually evolves into the full product , once the user is satisfied . This model is ideal when user requirements are expected to change or develop over time . Rapid Application Development (RAD) The rapid application development ( RAD ) model focuses on quickly building software through iterative development and frequent user feedback . It uses reusable components , time-boxing and constant feedback to speed up the delivery of an effective final product . RAD is best suited for projects that need to be completed quickly and where requirements can evolve during development . Spiral Model The spiral model combines iterative development and risk management , progressing through repeated cycles of planning , risk assessment , engineering ( development and testing ) and evaluation . Each loop focuses on identifying and addressing risks early in the project. It is ideal for complex and high-risk projects where requirements may change over time . Agile Model The agile model is an iterative and flexible approach that progresses in small , usable chunks called iterations (or sprints ). It relies on frequent collaboration with stakeholders and user feedback to adapt to changing requirements . This model is ideal for dynamic projects where quick delivery and frequent updates are important. Q uesto's Q uestions 2.1 - Software Development Models: 1. Choose three development models to explain and draw a diagram for each. [6 ] 2. A large company is making the next sequel in a hugely popular video game series , FieldBattle 2043 . Justify which application development model(s) they should use (and which they shouldn't ). [5 ] 3. Describe the advantages and disadvantages of any development models you have not covered in Q1 or Q2 . [6 ] Agile development is named after the ' Agile Manifesto ' - a set of principles for software development agreed by a group of developers at a ski resort in Utah , USA in 2001 . D id Y ou K now? 1.3.3 - App. Software Types Topic List 2.2 - Phases of Development Models

  • OCR CTech IT | Unit 1 | 5.6 - Data Disposal | CSNewbs

    Learn about laws regarding suitable data disposal of information and computer systems as well as methods including electromagnetic wipe and physical destruction. Based on the 2016 OCR Cambridge Technicals Level 3 IT specification. 5.6 - Data & System Disposal Exam Board: OCR Specification: 2016 - Unit 1 Computer components such as circuit boards, processors and monitors contain hazardous materials that cannot be disposed of in traditional ways such as rubbish collection and landfills. For security reasons, data must also be disposed of carefully so that it is not returned to a readable format by unauthorised viewers . Legislation In recent years, the government has introduced different laws that relate to the safe disposal of computer equipment to help reduce environmental impact . Waste Electronic and Electrical Equipment ( WEEE ) Directive : This provides guidance on how hazardous materials should be disposed of safely . This includes materials such as mercury (found in smartphones and newer monitors ) and toner cartridges in printers . These materials can damage the environment if not disposed of appropriately . Waste Acceptance Criteria ( WAC ): Equipment must meet these rules before it can be sent to a landfill . Hazardous materials, such as the elements in computer monitors , do not meet these criteria and should not be accepted . Hazardous Waste Directive : This ensures businesses safely store hazardous materials and use authorised businesses to dispose of the waste . Hazardous materials include mercury and hexavalent chromium . Data Protection Act ( DPA ): One principle of the DPA specifies that data should only be kept for a reasonable amount of time until it is securely deleted . Data stored on customers should be checked regularly and permanently deleted if no longer required . Methods of Data & System Disposal Overwriting is when new data is written to the hard disk drive to replace the current data - essentially resetting the data . Remember all data stored by a computer is in a binary format . Overwriting just once is usually not enough to remove all evidence of the data and the process may be repeated several times . Overwriting data causes no damage and means the drive can still be used for other purposes afterwards. Electromagnetic wiping uses a machine called a degausser , which has a very strong electromagnetic coil , to completely wipe the hard disk drive . Many large organisations use degaussers to be sure that their data is no longer on the devices they have used so it can’t be restored and accessed by unauthorised viewers . Degaussers are expensive to buy but it allows the device to be used again for other purposes afterwards as it is not physically damaged. A third option is the physical destruction of a computer system or storage device , like a hard disk drive , which guarantees the data is permanently inaccessible . However, physical destruction also renders the storage media unusable again for other purposes. Examples of physical destruction include shredding (e.g. a CD shredder ) or tools such as sledgehammers if no other option is available. Q uesto's Q uestions 5.6 - Data & System Disposal: 1. Describe the purpose of 4 different pieces of legislation relating to how data or computer systems should be disposed of safely . [8 ] 2a. State 3 methods of data and system disposal . [3 ] 2b. Describe 1 advantage and 1 disadvantage of using each method you stated in 2a. [6 ] 5.5 - Digital Security Topic List

  • Little Man Computer Editor | CSNewbs

    A simple Little Man Computer (LMC) editor. Perfect for students learning A-Level Computer Science in UK schools. Little Man Computer (LMC) Editor You can use this simple Little Man Computer ( LMC ) editor below to check any LMC code you have written to ensure it outputs correctly . Use the reminders on the right for the 11 commands needed in the OCR A-Level specification . LMC is a simplified form of assembly language . This page is under active development. INP is used without a label to input a number . The number is temporarily stored in the accumulator. Example: INP OUT will output the current value of the accumulator. Example: OUT STA stores the value that is currently in the accumulator into a named memory location. Example: STA num1 ADD is used to add the value of a named memory location to the value currently stored in the accumulator. Example: ADD num1 SUB takes away the value of a named memory location from the value currently stored in the accumulator. Example: SUB num1 LDA is used to load the value of a stored variable into the accumulator. Example: LDA num1 BRZ is used to branch to a labelled line of code if the value in the accumulator is exactly 0 . Example: BRZ ifzero BRP is used to branch if the value in the accumulator is currently positive (including 0). Example: BRP repeat BRA is used to branch regardless of the accumulator's current value . Example: BRA loop HLT will stop the program. Example: HLT DAT defines and stores data in memory. It creates a variable or memory location that can hold a specific value. It is written after the final HLT command. Example: fifty DAT 50

  • Scams & Staying Safe | Key Stage 3 | CSNewbs

    Learn how to spot a phishing email and other ways to stay secure online including choosing strong passwords. Scams & Staying Safe Part 1: Phishing Scams A phishing scam is when an attacker will send you an email pretending to be someone you trust . They are trying to get your username, password or other sensitive information . What does a phishing email look like? Capital letters and exclamation marks may be used to create a sense of urgency. A phishing email might be sent from a long, unrecognisable email address . It may be similar but slightly different to a real email address. An attacker might not know your name , so they will use your email address. A phishing email might contain spelling and grammar mistakes , so look carefully. Check any links carefully , if it looks suspicious, don't click it. Phishing emails try to rush you into making a silly decision. Don't panic and read the email carefully. Part 2: Secure webpages When you are browsing the web , you should stick to websites that you know and trust. Don't click on any links that you don't recognise , especially from strangers . How do i know a web page is secure? HTTP is a protocol (set of rules) for displaying a web page . If the web address at the top of your web browser starts with HTTP then it is not secure . Do not enter any personal information on an insecure web page. HTTPS is a protocol (set of rules) for displaying a secure web page. If you see a padlock in the address bar of your web browser then you know it is safer to enter information . Part 3: Strong passwords Your passwords must be secure so they cannot be broken easily. How to choose a strong password: ********* Passwords should be more than at least 8 characters long. Passwords should use numbers and punctuation marks . Aa Bb Cc Dd Ee Passwords should use uppercase and lowercase letters . You should use a different password for each account that you have. Passwords should not use words found in the dictionary . KS3 Home

  • 4.1 - Boolean Logic - OCR GCSE (J277 Spec) | CSNewbs

    Learn about the three logical operators - NOT, AND and OR - as well as truth tables. Based on the J277 OCR GCSE Computer Science specification (first taught from 2020 onwards). 4.1: Boolean Logic Exam Board: OCR Specification: J277 Watch on YouTube : Boolean Operators & Truth Tables Logic Gate Diagrams What is a logical operator? Inside of each computer system are millions of transistors . These are tiny switches that can either be turned on (represented in binary by the number 1 ) or turned off (represented by 0 ). Logical operators are symbols used to represent circuits of transistors within a computer. The three most common operators are: NOT AND OR What is a truth table? Truth tables are used to show all possible inputs and the associated output for each input . The input and output values in a truth table must be a Boolean value - usually 0 or 1 but occasionally True or False. NOT AND OR A NOT logical operator will produce an output which is the opposite of the input . NOT is also known as Negation . The symbol for NOT is ¬ An AND logical operator will output 1 only if both inputs are also 1 . AND is also known as Conjunction . The symbol for AND is ∧ An OR logical operator will output 1 if either input is 1 . OR is also known as Disjunction . The symbol for OR is ∨ NOT Logic Gate AND Logic Gate Symbol OR Logic Gate Symbol Truth Table Truth Table Truth Table Multiple Operators Exam questions could ask you complete truth tables that use more than one logical operator . Work out each column in turn from left to right and look carefully at which preceding column you need to use. NOT B A AND NOT B A OR (A AND NOT B) As binary is a base-2 number system , the number of rows required in a truth table will double with each new input in the expression in order to show the unique combinations of inputs. The examples above use just two inputs (A + B) so 4 rows are required. e.g. A = 2 rows / A + B = 4 rows / A, B + C = 8 rows / A, B, C + D = 16 rows Logic Diagrams You may be asked in an exam to d raw a logic diagram when given a logical expression . Draw any NOT symbols or expressions in brackets first. A logic diagram for C = ¬A ∧ B A logic diagram for D = C ∨ (A ∧ B) Q uesto's Q uestions 4.1 - Boolean Logic: 1. Copy and complete the following truth tables: 1b. Simplify the expression in the second truth table. 2a. A cinema uses a computer system to monitor how many seats have been allocated for upcoming movies. If both the premium seats and the standard seats are sold out then the system will display a message. State the type of logical operator in this example. 2b. For the more popular movies, the cinema's computer system will also display a message if either the premium seats or the standard seats have exclusively been sold out. However, it will not output a message when both have been sold out. State the type of logical operator in this example. 3. Draw a logic diagram for C = (¬B v A) ∧ A . 3.2 - Testing Theory Topics 5.1 - Languages & Translators

  • Python | Section 1 Practice Tasks | CSNewbs

    Test your understanding of printing, comments and variables. Try practice tasks and learn through text and images. Perfect for students learning GCSE Computer Science in UK schools. top Python - Section 1 Practice Tasks Task One: Weekdays Create a program that prints all 5 weekdays , with each day on a new line . Requirements for a complete program: Use only one print line - use \n . No empty space at the start of a printed line. Example solution: Monday Tuesday Wednesday Thursday Friday Task Two: Colour & Animal Sentence Write a program that uses two variables , one for a colour and one for an animal . Print a sentence using both variables . Requirements for a complete program: Use both your variables within one print line. Include capital letters, appropriate punctuation 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: Have you ever seen a purple cat? A horse that was green galloped past! Three yellow ants ate my lunch. Task Three: Number, Adjective & Animal Write a program that uses three variables , a number , an adjective (descriptive word) and an animal . Print a sentence using all three variables . Requirements for a complete program: Use all three variables within one 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? 64 sneaky elephants just ran past me! There were 12 hungry bears in the park. 85 patient spiders waited in the corner. ⬅ 1d - Using Va riables 2a - Inputting Text ➡

  • OCR Cambridge Technicals | CSNewbs

    A splash page for the previous Cambridge Technicals units - Unit 1 (Fundamentals of IT) and Unit 2 (Global Information). OCR Cambridge Technicals IT Level 3 These pages are based on content from the OCR Cambridge Technicals 2016 Level 3 IT specification . This qualification stopped in July 2025. The pages on the site will remain for at least two years. Unit 1 Fundamentals of IT Unit 2 Global Information

  • 10.1 - Translators - Eduqas GCSE (2020 Spec) | CSNewbs

    Learn about the three types of translators - assemblers, interpreters and compilers. Also, understand the differences between compilers and interpreters. Based on the 2020 Eduqas (WJEC) GCSE specification. 10.1: Translators Exam Board: Eduqas / WJEC Specification: 2020 + What is a translator? A translator changes (translates) a program written in one language into another language (usually machine code ). There are three types of translator : Assembler An assembler converts low level assembly language into machine code . INP STA 33 INP STA 34 LDA 33 ADD OUT HLT Interpreter An interpreter converts high-level language one line at a time into machine code and executes it. PYT HON Compiler A compiler converts high-level language into machine code for execution at a later time. The entire program is converted at once . PYT HON 0010 1011 0101 0101 0110 0111 0101 0001 0101 0101 0010 1011 0101 0101 0110 0111 0101 0001 0101 0101 0010 1011 0101 0101 0110 0111 0101 0001 0101 0101 Differences between an interpreter and a Compiler: Interpreter Compiler Execution Method: An interpreter translates source code (high level code) into machine code one line at a time . Execution Speed: An interpreter is slower than a compiler because the code must be reinterpreted each time the program is run. Complexity: Interpreters are smaller, simpler programs . Error Reporting: In error reporting, the interpreter would encounter the errors and report it to the user immediately and stops the program from running. Repetition: Interpreted programs can be edited and run without translating the whole program . Interpreters must reinterpret the program every time it is run. Execution Method: A compiler translates all the source code (high level code) into machine code in one go . A compiler produces an executable file that will run on other machines without the compiler needing to be installed. Execution Speed: Compilers can produce much more efficient code than interpreters making the compiled programs run faster . Complexity: Compilers tend to be large complex programs . Error Reporting: The compiler would analyse the entire program , taking note of where errors have occurred and record them in an error file . Repetition: Compilation requires analysis and the generation of the code only once , whereas interpreters must re-interpret each time. However, compiled programs have to be re-compiled after any changes have been made. x1 ∞ x1 Q uesto's Q uestions 10.1 - Translators: 1. Briefly describe each type of translator : a. Assembler [ 1 ] b. Interpreter [ 2 ] c. Compiler [ 2 ] 2. Compare interpreters and compilers for each of the following features : a. Execution Method b. Execution Speed c. Complexity d. Error Reporting e. Repetition [ 10 total ] 9.1 - IDE Tools Theory Topics 10.2 - Stages of Compilation

  • 1.1 - Holders of Information | Unit 2 | OCR Cambridge Technicals | CSNewbs

    Learn about the different types of organisations that hold information. Also, consider the differences between urban and rural connections and remote locations. Based on the 2016 OCR Cambridge Technicals Level 3 IT specification for Unit 2. 1.1 - Holders of Information Exam Board: OCR Specification: 2016 - Unit 2 Categories of Information Holders Organisations that store and process information can be put into seven different categories : Business A business will hold information on all of its employees , including their date of birth, address and financial information , allowing them to be paid at the end of each month. Businesses will also hold commercial information about their organisation such as profits and losses, product descriptions and historical data . Many companies may record information about their competitors and general marketing data. Government The government will hold a huge amount of information about all citizens in the country including financial earnings, tax paid, births and deaths . The electoral roll holds information about addresses . A national census is taken every 10 years in the UK (the next census is in 2021) that records extensive data about everyone living in the country. The government also stores information about other countries and shares some of this publicly, such as the Foreign Office posting travel advice . Individual Education Educational organisations , such as schools, colleges and universities will hold information about current and past students as well as staff. Student information such as addresses, attendance records and examination history will be recorded, as well as contact information for parents and guardians. Teacher information will be stored too, as well as students that previously attended the institution, even for a number of years after they have left. An individual will hold information about themselves , either in their head or on paper or electronically. This includes their name, date of birth, address, usernames and passwords . Individuals will store information of others , such as phone numbers, social media details and email addresses . Other information will be about organisations , such as the address of their favourite restaurant, opening hours of the local cinema or the telephone number from a catchy advert. Healthcare Healthcare services , like the NHS in the United Kingdom, will hold entire medical histories for each civilian in the country. This includes basic personal information such as current address and date of birth but much more detailed data too like previous illnesses and operations, blood type, allergies and prescriptions . The data stored by healthcare organisations is usually confidential and should not be shared by anyone other than the citizen in question. Charity & Community Charities may hold financial information of donors who give money to them, as well as information about the different projects that the donations are funding. Charities such as the British Heart Foundation might have physical addresses on the high street so information may be kept about the shops too. Community organisations like sport centres or religious institutions may hold information on members and matches, meetings or events . Comparison of Locations The location of systems and data affects access speed and network quality . The digital divide is the gap between people who do and do not have easy access to computers and networks . Developed vs. Developing Countries Developed countries , like areas of Western Europe, North America and East Asia, have a more developed technology and industry base with more funding available for information infrastructures such as cabling and high-speed access . Developing countries , like areas of Africa and Central Asia, have unstable governments and slower access (if any) to the internet . Less money is spent on technology and improving broadband speed and expensive equipment like computers cannot be purchased on low wages . Urban vs. Rural Urban locations like towns and cities have a high population density . Because there are so many people, councils and IT companies will spend a lot of money on internet infrastructure such as cabling and installing high-speed lines . In Rural locations like the countryside, the population is sparse and settlements may be far apart so internet access is poorer and broadband speeds are slower . This means accessing information on the internet is more difficult . Internet Access from Remote Locations Remote locations (such as the countryside or difficult-to-reach areas like mountains or deserts) might have limited internet access . Fast fixed broadband is expensive to install and many providers simply won't invest in rural areas as it is not economically viable . Some areas, usually those with a very small or temporary population, might have no fixed internet access which will make it difficult for an individual or organisation to communicate or work online. Many remote locations have some form of internet but download speeds will be slow or interrupted due to intermittent connection . This makes it difficult to work online and could take a long time to access webpages or document stores. Alternatives to fixed broadband in remote locations include mobile broadband and satellite broadband . Mobile broadband is generally not designed for home use and would be very expensive for everyday use , plus the remote location will generally mean mobile coverage could also be weak . Satellite broadband requires a dish with an unrestricted view of the sky. Satellite broadband has a relatively high internet speed but will cost a lot to install and has a high latency (more chance of experiencing lag). Q uesto's Q uestions 1.1 - Holders of Information: 1a. State the 7 categories of information holders . [7 ] 1b. For each of the 7 categories , briefly describe 3 different pieces of information that may be stored by the information holder. For example, a charity may store the financial information of donors. [3 each ] 2. What is the digital divide ? [2 ] 3. Describe the differences in information access for the following locations : a. Developed vs. developing countries b. Urban vs. rural areas c. Remote locations [4 each ] Topic List 1.2 - Storage Media

  • Python | 4c - Logical Operators | CSNewbs

    Learn how to use logical operators in Python. Try practice tasks and learn through text and images. Perfect for students learning GCSE Computer Science in UK schools. top Python 4c - Logical Operators AND Operator The AND operator is used to execute certain code if more than one thing is true . AND is commonly used with account logins - both the username AND the password must be correct . The example below requires both a secret word and a secret number to be correct: print ( "To enter you need the secret word and the secret number!" ) word = input ( "What is the secret word? " ) number = int ( input ( "What is the secret number? " )) if word == "solitude" and number == 2011: print ( "Correct! You may enter!" ) else : print ( "Incorrect! Get out of here!" ) If no part or only some of the if statement is true then the indented code will not run : To enter you need the secret word and the secret number! What is the secret word? solitude What is the secret number? 4503 Incorrect! Get out of here! To enter you need the secret word and the secret number! What is the secret word? windhelm What is the secret number? 1021 Incorrect! Get out of here! Only If all parts of the if statement are true will the indented code be executed : To enter you need the secret word and the secret number! What is the secret word? solitude What is the secret number? 2011 Correct! You may enter! Logical Operators Task 1 ( Three Easy Questions) Ask the user three easy questions and print a special response if they get all three correct . Use the and operator to see if their answer for all each of the questions is correct. You must use a unique variable nam e for each of your inputs (it can't be 'answer' for all three, for example). Example solutions: What is the capital of Germany? Berlin What is the chemical formula for water? H20 What year did World War Two end? 1945 You absolute genius! What is the capital of Germany? Vienna What is the chemical formula for water? W20 What year did World War Two end? 1945 Bit awkward, I thought you'd do better... OR Operator The OR operator is used to execute certain code if one of several statements is true . The program below is checking if either a , e , i , o or u were entered. letter = input ( "Enter a letter: " ) if letter == "a" or letter == "e" or letter == "i" or letter == "o" or letter == "u" : print ( "You entered a vowel." ) else : print ( "You entered a consonant." ) Enter a letter: f You entered a consonant. Enter a letter: e You entered a vowel. It is important that you re-write the variable and operator (e.g. letter ==) each time you use 'or' . It will not work if you just write: if letter == “a” or “e” or “i” or “o” or “u”: Logical Operators Task 2 ( Twins?) Ask the user to enter their favourite colour and then ask them their age . If their favourite colour is the same as yours AND their age is the same as yours then print “Snap! Are you my twin?” . If only one of the statements is true (use the OR operator) then print “Spooky! You’re a bit like me.” . Add an else statement to print “We’re not so similar, you and I.” if there's nothing in common. Example solutions: What's your favourite colour? green What's your age? 15 Snap! Are you my twin? What's your favourite colour? blue What's your age? 15 Spooky! You're a bit like me. What's your favourite colour? red What's your age? 16 We're not so similar, you and I. ⬅ 4b - Mathematical Opera tors Sectio n 4 Practice Tasks ➡

  • Python | 10b - Read & Search Files | CSNewbs

    Learn how to read and search through files in Python. Try practice tasks and learn through text and images. Perfect for students learning GCSE Computer Science in UK schools. Python 10b - Read & Search Files Reading from a File To read and print from a file you must open it in read mode by typing "r" instead of "a". If you are writing and reading in the same program, make sure you close the file in append mode before you open it in read mode . The program below uses the Customers.txt file from the last section. A simple for loop can be used to print each line of the file. The end = "" code just prevents a space between each line. Practice Task 1 Open one of the files that you used in Section 10a and print each line. Example solution: Reading Specific Lines from a File Sometimes it is necessary only to print certain lines. The following example uses a file where I have written a sentence of advice on each line. The user is asked to enter a number between 1 and 6. If they enter 1, the first line of the file is printed. If they enter 2, the second line of the file is printed etc. Remember Python starts counting everything at 0 so each line is a digit less than you would expect . Square brackets must be used to denote the line to print: [1] not (1). The end = "" code is not necessary but removes space after the line. Practice Task 2 Create a text file (saved in the same folder as your Python file) with a list of video games. Ask the user to enter a number between 1 and 10. Print the line for the number that they input. Example solution: Print a Random Line The randint command can be imported and used to print a random line from a file . The example below prints one of the 12 months . The file is opened in read mode and the readlines() command extracts each line , placing them in a list . A random number is then generated between 0 and one less than the total number of lines . This random number is then used to print a line from the extracted list of lines . Python code from random import randint file = open ( "months.txt" , "r" ) lines = file.readlines() random = randint(0,11) print (lines[random]) months.txt January February March April May June July August September October November December potential outputs March December April July If the length of the file is not fixed (e.g. new lines are being added or lines removed ) then the random number generation line can be adapted to use the len command to calculate the current number of lines . This is required to know the upper limit of the random number . random = randint(0,len(lines)-1) Searching Through Files A for loop is used to search through a file , line by line . First, an input line is used to allow the user to enter their search term . If the term that is being searched for is found, then the whole line is printed. The example below uses a variable named found to state if there is a match when the file is searched. If the search term is found, then the found variable is changed to true . If the search term is not found , the found variable remains as false, so the 'no customers found' statement is printed . Practice Task 3 You should have completed Practice Task 2 from Section 10a (the A Level task). Add extra code to that program so that you can search for specific students. Example solution: ⬅ 10a - Open & Write Files 10c - Remove & Edit Lines ➡

© CSNewbs 2026

The written, video and visual content of CSNewbs is protected by copyright. © 2026
bottom of page