BE1600 - Exam 01 Review (F24).pptx
Document Details
Uploaded by Deleted User
Full Transcript
1 BE 1600 Introduction to Programming and Computation Fall Term 2024 Exam 01 10/10/2024 2 Exam Instructions Date: Thursday 10/10/2024 Time: Class time Location: Shapero| Room 100 Exam dur...
1 BE 1600 Introduction to Programming and Computation Fall Term 2024 Exam 01 10/10/2024 2 Exam Instructions Date: Thursday 10/10/2024 Time: Class time Location: Shapero| Room 100 Exam duration: total 60 minutes Please, arrive 10 minutes before the exam begins. There will be No make-up Exam (NO EXCEPTION) Exam Instructions The exam is Closed Book/Closed Notes. You can use one cheat sheets (81/2 x 14), typed or handwritten. Submit your cheat sheet with your exam copy. Do not write your name on the cheat sheet. No electronic devices may be used during the examination, i.e. no calculator, cell phones, mp3 players, laptops, etc. Make sure you complete the requested information at the top of the exam. Please ensure you have your picture ID, as we may ask you to show it during the exam to confirm your name. Exam Instructions There will be 40 Multiple-Choice Questions (200 points) Answer each multiple-choice question by selecting the correct response. You should choose the single best alternative for each multiple-choice question, even if you believe that a question is ambiguous or contains a typographic error. Provide only one answer. When completing the exam, please leave the room and be courteous to those still taking the exam. What to Study? Four chapters Chapter 1: Introduction to Computers and Programming Chapter 2: Input, Processing, and Output Chapter 3: Decision Structures and Boolean Logic Chapter 4: Repetition Structures 5 Starting out with Python Fifth Edition Chapter 1 Introduction to Computers and Programming Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 2-6 How Computers Store Data All data in a computer is stored in sequences of 0s and 1s Bit represents two values, 0 and 1 Bit: electrical component that can hold positive or negative charge, like on/off switch Byte: just enough memory to store letter or small number Storing Characters Data stored in computer must be stored as binary number Characters are converted to numeric code, numeric code stored in memory – Most important coding scheme is ASCII ▪ ASCII is limited: defines codes for only 128 characters – Unicode coding scheme becoming standard ▪ Compatible with ASCII ▪ Can represent characters for other languages Compilers Programs written in Python (high-level languages) must be translated into machine (binary) language to be executed Compiler: translates high-level language program into separate machine language program – Machine language program can be executed at any time Interpreters Interpreter: translates and executes instructions in high-level language program – Used by Python language – Interprets one instruction at a time – No separate machine language program Compilers and Interpreters Figure 1-19 Executing a high-level program with an interpreter Starting out with Python Fifth Edition Chapter 2 Input, Processing, and Output Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 2 - 13 Displaying Output with the print Function print function: displays output on the screen >>> print('Hello world') Hello world >>> Strings and String Literals String: sequence of characters that is used as data String literal: string that appears in actual code of a program Must be enclosed in single (') or double (") quote marks String literal can be enclosed in triple quotes (''' or """) Enclosed string can contain both single and double quotes and can have multiple lines Comments Comments: notes of explanation within a program Ignored by Python interpreter Intended for a person reading the program’s code Begin with a # character End-line comment: appears at the end of a line of code Typically explains the purpose of that line Variables Variable: name that represents a value stored in the computer memory Used to access and manipulate data stored in memory A variable references the value it represents Assignment statement: used to create a variable and make it reference data General format is variable = expression Example: age = 29 Assignment operator: the equal sign (=) Variable Naming Rules Rules for naming variables in Python: Variable name cannot be a Python key word Variable name cannot contain spaces First character must be a letter or an underscore After first character may use letters, digits, or underscores Variable names are case sensitive Variable name should reflect its use Python key Words and del from not while as elif global or with assert else if pass yield break except import print class exec in raise continue finally is return def for lambda try Numeric Data Types, Literals, and the str Data Type Data types: categorize value in memory e.g., int for integer, float for real number, str used for storing strings in memory Numeric literal: number written in a program No decimal point considered int, otherwise, considered float Some operations behave differently depending on data type Reading Input from the Keyboard Most programs need to read input from the user Built-in input function displays a prompt and reads input from keyboard Returns the data as a string Format: variable = input(prompt) prompt is typically a string instructing user to enter a value Does not automatically display a space after the prompt Reading Numbers with the input Function input function always returns a string Built-in functions convert between data types int(item) converts item to an int float(item) converts item to a float Nested function call: general format: function1(function2(argument)) value returned by function2 is passed to function1 Type conversion only works if item is valid numeric value, otherwise, causes an error Performing Calculations Operators Symbol Operation Description + Addition Adds two numbers − Subtraction Subtracts one number from another * Multiplication Multiplies one number by another / Division Divides one number by another and gives the result as a floating-point number // Integer Division Divides one number by another and gives the result as a whole number % Remainder Divides one number by another and gives the remainder ** Exponent Raises a number to a power Operator Precedence and Grouping with Parentheses Python operator precedence: 1. Operations enclosed in parentheses Forces operations to be performed before others 2. Exponentiation (**) 3. Multiplication (*), division (/ and //), and remainder (%) 4. Addition (+) and subtraction (-) Higher precedence performed first Same precedence operators execute from left to right Mixed-Type Expressions and Data Type Conversion Data type resulting from math operation depends on data types of operands Two int values: result is an int Two float values: result is a float int and float: int temporarily converted to float, result of the operation is a float Mixed-type expression Type conversion of float to int causes truncation of fractional part String Concatenation To append one string to the end of another string Use the + operator to concatenate strings >>> message = 'Hello ' + 'world' >>> print(message) Hello world >>> String Concatenation You can use string concatenation to break up a long string literal print('Enter the amount of ' + 'sales for each day and ' + 'press Enter.') This statement will display the following: Enter the amount of sales for each day and press Enter. More About The print Function print function displays line of output Newline character at end of printed data Special argument end='delimiter' causes print to place delimiter at end of data instead of newline character print function uses space as item separator Special argument sep='delimiter' causes print to use delimiter as item separator More About The print Function Special characters appearing in string literal Preceded by backslash (\) Examples: newline (\n), horizontal tab (\t) Treated as commands embedded in string Displaying Formatted Output with F-strings Format specifiers can be used with placeholders >> num = 123.456789 >> print(f'{num:.2f}') 123.46 >>>.2f means: round the value to 2 decimal places display the value as a floating-point number Displaying Formatted Output with F-strings Other examples: >> num = 123456789 >> print(f'{num:,d}') 123,456,789 >>> num = 12345.6789 >>> print(f'{num:.2e}') 1.23e+04 Displaying Formatted Output with F-strings Specifying a minimum field width: >>> num = 12345.6789 >>> print(f'The number is {num:12,.2f}') The number is 12,345.68 Field width = 12 The number is 12,345.68 Field width = 12 Displaying Formatted Output with F-strings Aligning values within a field Use < for left alignment Use > for right alignment Use ^ for center alignment Examples: print(f'{num:20.2f}') print(f'{num:^20.2f}') Displaying Formatted Output with F-strings The order of designators in a format specifier When using multiple designators in a format specifier, write them in this order: [alignment][width][,][.precision][type] Named Constants You should use named constants instead of magic numbers. A named constant is a name that represents a value that does not change during the program's execution. Example: INTEREST_RATE = 0.069 This creates a named constant named INTEREST_RATE, assigned the value 0.069. It can be used instead of the magic number: amount = balance * INTEREST_RATE Starting out with Python Fifth Edition Chapter 3 Decision Structures and Boolean Logic Copyright © 2021, 2018, 2015 Pearson Education, Inc. All Rights Reserved 2 - 36 Boolean Expressions and Relational Operators Single-Line if Statements An if statement can be written on a single line if it executes only one statement. Python syntax: if condition: statement Example: if score > 59: print('You passed!') The if-else Statement Dual alternative decision structure: two possible paths of execution – One is taken if the condition is true, and the other if the condition is false Syntax: if condition: statements else: other statements if clause and else clause must be aligned Statements must be consistently indented The if-elif-else Statement if-elif-else statement: special version of a decision structure Makes logic of nested decision structures simpler to write Can include multiple elif statements Syntax: if condition_1: statement(s) elif condition_2: statement(s) Insert as many elif clauses elif condition_3: as necessary. statement(s) else statement(s) Comparing Strings Strings can be compared using the == and != operators String comparisons are case sensitive Strings can be compared using >, =, and