Introduction to Python Programming

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson

Questions and Answers

What is the primary purpose of the try and except blocks in Python when handling errors?

  • To automatically fix any errors that occur during program execution.
  • To force the program to terminate immediately upon encountering any error.
  • To handle anticipated errors gracefully without crashing the program. (correct)
  • To prevent errors from occurring in the first place.

In Python, what is the correct way to open a file named data.txt in read mode and assign it to a file object?

  • `with open("data.txt", "r") as file:` (correct)
  • `open("data.txt", "read") as file`
  • `file = open("data.txt", mode='read')`
  • `file = open("data.txt", "w+")`

Given the list fruits = ["apple", "banana", "cherry"], how would you access the first element ("apple") of the list?

  • `fruits.first()`
  • `fruits["first"]`
  • `fruits[0]` (correct)
  • `fruits[1]`

What is the result of the following Python code?

x = 7
if x > 10:
    print("x is greater than 10")
elif x == 7:
    print("x is exactly 7")
else:
    print("x is less than 10")

<p><code>x is exactly 7</code> (C)</p> Signup and view all the answers

Which of the following best describes the use of a for loop with range() in Python?

<p>To iterate over a sequence of numbers. (C)</p> Signup and view all the answers

Given the following code snippet, what will be the output?

count = 0
while count < 3:
    print("Count:", count)
    count += 1

<p>It will print <code>Count: 0</code>, <code>Count: 1</code>, <code>Count: 2</code>. (D)</p> Signup and view all the answers

In the context of file handling in Python, what does the w mode signify when opening a file?

<p>Open the file in write mode, creating the file if it does not exist and overwriting it if it does. (C)</p> Signup and view all the answers

What is the purpose of the def keyword in Python?

<p>To define a function. (B)</p> Signup and view all the answers

Consider the following Python dictionary: student = {"name": "Caren", "age": 22, "major": "MIS"}. How would you correctly access the value associated with the key "age"?

<p><code>student[&quot;age&quot;]</code> (A)</p> Signup and view all the answers

What is the output of this code?

def greet(name):
    print("Hello, " + name + "!")

greet("World")

<p><code>Hello, World!</code> (D)</p> Signup and view all the answers

Flashcards

What is a variable in Python?

A named storage location that can hold a value (e.g., name = "Caren").

What are If-Else Statements?

Statements that execute different code blocks based on whether a condition is true or false.

What is a 'while' loop?

A control flow statement that repeatedly executes a block of code as long as a condition is true.

What is a Function?

A reusable block of code that performs a specific task. It’s defined using the def keyword.

Signup and view all the flashcards

What is a List?

An ordered collection of items; similar to an array. Created using square brackets [].

Signup and view all the flashcards

What is a Dictionary?

A collection of key-value pairs. Keys are unique identifiers, and values are data associated with those keys.

Signup and view all the flashcards

What is File Handling?

Allows a program to interact with files on a storage device, enabling data to be read from or written to files.

Signup and view all the flashcards

What is Error Handling (Try-Except)?

A mechanism to handle runtime errors gracefully, preventing the program from crashing.

Signup and view all the flashcards

Study Notes

  • Python displays text using the print() function, such as Print(“Hello, World!”).
  • Variables are used to store information; for example, name = "Caren" stores the name "Caren".
  • Numerical data can be stored as integers, like age = 22, or as decimal numbers, like price = 19.99.
  • User input can be obtained using the input() function, as in user_input = input("Enter something: ").

If-Else Statements

  • Python uses if, elif (else if), and else to make decisions based on conditions.
  • Example:
x = 10
if x > 5:
    print("x is greater than 5")
elif x == 5:
    print("x is exactly 5")
else:
    print("x is less than 5")

Loops

  • Loops are used to repeat actions.
  • The for loop can iterate over a range of numbers:
for i in range(1, 6):
    print(i)
  • The while loop continues as long as a condition is true:
count = 0
while count < 5:
    print("Count:", count)
    count += 1

Functions

  • Functions are blocks of code that can be called to perform specific tasks.
  • Defined using the def keyword:
def greet(name):
    print("Hello, " + name + "!")
  • Functions are then called by name; for example, greet("Caren").

Lists and Dictionaries

  • Lists store ordered collections of items: fruits = ["apple", "banana", "cherry"].
  • Accessing list elements, for example, print(fruits[0]) outputs "apple".
  • Dictionaries store key-value pairs: student = {"name": "Caren", "age": 22, "major": "MIS"}.
  • Accessing dictionary values, for example, print(student["name"]) outputs "Caren".

File Handling

  • Files can be opened in write mode ("w") to save data:
with open("test.txt", "w") as file:
    file.write("Hello, this is a test file!")
  • Files can be opened in read mode ("r") to retrieve data:
with open("test.txt", "r") as file:
    content = file.read()
    print(content)

Handling Errors

  • try and except blocks catch errors without crashing the program:
try:
    num = int(input("Enter a number: "))
    print(10 / num)
except ZeroDivisionError:
    print("You can't divide by zero!")
except ValueError:
    print("Invalid input! Please enter a number.")

Overtime Pay Program

  • The program calculates weekly pay based on hours worked:
def payFunction(hours):
    payrate = 20.756
    if hours > 40:
        extraHours = hours - 40
        pay = payrate * 40 + extraHours * payrate * 1.5
    else:
        pay = payrate * hours
    print("Your weekly pay is", round(pay, 2))

hours = float(input("Please enter total hours worked: "))
if hours < 0 or hours > 80:
    print("Invalid input. Hours should be between 0-80")
else:
    payFunction(hours)
  • It asks for hours worked, adds extra pay for more than 40 hours (1.5x rate), and calculates regular pay if less than 40 hours.

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

Related Documents

More Like This

Python Syntax and Design Philosophy Quiz
6 questions
Python Syntax and Basics
5 questions
Python Basic Syntax Quiz
6 questions
Introduction to Python Syntax
5 questions
Use Quizgecko on...
Browser
Browser