Podcast
Questions and Answers
Which of the following is the correct way to embed both single and double quotes within a single string in Python?
Which of the following is the correct way to embed both single and double quotes within a single string in Python?
- Both B and C (correct)
- `print("I can display 'single' and \"double\" quotes here")`
- `print("""I can display 'single' and \"double\" quotes here""")`
- `print('I can display \'single\' and "double" quotes here')`
What is the primary purpose of comments in Python code?
What is the primary purpose of comments in Python code?
- To import external libraries and modules into the current program.
- To provide notes of explanation within a program, ignored by the Python interpreter. (correct)
- To be executed by the Python interpreter to perform specific tasks.
- To define variables and data structures used in the program.
Which of the following is a valid example of an end-line comment in Python?
Which of the following is a valid example of an end-line comment in Python?
- `print('Hello World') #This is a comment` (correct)
- `#print('Hello World')`
- `/* print('Hello World') */`
- `// print('Hello World')`
What is the role of an assignment statement in Python?
What is the role of an assignment statement in Python?
In an assignment statement, where should the variable receiving the value be located?
In an assignment statement, where should the variable receiving the value be located?
Which of the following variable names is invalid in Python?
Which of the following variable names is invalid in Python?
What will be the output of the following Python code?
width = 10
length = 5
print('width')
print(width)
What will be the output of the following Python code?
width = 10
length = 5
print('width')
print(width)
Which of the following is true regarding variable names in Python?
Which of the following is true regarding variable names in Python?
During the fetch-decode-execute cycle, what is the primary role of the 'decode' stage?
During the fetch-decode-execute cycle, what is the primary role of the 'decode' stage?
Why is assembly language considered more practical for programmers than machine language?
Why is assembly language considered more practical for programmers than machine language?
Which of the following is a characteristic of high-level programming languages?
Which of the following is a characteristic of high-level programming languages?
In the context of programming languages, what is the significance of 'syntax'?
In the context of programming languages, what is the significance of 'syntax'?
What is the key difference between a compiler and an interpreter?
What is the key difference between a compiler and an interpreter?
What happens when a syntax error is present in the source code?
What happens when a syntax error is present in the source code?
Consider a program written in a high-level language. Which of the following sequences accurately describes the process of executing this program?
Consider a program written in a high-level language. Which of the following sequences accurately describes the process of executing this program?
Which of the following scenarios best illustrates the use of an assembler?
Which of the following scenarios best illustrates the use of an assembler?
What is the result of the expression 10 + 5 * 2 // 3 - 1
in Python, considering operator precedence?
What is the result of the expression 10 + 5 * 2 // 3 - 1
in Python, considering operator precedence?
If x = 15
and y = 4
, what will be the output of print(x // y, x % y)
?
If x = 15
and y = 4
, what will be the output of print(x // y, x % y)
?
What is the data type of the result when you divide an integer by a float in Python?
What is the data type of the result when you divide an integer by a float in Python?
If you need to determine if a number is even, which operator is most suitable in Python?
If you need to determine if a number is even, which operator is most suitable in Python?
What is the result of the expression 2 ** 3 + 5.0 // 2
?
What is the result of the expression 2 ** 3 + 5.0 // 2
?
Which of the following statements about operator precedence in Python is correct?
Which of the following statements about operator precedence in Python is correct?
What is the output of the following code snippet?
num1 = 7.0
num2 = 3
result = num1 // num2
print(result)
What is the output of the following code snippet?
num1 = 7.0
num2 = 3
result = num1 // num2
print(result)
What does the format specifier '.2f' indicate when formatting a floating-point number?
What does the format specifier '.2f' indicate when formatting a floating-point number?
When using the format
function in Python, what is the purpose of specifying a minimum field width?
When using the format
function in Python, what is the purpose of specifying a minimum field width?
If you want to format a number as a percentage using the format
function, which symbol should be included in the format string?
If you want to format a number as a percentage using the format
function, which symbol should be included in the format string?
What is the correct way to format an integer using the format
function, specifying a field width of 10?
What is the correct way to format an integer using the format
function, specifying a field width of 10?
What is the primary benefit of using named constants in a program?
What is the primary benefit of using named constants in a program?
What is the purpose of the statement turtle.initializeTurtle()
in the context of Turtle graphics on Google Colab?
What is the purpose of the statement turtle.initializeTurtle()
in the context of Turtle graphics on Google Colab?
If import turtle
is used, which statement moves the turtle forward by 50 pixels?
If import turtle
is used, which statement moves the turtle forward by 50 pixels?
What is the turtle's initial heading in degrees when it is first created in the turtle graphics system?
What is the turtle's initial heading in degrees when it is first created in the turtle graphics system?
A program continuously prompts a user for input until they enter 'quit'. Which type of loop would be most appropriate for this task?
A program continuously prompts a user for input until they enter 'quit'. Which type of loop would be most appropriate for this task?
Which of the following is a potential drawback of duplicating code instead of using a repetition structure?
Which of the following is a potential drawback of duplicating code instead of using a repetition structure?
What is the primary purpose of using relational and logical operators within a while
loop's condition?
What is the primary purpose of using relational and logical operators within a while
loop's condition?
Consider the following scenario: you need to process each item in a list, but only if a certain condition is met. Inside the loop, if another condition is met, you skip to the next element. Which control structures are involved?
Consider the following scenario: you need to process each item in a list, but only if a certain condition is met. Inside the loop, if another condition is met, you skip to the next element. Which control structures are involved?
What is the most important characteristic of a condition-controlled loop?
What is the most important characteristic of a condition-controlled loop?
Which of the following scenarios is best suited for using a count-controlled loop (e.g., a for
loop)?
Which of the following scenarios is best suited for using a count-controlled loop (e.g., a for
loop)?
How do nested decision structures differ from nested loops in terms of program execution?
How do nested decision structures differ from nested loops in terms of program execution?
Consider this code:
x = 0
while x < 10:
if x % 2 == 0:
print(x, 'is even')
x += 1
How many times will 'x
is even' be printed?
Consider this code:
x = 0
while x < 10:
if x % 2 == 0:
print(x, 'is even')
x += 1
How many times will 'x
is even' be printed?
What is the primary function of the target variable within a loop?
What is the primary function of the target variable within a loop?
If a range()
function is used to generate numbers in descending order, which of the following conditions must be met?
If a range()
function is used to generate numbers in descending order, which of the following conditions must be met?
In the context of calculating a running total, what is the role of the accumulator variable?
In the context of calculating a running total, what is the role of the accumulator variable?
What is the purpose of augmented assignment operators in programming?
What is the purpose of augmented assignment operators in programming?
What is a key consideration when using a range()
function where inputs are variables provided by the user?
What is a key consideration when using a range()
function where inputs are variables provided by the user?
Consider this code:
total = 0
for i in range(1, 5):
total += i
print(total)
What will be the output of this code?
Consider this code:
total = 0
for i in range(1, 5):
total += i
print(total)
What will be the output of this code?
Which code snippet will successfully calculate the square root of each number in the range from 25 to 30 (inclusive) using the math.sqrt()
function?
Which code snippet will successfully calculate the square root of each number in the range from 25 to 30 (inclusive) using the math.sqrt()
function?
What will the following code display?
for num in range(10, 5, -2):
print(num, end=" ")
What will the following code display?
for num in range(10, 5, -2):
print(num, end=" ")
Flashcards
Program Loading
Program Loading
Copying a program from secondary storage (like a hard drive) to RAM for the CPU to execute.
Fetch-Decode-Execute Cycle
Fetch-Decode-Execute Cycle
The cycle the CPU uses to execute programs: fetch, decode, execute.
Assembly Language
Assembly Language
Uses mnemonics (short words) for instructions, making it easier to write code than machine language.
Assembler
Assembler
Signup and view all the flashcards
High-Level Language
High-Level Language
Signup and view all the flashcards
Key Words
Key Words
Signup and view all the flashcards
Compiler
Compiler
Signup and view all the flashcards
Interpreter
Interpreter
Signup and view all the flashcards
print() function
print() function
Signup and view all the flashcards
Comments
Comments
Signup and view all the flashcards
End-line comment
End-line comment
Signup and view all the flashcards
Variable
Variable
Signup and view all the flashcards
Assignment statement
Assignment statement
Signup and view all the flashcards
Assignment Operator
Assignment Operator
Signup and view all the flashcards
Python keywords
Python keywords
Signup and view all the flashcards
Case sensitivity
Case sensitivity
Signup and view all the flashcards
Floating Point Division (/)
Floating Point Division (/)
Signup and view all the flashcards
Integer Division (//)
Integer Division (//)
Signup and view all the flashcards
Operator Precedence
Operator Precedence
Signup and view all the flashcards
Order of Operations
Order of Operations
Signup and view all the flashcards
Exponent Operator (**)
Exponent Operator (**)
Signup and view all the flashcards
Remainder Operator (%)
Remainder Operator (%)
Signup and view all the flashcards
Mixed-Type Expression
Mixed-Type Expression
Signup and view all the flashcards
Data Type Conversion
Data Type Conversion
Signup and view all the flashcards
Format Specifier
Format Specifier
Signup and view all the flashcards
Minimum Field Width
Minimum Field Width
Signup and view all the flashcards
Percent (%) Symbol
Percent (%) Symbol
Signup and view all the flashcards
Integer Format ('d')
Integer Format ('d')
Signup and view all the flashcards
Named Constant
Named Constant
Signup and view all the flashcards
Turtle Graphics
Turtle Graphics
Signup and view all the flashcards
Import Turtle
Import Turtle
Signup and view all the flashcards
turtle.forward(n)
turtle.forward(n)
Signup and view all the flashcards
Repetition Structure
Repetition Structure
Signup and view all the flashcards
Disadvantages of Duplicated Code
Disadvantages of Duplicated Code
Signup and view all the flashcards
Condition-Controlled Loop
Condition-Controlled Loop
Signup and view all the flashcards
while Loop
while Loop
Signup and view all the flashcards
while Keyword
while Keyword
Signup and view all the flashcards
while Loop Condition
while Loop Condition
Signup and view all the flashcards
while Loop Statements
while Loop Statements
Signup and view all the flashcards
Flow Chart
Flow Chart
Signup and view all the flashcards
Target Variable (Loop)
Target Variable (Loop)
Signup and view all the flashcards
User-Controlled Loop Iterations
User-Controlled Loop Iterations
Signup and view all the flashcards
Descending Range
Descending Range
Signup and view all the flashcards
Running Total
Running Total
Signup and view all the flashcards
Accumulator Variable
Accumulator Variable
Signup and view all the flashcards
Augmented Assignment Operators
Augmented Assignment Operators
Signup and view all the flashcards
Shorthand Operators
Shorthand Operators
Signup and view all the flashcards
Calculating a Running Total
Calculating a Running Total
Signup and view all the flashcards
Study Notes
Introduction to Computers and Programming
- CSBP119: Algorithms & Problem Solving at CIT, UAEU is the context
- Discusses introduction, hardware, software, data storage, program execution, and Python usage
Introduction
- Computers are programmable and can perform tasks as directed by programs
- A program is a set of instructions for a computer to perform a task
- Software is commonly used to refer to programs
- A programmer designs, creates, and tests computer programs and is also known as a software developer
Hardware and Software
- Hardware comprises the physical devices of a computer
- A computer is a system of interconnected components
Typical major components of Hardware
- Central Processing Unit (CPU)
- Main memory
- Secondary storage devices
- Input and output devices
The CPU
- Central Processing Unit (CPU) runs programs and is the most important component
- Without the CPU, software cannot run
- Microprocessors are CPUs on small chips
Main Memory
- Main memory stores programs during execution and the data they use
- Also known as Random Access Memory (RAM)
- The CPU can quickly access data stored in RAM
- RAM is volatile memory for temporary storage while the program is running
- RAM contents are erased when the computer is turned off
Secondary Storage Devices
- Secondary storage holds data for extended periods
- Programs are usually stored in secondary storage and loaded into main memory when needed
Types of secondary memory
- Disk drives magnetically encode data on spinning circular disks
- Solid State Drives (SSDs) stores data in solid-state memory, is faster than disk drives, and has no moving parts
- Flash memory is portable with no physical disk
- Optical devices encode data optically
Input Devices
- Input is data collected by the computer from people and other devices
- Input devices collect data
- Keyboards, mice, touchscreens, scanners, and cameras are examples
Output Devices
- Output is data produced by the computer for users and other devices
- Output can be text, images, audio, or bit streams
- Output devices format and present the output
- Video displays and printers are examples
Software
- Software controls all computer operations
- General categories of software are application and system software
- Application software makes computers useful for everyday tasks
- Word processing, email, games, and web browsers are examples
How Computers Store Data
- All computer data is stored as sequences of 0s and 1s
- A byte is enough memory to store a letter or small number
- A byte is divided into eight bits
- A bit is an electrical component holding positive or negative charge, like an on/off switch
- The on/off pattern of bits in a byte represents the data stored
Storing Numbers
- A bit has two values: 0 and 1
- Computers use the binary numbering system
- A digit's position j has the value 2^(j-1)
- A binary number's value sums the position values of the 1s
- Byte size limits are 0 and 255
- 0 means all bits are off and 255 means all bits are on
- Multiple bytes are used to store larger numbers
Storing Characters
- Data stored in a computer must be stored as a binary number
- Characters are converted to numeric code, which is stored in memory
- ASCII is the most important coding scheme
- ASCII is limited to 128 characters
- Unicode is becoming a coding scheme standard
- Unicode is compatible with ASCII
- Unicode can represent characters for other languages
How a Program Works
- CPUs are designed to perform simple operations on data like reading, adding, subtracting, multiplying, and dividing numbers
- CPUs understand instructions written in machine language included in their instruction set
- Each CPU brand has its instruction set
- The CPU must perform many operations to carry out meaningful calculations
How a Program Works (cont'd.)
- Programs must be copied from secondary memory to RAM each time the CPU executes it
- The CPU executes programs in a cycle
- The steps include fetch, decode, and execute
- Fetch involves reading the next instruction from memory into CPU
- Decode means the CPU decodes the fetched instruction to determine operation
- Execute is performing the operation
From Machine Language to Assembly Language
- It is impractical for people to write in machine language
- Assembly language uses short words (mnemonics) for instructions, instead of binary numbers, making it easier for programmers
- Assemblers translate assembly language into machine language for execution by CPU
High-Level Languages
- Low-level language is close to machine language
- Assembly language is an example
- High-level languages allow simple creation of powerful and complex programs
- No need to know CPU specifics or write many instructions
- More intuitive to understand
Key Words, Operators, and Syntax: an Overview
- Key words are predefined words for writing programs in high-level language and each has a specific meaning
- Operators perform operations on data such as arithmetic
- Syntax is the set of rules for writing programs
- A statement is an individual instruction in a high-level language
Compilers and Interpreters
- Programs in high-level languages must be translated into machine language to be executed
- A compiler translates high-level language programs into separate machine language programs
- The Machine language programs an be executed at any time
Compilers and Interpreters (cont'd.)
- An interpreter translates and executes instructions in a high-level language program
- The Python language is interpreted
- The interpreter interprets one instruction at a time
- There is no separate machine language program
- Source code is statements written by a programmer
- A syntax error prevents code from being translated
Using Python
- Python must be installed and configured before use
- Included is the Python interpreter
- The Python interpreter can be used in two modes
- Interactive, to enter statements
- Script, to save statements in a Python Script
Interactive Mode
- A prompt indicates the interpreter is ready
- The prompt reappears after statement is executed
- Error messages are displayed after incorrectly typed statements
- Interactive mode is a good way to learn Python
Writing Python Programs and Running Them in Script Mode
- Statements entered in interactive mode are not saved as programs
- To use a program, it must use script mode
- First, save Python statements in a file
- The filename should have a ".py" extension
- Run the file, or script, by typing “python filename” at the operating system command line
Summary
- Main hardware components of the computer, and types of software
- How data is stored in a computer
- Basic CPU operations and machine language
- Fetch-decode-execute cycle
- Complex languages and their translation to machine code
- Python installation and Python interpreter modes
Input, Processing, & Output
- Designing a Program
- Input, Processing, and Output
- Displaying Output with the “print” Function
- Comments
- Variables
- Reading Input from the Keyboard
- Performing Calculations
- More About Data Output
- Named Constants
- Introduction to Turtle Graphics
Designing a Program
- Programs must be designed before written
- Program development cycle includes steps such as design, code writing, error correction, testing, and correcting logic errors
- Determine steps to perform a task then break it down into a series of steps
- An algorithm lists logical steps to be order taken
Pseudocode
- Pseudocode is fake code and an informal language without syntax rules
- It is not meant to be compiled or executed, but is used to create a model program
- There is no need to worry about syntax errors which allows one to focus on the design
- Pseudocode can be translated into actual code in any programming language
- The general order is input, processing and then output
Example Algorithm in Pseudocode
- Input the number of hours worked
- Input the hourly pay rate
- Calculate gross pay as the number of hours worked times hourly pay rate
- Display the gross pay
Flowcharts
- Flowcharts graphically depict steps in a program
- Ovals are terminal symbols
- Parallelograms are input and output symbols
- Rectangles are process symbols
- Symbols are connected by arrows that represent the flow
Input, Processing, and Output
- Computers typically perform a three-step process
- Receive input
- Perform some process on the input
- Produce output
- Input is any running program data
- Processing is what a program performs on input
- An example mathematical calculation
- Hours worked, hourly pay rate are both examples of input
- Multiply hours worked by hourly pay rate is processing
- Gross pay is the output
Functions
- A function is a section of prewritten code performing an operation
- An argument provides data to a function
- program operates on the order they appear
- The operate from top to bottom
Example: Displaying Output with the print Function
- Syntax: print(’Hello World’)
- The print function displays output to the screen
- “Hello World” is the argument which is the screen output
Strings and String Literals
- A string is a sequence of characters, being zero or more, used as data
- A string is a type of data
- A string literal is a string appearing in actual code
Rules for String Literals
- Must be enclosed in single (') or double (") quote marks
- Example: 'Hello World', "Hello world"
- String literals can be enclosed in triple quotes (""" or ''')
- Example: print("""I can display 'single' and "double" quotes here""")
- Enclosed strings can contain both single and double quotes and can have multiple lines
Examples
- print ('Hello World')
- print ("I can display single 'quotes' here!")
- print ('I can display double "quotes" here')
- print ("""I can display 'single' and "double" quotes here""")
Output:
- Hello World
- I can display single 'quotes' here!
- I can display double "quotes" here
- I can display 'single' and "double" quotes here
Comments
- Comments are explanatory notes within the program that are ignored by the interpreter
- Start with "#" character
End Line Comments
- Display at the end of the line of code
- Example: print ('Hello World') #diaplay statement
Variables
- A variable stores a value in computer memory
- Variables are used to access and manipulate stored memory data
- Variables reference the value they represent
- An assignment statement creates a variable and makes it reference data
Using Assignment Statements
- The general format is variable = expression
- Example: age = 29
- Assignment operators feature the "=" sign
Program with Variables
- #this program creates two variables
- width = 10
- length = 5
- print('width') #displays the string width
- print(width) #displays the variable width
Program Output
- width
- 10
- 5
Variables (cont'd.)
- Using assignment statements the receiving variables must be on the left
- Variables can be passed as an argument to a function
- Variable names must not be in quotation marks
Variable Naming Rules
- Variable names cannot be a Python key word
- Variable names cannot contain spaces
- First character must be a letter or underscore
- After the first character can use letters, digits, or underscores
- Variable names are case sensitive
- It should reflect its use
Displaying Multiple Items with the Print Function
- Python can display multiple items
- Items are separated by comas
- The program displays in order
- Items are automatically separated by a space
- Use "end=" to change a printed string termination
- Use "sep=" to change separator between printed string
Example
width" = 10
length =5
print ( 'the width is’, 'width’ )
print("The length is ', length)
Output:
The with is 10
The length is 5
Variable Reassignment
Variables can change values while program is running
-garbage collection removes unused values
- Variables can refer to item in type and the type can be reassigned
Numeric Data Types, Literals, and the str Data Type
- Data types categorize values in memory
- Ints store integer and floats store string
- Numeric literal are num values with in a program
- No decimal points are integers but other wise can store float
- Operations depending on the datat type
Numerical Data Types
- Value =2.6 print int (Value)
OUPUT: 2
Reading Input from the Keyboard
- Most programs utilize user input that is read from the built in keyboard
- Returns data only as a string
- Variable= Input prompt example
- Does not already displays space after prompt
- Variable is an output while prompt is the user interaction
Example
"print('Hello', name) #then displays a greeting #first displays the prompt and store the input in name name=input("what is your name? ") #then display a greeting print('Hi', name)"
OUTPUT: what is your name? Holly Holly is hi
Reading Numbers with the input Function
- The Input function returns always a string
- Built in functions are able to convert between datatypes
- Example in < (items) converts time to int
- Float function (items) converts item to float
- Nested functions calls have general for mat
function one(funcionTwo (arguments.
- Types conversion only works if the item is a valid number value
Performing Calculations
- math expression performals some calculations by providing a value by being
- MATH tool
- OPERANDS.
- The results assign variables
The Math operators follow
(+)Addition (-)Subtraction (*)Multiplication (/)Division (**) = Raised
"Rate= (float (input ‘ is your hourly rate is’?)
rate= float (Input ‘what hourly rates?)"
Inter Vs Flat
- Inter division truncate = 5//2 #Integer Point display number
Result
Point=6/8=Float point
More example Values for display math operators
- (+) (5+2) *4=26
- (*) 10/(3-@) =/
- (Float) =2
- % remainder operators
Mixed-Type Expressions and Data Type Conversion
- Int and floa are an impory type
- A number is a temporatry can convert to the floating point
- A type conversion can store from a plot but may cases a traction
Examples
MixedType Examples
“ value=0.9 point
“print (int Value ()
- Multiline contamination charectors
Result Val 1* (4+ val 4 *. Val
Turtle Graphic
Python graphic model displays code with a smaller cursor displays the tools
""import turtle Turtle forward (50) Turtle pensue (5) """
###Summary
- Designing programs and cycles
- Displaying multiple items with print functions-
- Using comments, variables, and name
- Perform math calculation
- Turtles graphics system
Booleans Eprression
Bool expressions use the following values
- Relationals
-
equals -==Equals two the value
The Statement
" - Is the statement if condition
- Block 1 is the other statement. Bool expression "
- if score >= 90 # score is a b
- print #score equal print to a
Relational Operators
A relation operation relation weather expression is bwetwwn to values
Comparing Stings
- if name 1 name 2 print
-
- Copyright c pearson value
logcial operation
“Bool operators and, O R connect Bool varible
1 If scarry and “
Optional Slides
“turtles graphics is system by adding small cursives You ca use that Turtle turtle #Import model Turtle for word (344) Turtle side true (3 points)
"""
Studying That Suits You
Use AI to generate personalized quizzes and flashcards to suit your learning preferences.