cs245 exam 2 python

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

Describe the general structure of a Python program, including imports, function definitions, and the main() function.

A Python program generally has imports at the top, followed by function definitions, and then the main logic (often in a main() function). It may include a call to main() at the end to start execution.

What is the syntax of a match/case statement in Python, and how does it differ from a switch statement in C?

A match/case statement in Python uses match expression: case value:. Unlike C's switch, Python's case expressions can be complex, and there's no need for break.

What is a tuple, and how is it different from a list?

A tuple is an immutable collection of elements. Unlike lists, tuples cannot be modified after creation.

List the basic data types in Python and provide examples of each.

Basic data types: int (e.g., 42), float (e.g., 3.14), bool (e.g., True), str (e.g., "Hello"), and collections like list, tuple, set, and dict.

How are command line arguments accessed in a Python program?

By importing sys and using sys.argv, where sys.argv[0] is the script name and additional elements are arguments.

How can a function return multiple values in Python?

By returning a tuple, e.g., return (index, value)

Explain the difference between integers and floating-point numbers in Python.

Integers (int) are whole numbers, while floating-point numbers (float) represent real numbers with decimal points.

How can you access elements in a list, tuple, set, and dictionary?

List/tuple elements are accessed by index (list[0]). Sets do not support indexing. Dictionary values are accessed by key (dict["key"]).

How are lists created in Python, and how do you access their elements

Lists are created with square brackets, e.g., data = [10, 20, 30]. Elements are accessed by index, e.g., data[0].

Explain the different types of collections in Python: lists, tuples, sets, and dictionaries.

Lists are ordered, changeable collections ([1, 2, 3]). Tuples are ordered and immutable ((1, 2, 3)). Sets are unordered, unique collections ({1, 2, 3}). Dictionaries map keys to values ({"a": 1, "b": 2}).

How do you assign multiple variables in Python? Provide examples of swapping two variables.

Multiple assignments can be done as a, b = 1, 2. To swap: a, b = b, a.

Why does Python not require a main() function, unlike languages like Java and C?

Python does not require a main() function because it executes code sequentially from top to bottom. However, main() is often used for clarity and to organize code when coming from languages like Java or C.

Explain how Python uses lexical scoping.

Python uses lexical (or static) scoping, meaning a variable is only accessible within the block it is defined in and any inner blocks.

Describe the syntax and use of an if-statement in Python.

Python's if-statement syntax is if condition:, followed by indented statements. It may include elif and else clauses.

What does primes[0:3] return if primes = [2, 3, 5, 7, 11, 13]?

Returns [2, 3, 5].

What are the main characteristics of sets in Python, and why are they unique among collections?

Sets are unordered, unindexed, and contain unique elements, making them efficient for membership tests.

How do you define strings in Python, and what operations can be performed on them?

Strings are defined with single, double, or triple quotes. Operations include concatenation (+), indexing (s[i]), and length (len(s)).

Explain the syntax of a ternary conditional expression in C, C++, or Java.

Syntax: <condition> ? <expression1> : <expression2>. This returns <expression1> if the condition is true; otherwise, it returns <expression2>.

What is the exponentiation operator in Python, and how is it used?

The exponentiation operator is **. For example, 2 ** 3 calculates 23=823=8.

How does the in operator work in Python? Provide examples using lists.

The in operator checks for membership. For example, 2 in [1, 2, 3] returns True, while 4 in [1, 2, 3] returns False.

What does the following line do? printf("It will take %d minute%c.\n", m, (m > 1) ? 's' : '\0'); what language

This prints It will take X minutes. if m > 1; otherwise, it prints It will take X minute. by conditionally adding the 's'.

What are the rules for naming variables in Python?

Variable names must start with a letter or underscore, followed by letters, numbers, or underscores (e.g., my_var

Does Python have a ternary conditional expression?

Yes, in the form: a if condition else b.

Define a function in Python that takes two arguments and returns the larger one.

def max(a, b): return a if a > b else b

Write a program that prints numbers from 1 to 100. However, for numbers that are multiples of three it prints the word "Fizz" instead of the number, for multiples of five, it prints "Buzz". And, for numbers that are multiples of both three and five, it prints "FizzBuzz".

for i in range(1, 101): if i % 3 == 0 and i % 5 == 0: print("FizzBuzz") elif i % 3 == 0: print("Fizz") elif i % 5 == 0: print("Buzz") else: print(i)

Write a program that simulates collecting unique cards in candy wrappers.

import random def collect(total_cards): cards_collected = set() candies = 0 while len(cards_collected) < total_cards: card = random.randint(0, total_cards - 1) cards_collected.add(card) candies += 1 return candies total_cards = 35 trials = 1000000 total_candies = sum(collect(total_cards) for _ in range(trials)) print("Average candies needed:", total_candies / trials)

Write a program to roll a six-sided die 100 million times and calculate the probability of getting a 6

import random rolls = 100000000 six_count = sum(1 for _ in range(rolls) if random.randint(1, 6) == 6) probability = six_count / rolls print(f"Probability of getting a 6: {probability}")

What purpose does the main() function serve in Python, and how is it typically called?

main() serves as an entry point for the program's main logic. It's typically called with if __name__ == "__main__": main() to ensure it only runs when the script is executed directly.

Write an equivalent Python expression for max = (a > b) ? a : b.

max_value = a if a > b else b

Provide an example of a while-loop and a for-loop in Python.

while x < 5: x += 1 for i in range(5): print(i)


Kaugnay na mga set ng pag-aaral

Chapter 20- Niche and Mass marketing.

View Set

Foundations of Project Management

View Set

Physical Science Review-- Chapter 23

View Set

05 - LINKED LIST & 07 - Linked stack & 08 - Linked Queue

View Set

Palabras con diptongos ai (ay), ei (ey), iu, oi (oy), ui (uy)

View Set