1. Python Beginner (3h) Flashcards

1
Q

Explain this code (Ticketing app):

SERVICE_CHARGE = 2
TICKET_PRICE = 10
tickets_remaining = 100

def calculate_price(number_of_tickets):
    # create a new constant for a the 2 dollar service charge
    # add the servicce charge to our result
    return (number_of_tickets * TICKET_PRICE) + SERVICE_CHARGE

while tickets_remaining > 0:
    print("There are {} tickets remaining.".format(tickets_remaining))
    name = input("Hi, what's your name? ")
    try: 
        tickets_order_no = int(input("Hi {}, how many tickets do you want? ".format(name)))
        if tickets_order_no > tickets_remaining:
            raise ValueError("There are only {} tickets remaining.".format(tickets_remaining))
    except ValueError as err:
        print("{} Enter a valid number...".format(err))
    else:
        total_price = calculate_price(tickets_order_no)
        print("The total cost for {} tickets is ${}".format(tickets_order_no, total_price))
        proceed = input("Do you want to proceed with the purchase of {} tickets for price of ${}? Reply with Y/N... ".format(tickets_order_no, total_price))
        if proceed.lower() == "y":
            print("Thank you {}! {} Tickets are sold to you for ${}".format(name, tickets_order_no, total_price))
            tickets_remaining -= tickets_order_no
        else:
            print("Thank you {}!".format(name))
            # Update the tickets_remaining variable here
            continue
else:
    print("Sorry! The tickets are all sold-out!")
A

This code is a simple ticket-selling program that allows users to purchase tickets until they are sold out.

The program starts by defining some constants: SERVICE_CHARGE which is set to 2, TICKET_PRICE which is set to 10, and tickets_remaining which is set to 100.

The program then defines a function called calculate_price which takes in a parameter number_of_tickets, multiplies it by TICKET_PRICE, adds SERVICE_CHARGE to the result, and returns the final total price.

Next, the program enters a while loop that continues to run as long as there are tickets_remaining. Inside the loop, the program prints the current number of tickets_remaining and prompts the user for their name and the number of tickets they want to purchase. If the user enters a value for tickets_order_no that is greater than tickets_remaining, the program raises a ValueError with an appropriate message.

If the user enters a valid tickets_order_no, the program calculates the total price using the calculate_price function and prints it to the console. It then prompts the user to confirm their purchase by typing “y” or “n”. If the user types “y”, the program subtracts the number of tickets sold from tickets_remaining and prints a confirmation message to the console. If the user types “n”, the program prints a thank you message to the console and continues to the next iteration of the loop.

If the while loop exits because tickets_remaining is zero, the program prints a message to the console indicating that all tickets have been sold out.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Considering the following code:

def add(first_number, second_number):
    return first_number + second_number

result = add(4, 5)

What term can be used to best define 4 and 5 in the function call line?

A

In the above code, first_number and second_number are referred to as parameters, while 4 and 5 are referred to as arguments.

A parameter is a variable that is declared as part of a function’s definition. It acts as a placeholder for a value that will be passed to the function when it is called. In the add function, first_number and second_number are the parameters, and they specify that the function expects two values to be passed in when it is called.

An argument, on the other hand, is the actual value that is passed to a function when it is called. In the line result = add(4, 5), 4 and 5 are the arguments that are passed to the add function.

So in summary, parameters are defined as part of a function’s definition and act as placeholders for the values that will be passed to the function when it is called. Arguments are the actual values that are passed to the function when it is called.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What does this code will do:
~~~
def cheer(name):
for letter in name:
print(f”Gimme a {letter}!”)
print(“What does that spell?”)
print(f”{name}!”)

user_input = input(“What’s your name? “)
cheer(user_input)
~~~

A

This code defines a function called cheer that takes in one parameter called name. The function loops through each letter in name, prints out a cheer for each letter, and then prints out the entire name in a cheer.

The function starts with a for loop that iterates over each letter in name. For each letter, the function prints out a cheer by using the print statement and an f-string. The f-string contains the letter being cheered for, which is obtained from the letter variable.

After the loop completes, the function prints out a final cheer for the entire name. It does this by using the print statement and another f-string. The f-string contains the entire name parameter being passed to the function.

The code then prompts the user to input their name using the input function and stores the input in a variable called user_input. Finally, the cheer function is called with user_input as the argument. This causes the function to execute with the user’s name, and the cheers for each letter and the full name are printed out to the console.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Command to list all files in console

A

ls

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

how to write hello world in python

A

print("Hello world")

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How to run a python script in console/terminal if python script is saved in file hello.py?

A

python hello.py

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is REPL in Python?

A

REPL stands for Read-Evaluate-Print-Loop. It is an interactive programming environment in which you can enter Python commands and immediately see the results. It is a simple way to quickly experiment with Python code without needing to write a full program.

For example, you can start a Python REPL by typing python in your terminal, and then you will see the prompt&raquo_space;>. You can then enter Python code such as print(“Hello, world!”), and the REPL will immediately execute it and display the output Hello, world!.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How will you see the version of Python you are running in terminal/console?

A

By typing “python” and entering.

python –version

or

python3 –version

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How to open REPL in Terminal?

A

By typing “python” and entering, everything in lower-case as python is case sensitive. And following it up with code you want to run in REPL like&raquo_space;> print(“Hello World”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How will you call for help in Python to learn about a function? Let’s say you want to learn about print function.

A

help(print)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How would you quit/exit REPL?

A

By entering the function called exit: exit()

Or just by pressing q

Or by pressing Ctrl+D

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

unexpected EOF while parsing, what does this error mean?

A

EOF = End of file: a code, marker, or signal used to indicate the end of a file of data is missing

Eg:
~~~
print(“hello world”
~~~
In above example closing parenthesis is missing which could lead to EOF error on line.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What does EOL error mean?

A

EOL is short for “End of Line”. The EOL error signifies that the Interpreter of Python reached the end of the line while scanning the string literal. The string literals, also known as constants, must be enclosed in single or double quotation marks.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Rules of Language in Python is called as?

A

The rules of language in Python are called “syntax”. Syntax refers to the set of rules that dictate how Python code must be written in order for it to be considered valid and executable by the Python interpreter. These rules include guidelines for things like the order of statements, the use of keywords and operators, and the proper formatting of code. Python’s syntax is designed to be easy to read and write, which makes it a popular language for beginners and experienced programmers alike.

Syntax:
* Refers to the set of rules that dictate how code must be written
* Includes things like keywords, punctuation, and structure
* Is specific to a programming language
* Necessary to write code that the computer can understand and execute
* Static and cannot change during the execution of a program
* Determines whether code is valid or not

Function:
* Refers to a block of code that performs a specific task
* Takes input, processes it, and produces output
* Is a general programming concept that can be applied in any language
* Not necessary for a program to run, but often used to make code more efficient and readable
* Dynamic and can change during the execution of a program
* Used to make code more modular and reusable

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What are object, variables, string, classes, attributes, methods mean in Python?

A

In Python, these are the basic concepts related to Object-Oriented Programming:

  1. Object: An object is an instance of a class, which is a user-defined blueprint for creating objects. An object can contain data (attributes) and functions (methods).
  2. Variables: A variable is a name that refers to a value. In Python, variables can be assigned different data types such as integers, floats, booleans, and strings.
  3. Strings: A string is a sequence of characters. In Python, strings are represented using quotes, either single quotes or double quotes.
  4. Classes: A class is a user-defined blueprint or a template for creating objects. It defines a set of attributes and methods that the objects of that class will have.
  5. Attributes: An attribute is a piece of data that belongs to an object. Attributes can be assigned values when the object is created or later in the program.
  6. Methods: A method is a function that belongs to an object. Methods can be used to modify the object’s attributes or perform other tasks related to the object.

Here’s an example to demonstrate these concepts:
~~~
# Defining a class
class Person:
# Defining attributes
def __init__(self, name, age):
self.name = name
self.age = age

# Defining a method
def greet(self):
    print(f"Hello, my name is {self.name} and I am {self.age} years old.")

Creating an object
person1 = Person(“John”, 30)

Accessing attributes
print(person1.name) # Output: John
print(person1.age) # Output: 30

Calling a method
person1.greet() # Output: Hello, my name is John and I am 30 years old.
~~~

In the example above, we defined a class Person with attributes name and age, and a method greet. We then created an object person1 from that class and accessed its attributes and called its method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

first_name = "Ada"

Which is variable and string here?

A

In the Python code first_name = “Ada”, first_name is a variable and “Ada” is a string.

The variable first_name is a named storage location in memory that holds a reference to the string “Ada”. You can use the variable name first_name to access the string value “Ada” in your program.

The string “Ada” is a sequence of characters that represents text and is enclosed in double quotes. In Python, strings can be created using either single quotes or double quotes, but they must start and end with the same type of quote.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q
first_name = "ada"
print("hello!", first_name)
print(first_name, "is the first", "programmer")

What output will this give?

A

The output of the given Python code would be:

hello! ada 
ada is the first programmer

Here is a breakdown of what each line of the code does:
* first_name = "ada" assigns the string value “ada” to the variable first_name.
* print("hello!", first_name) prints the string “hello!” followed by the value of the variable first_name, which is “ada”.
* print(first_name, “is the first”, “programmer”) prints the value of the variable first_name, followed by the strings “is the first” and “programmer”, separated by spaces as comma indicates space. The output of this line is”ada is the first programmer”.
* So the complete output is “hello! ada” followed by “ada is the first programmer”.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

How will you create a varible where users can enter there own input?

A
current_mood=input("how are you feeling now?")

The line of Python code current_mood = input("how are you feeling now?") prompts the user to input a response to the question “how are you feeling now?” and assigns the user’s input to the variable current_mood.

When this line of code is executed, the program will pause and wait for the user to enter some text. The text that the user enters will be stored as a string in the variable current_mood.

For example, if the user types “happy” and presses Enter, the variable current_mood will be assigned the value “happy”. You can then use the value of current_mood in your program to perform different actions depending on the user’s response.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Use snake_case for variables means?

A

Assigning values to variables using snake_case

Using snake_case for variables means that variable names are written in all lowercase letters, with words separated by underscores. For example, first_name, last_name, user_id, and age_group are all examples of variables written in snake_case.

Using snake_case is a common convention in Python programming. It makes variable names easier to read and understand, as well as making the code more consistent and readable. It’s important to note that Python is a case-sensitive language, so first_name and FirstName are considered to be different variables.

Here’s an example of using snake_case for variable names in Python:
~~~
first_name = “John”
last_name = “Doe”
user_id = 12345
age_group = “30-40”

Printing the values of the variables
print(first_name)
print(last_name)
print(user_id)
print(age_group)
~~~

In the example above, we assign values to four variables using snake_case and then print their values. Using snake_case makes the variable names easy to read and understand, and helps to make the code more consistent and maintainable.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

what is camelCase and PascalCase?

A

CamelCase and PascalCase are naming conventions for compound words in programming languages. They differ from snake_case in that they use capitalization instead of underscores to separate words.

Here’s a brief description of each:

CamelCase: In CamelCase, the first word is lowercase and each subsequent word is capitalized. For example, firstName, lastName, and phoneNumber are all examples of variables that use CamelCase.

PascalCase: In PascalCase, the first letter of each word is capitalized. For example, FirstName, LastName, and PhoneNumber are all examples of variables that use PascalCase.

Both CamelCase and PascalCase are commonly used in programming languages like Java and C#. In Python, snake_caseis the convention that is most commonly used for variable names.

It’s important to note that while using CamelCase or PascalCase can make variable names easier to read, they can also be harder to type and more prone to typos than snake_case. In general, it’s a good idea to follow the naming conventions used in the language or framework you’re working with to make your code more consistent and easier to understand for other developers.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What are whole numbers and what are integers?

A

Whole numbers are a set of numbers that includes all positive integers (1, 2, 3, …), as well as zero (0). These numbers are used to count objects or represent quantities that cannot be divided into smaller parts.

Integers, on the other hand, are a set of numbers that includes all whole numbers, their negative counterparts (e.g., -1, -2, -3, …), and zero (0). Integers are used to represent both positive and negative quantities, such as gains and losses, debts and credits, or elevations above and below sea level.

In summary, every integer is a whole number, but not every whole number is an integer.

Whole numbers are called “whole” because they are the set of numbers that represent complete, undivided quantities or objects. They do not include any fractional or decimal parts. For example, if you have three apples, you have a whole number of apples, but if you have 3.5 apples, you have a fraction or decimal, which is not a whole number.

Integers, on the other hand, are called “integer” because the word comes from the Latin word “integer” which means “whole” or “untouched”. Integers represent whole numbers without any fractions or decimals, and they also include their negative counterparts. For example, the integer 5 represents the whole, untouched quantity of five, and the integer -3 represents the untouched negative quantity of three.

So both “whole” and “integer” have meanings related to representing undivided, complete quantities or numbers without any fractional or decimal parts.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What is floating point or float?

A

A floating point number is a type of numerical data that represents a real number with a fractional part. Unlike integers, which can represent only whole numbers, floating point numbers can represent numbers with decimal points or fractions.

Here are some examples of floating point numbers:
* 3.14159: This is a floating point number that represents the mathematical constant pi, which has a decimal value that continues infinitely.
* 2.5: This is a floating point number that represents the value halfway between the whole numbers 2 and 3.
* 0.0001: This is a very small floating point number that represents a small fraction of a larger value, such as a financial transaction or scientific measurement.
* -8.75: This is a negative floating point number that represents a quantity that is less than negative 8 but greater than negative 9.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

what does _ represent in REPL?

A

In a REPL (Read-Eval-Print Loop) environment, the underscore character ('_') is typically used to represent the result of the previous evaluation or computation. When you enter a command or expression into the REPL, the system will evaluate it and return a result. The underscore character can then be used to reference that result in subsequent commands or expressions.

For example, if you entered the command “2 + 2” into a Python REPL, the system would evaluate it and return the result “4”. You could then use the underscore character to reference that result in another command, such as ` “print(_)”` , which would output “4” to the console.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

When you use arithmetic in REPL for 0.1+0.1+0.1-0.3, the answer returns 5.551115123125783e-17 and not 0. Why? How can you fix it?

A

The reason why the expression “0.1+0.1+0.1-0.3” does not result in exactly 0, but instead produces a value of “5.551115123125783e-17” (which is very close to 0, but not exactly 0), is due to the limitations of floating-point arithmetic.

In many programming languages, including Python, floating-point numbers are represented in binary format using a fixed number of bits. However, not all decimal numbers can be represented exactly in binary format, which can lead to small errors or rounding issues when performing calculations with floating-point numbers.

In the case of the expression “0.1+0.1+0.1-0.3”, the result should mathematically be exactly 0. However, when this calculation is performed using floating-point arithmetic, the intermediate results are subject to rounding errors and precision limitations, which can result in a very small residual value that is not exactly 0.

This is why the result of the expression is given as “5.551115123125783e-17” (which represents a very small number, equivalent to 0.00000000000000005551115123125783), instead of exactly 0. It is important to keep in mind that while floating-point arithmetic is very useful and widely used, it is subject to certain limitations and can produce small errors or rounding issues in some cases.

By using “round()” function we can fix it.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

what does CTRL+L do in REPL in terminal?

A

In a REPL (Read-Eval-Print Loop) environment running in a terminal, pressing the CTRL+L key combination typically clears the screen and resets the console output. This can be useful for clearing previous commands or results and starting with a fresh console.

The CTRL+L key combination is a common keyboard shortcut for the “clear” or “clear screen” command in many terminal applications, including REPL environments like Python, Ruby, and Node.js. When you press CTRL+L, the terminal emulator sends a special control sequence to the shell or REPL process running in the terminal, which instructs it to clear the screen and reset the console.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

What does PEMDAS mean? What is the acronym/mnemonics expansion for PEMDAS?

A

PEMDAS = Please Excuse My Dear Aunt Sally

PEMDAS = Parentheses, Exponents, Multiplication and Division (from left to right)

When evaluating an arithmetic expression with multiple operators and operands, it is important to follow the order of operations to ensure that the expression is evaluated correctly. PEMDAS provides a mnemonic for remembering the correct order of operations:

  • Parentheses: Evaluate expressions inside parentheses first, starting from the innermost pair and working outward.
  • Exponents: Evaluate expressions with exponents or roots next, from left to right.
  • Multiplication and Division: Evaluate multiplication and division operations from left to right.
  • Addition and Subtraction: Evaluate addition and subtraction operations from left to right.

By following the order of operations in this way, you can ensure that arithmetic expressions are evaluated consistently and accurately. It is important to note that in some cases, parentheses may be used to override the normal order of operations and specify a different order for evaluating the expression.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

How will use PEMDAS on this equation: 5 + 6 * (7 - 3) / 2^2 ?

A

Here’s an example of how to use PEMDAS to evaluate an arithmetic expression:

Given the expression: 5 + 6 * (7 - 3) / 2^2

Using PEMDAS, we can evaluate this expression as follows:

  • Parentheses: Evaluate the expression inside the parentheses first: 7 - 3 = 4
  • Exponents: Evaluate any exponents next, from left to right: 2^2 = 4
  • Multiplication and Division: Evaluate any multiplication and division operations next, from left to right: 6 * 4 = 24 24 / 4 = 6
  • Addition and Subtraction: Evaluate any addition and subtraction operations next, from left to right: 5 + 6 = 11

Therefore, the final result of the expression is 11.

By following the order of operations specified by PEMDAS, we ensure that each operation is performed in the correct order, resulting in the correct final result.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

Difference between BODMAS and PEMDAS? And how can this equation be solved with both methods: 4 + 5 * (8 / 2) - 3^2 + 6 / 2 ?

A

BODMAS and PEMDAS are similar and related concepts, but they are not exactly the same.

BODMAS stands for Brackets, Orders (exponents and roots), Division and Multiplication (from left to right), and Addition and Subtraction (from left to right). This means that in an arithmetic expression, you should first evaluate expressions inside brackets, then expressions with exponents or roots, then perform any division and multiplication operations from left to right, and finally perform any addition and subtraction operations from left to right.

PEMDAS, on the other hand, stands for Parentheses, Exponents, Multiplication and Division (from left to right), and Addition and Subtraction (from left to right). This means that in an arithmetic expression, you should first evaluate expressions inside parentheses, then expressions with exponents, then perform any multiplication and division operations from left to right, and finally perform any addition and subtraction operations from left to right.

The key difference between BODMAS and PEMDAS is the order of the “O” (Orders) and “P” (Parentheses) operations. BODMAS considers expressions inside brackets first, while PEMDAS considers expressions inside parentheses first. However, both methods agree on the order of the other operations.

While BODMAS and PEMDAS may be used interchangeably in many cases, it is important to understand the specific order of operations being used in any given arithmetic expression to ensure accurate evaluation.

Here’s an example equation that can be solved using both BODMAS and PEMDAS:

Given the expression: 4 + 5 * (8 / 2) - 3^2 + 6 / 2

Using BODMAS, we can evaluate this expression as follows:

  • Brackets: Evaluate the expression inside the brackets first: 8 / 2 = 4 5 * 4 = 20
  • Orders: Evaluate any expressions with exponents or roots next, from left to right: 3^2 = 9
  • Division and Multiplication: Evaluate any division and multiplication operations from left to right: 6 / 2 = 3
  • Addition and Subtraction: Evaluate any addition and subtraction operations from left to right: 4 + 20 - 9 + 3 = 18

Therefore, the final result of the expression using BODMAS is 18.

Using PEMDAS, we can evaluate the same expression in a different order:

  • Exponents: Evaluate any exponents or roots first, from left to right: 3^2 = 9
  • Parentheses: Evaluate the expression inside the parentheses next: 8 / 2 = 4 5 * 4 = 20
  • Multiplication and Division: Evaluate any multiplication and division operations from left to right: 6 / 2 = 3
  • Addition and Subtraction: Evaluate any addition and subtraction operations from left to right: 4 + 20 - 9 + 3 = 18

Therefore, the final result of the expression using PEMDAS is also 18.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

What Arithmetic method does the Python use? Give example.

A

Python, like most programming languages, follows the PEMDAS order of operations when evaluating arithmetic expressions. This means that in Python, expressions inside parentheses are evaluated first, followed by exponents, multiplication and division (from left to right), and finally addition and subtraction (from left to right).

For example, consider the following expression in Python:

result = 2 + 3 * 4 ** 2 - 1 / 2

In this expression, the exponent operator (**) is evaluated first, followed by multiplication and division, and finally addition and subtraction. The parentheses are not needed in this case because the operator precedence is already well-defined by the PEMDAS order of operations.

It’s important to note that while Python follows the PEMDAS order of operations, it also allows you to use parentheses to override the normal order of operations and specify a different order for evaluating an expression. This can be useful in complex expressions where the order of operations may not be immediately clear or in cases where you want to ensure a specific order of evaluation.

30
Q

What output will functions int(11) and float(11) will give? And what does int() and float() functions mean?

A

The int(11) function will return the integer value 11, while the float(11) function will return the floating-point value 11.0.

The int() function in Python is used to convert a value to an integer. If the value is already an integer, the function simply returns the same value. If the value is a float, it will be rounded down to the nearest integer. If the value is a string, it will be converted to an integer if possible. For example:

print(int(11.8))    # Output: 11
print(int("42"))    # Output: 42

The float() function in Python is used to convert a value to a floating-point number. If the value is already a float, the function simply returns the same value. If the value is an integer, it will be converted to a float. If the value is a string, it will be converted to a float if possible. For example:

print(float(11))    # Output: 11.0
print(float("3.14"))    # Output: 3.14

In summary, the int() function is used to convert a value to an integer, while the float() function is used to convert a value to a floating-point number. The output of int(11) is the integer value 11, while the output of float(11) is the floating-point value 11.0.

31
Q

What is the difference between this arithmetic in Python: 23 / 3 and 23 // 3 and what output will each give?

A

In Python, the arithmetic operator / performs division and returns the result as a floating-point number, while the // operator performs integer division and returns the result as an integer.

For example, 23 / 3 will return the floating-point value 7.666666666666667, while 23 // 3 will return the integer value 7.

Here’s an example to demonstrate the difference between the two operators:
~~~
# Using the / operator for division
result1 = 23 / 3
print(result1) # Output: 7.666666666666667

Using the // operator for integer division
result2 = 23 // 3
print(result2) # Output: 7
~~~

In the example above, we perform division using both the / and // operators. The output of 23 / 3 is a floating-point number with a value of 7.666666666666667, while the output of 23 // 3 is an integer with a value of 7.

In summary, the difference between 23 / 3 and 23 // 3 in Python is that the former performs division and returns a floating-point number, while the latter performs integer division and returns an integer.

32
Q

what does 23%3 arithmetic do in python? what it means?

A

In Python, the % operator is used to perform the modulus operation, which returns the remainder of a division operation.

So, 23 % 3 in Python would evaluate to 2, because 23 divided by 3 gives a quotient of 7 with a remainder of 2. In other words, the modulus operation calculates the remainder when 23 is divided by 3.

Here’s an example:
~~~
x = 23 % 3 print(x) # Output: 2
~~~

In this example, x is assigned the value of the remainder when 23 is divided by 3 using the modulus operator, and the print() function is used to output the value of x to the console.

33
Q

what is TypeError in python?

A

In Python, TypeError is a built-in exception that is raised when an operation or function is applied to an object of inappropriate type. This means that the data type of an object is not compatible with the operation or function that is trying to be executed.

For example, if you try to perform arithmetic operations on objects that are not numbers (such as strings or lists), a TypeError will be raised. Similarly, if you try to call a method on an object that doesn’t have that method, a TypeError will be raised.

Here’s an example of a TypeError being raised when trying to add a string and an integer:
~~~
a = “hello”
b = 123
c = a + b # This line will raise a TypeError
~~~

In this case, a TypeError will be raised because you cannot concatenate a string and an integer directly. To fix this, you would need to convert the integer to a string before concatenating:

a = "hello"
b = 123
c = a + str(b) # This line will not raise a TypeError

In general, when you encounter a TypeError in your Python code, you should check the data types of the objects involved in the operation or function call and make sure they are compatible.

34
Q

age=29, what data type is the age variable? 1.int, 2.string, 3.float

A

integer, int

35
Q

what is the use of \ (backslash) in string in python? Give examples of how to escape special characters in a string.

A

In Python, the backslash character () is used to escape special characters in a string. This means that when the backslash is followed by certain characters, it changes the meaning of the character to something else.

Here are some examples of how to use the backslash to escape special characters in a string:

    1. To include a single quote or double quote inside a string that is delimited by the same type of quote, you can use the backslash to escape the quote character. For example:
      ~~~
      string1 = ‘He said, “I'm going to the store.”’
      string2 = “She said, ‘He\’s not here.’”
      ~~~
      In the first example, the backslash is used to escape the single quote inside the string that is delimited by single quotes. In the second example, the backslash is used to escape the single quote inside the string that is delimited by double quotes.
    1. To include a backslash character itself inside a string, you need to use two backslashes in a row. For example:
      ~~~
      string3 = “C:\Program Files\Python\”
      ~~~
      In this example, the double backslashes are used to include a single backslash character inside the string.
    1. To include special characters like newline (\n), tab (\t), or carriage return (\r) inside a string, you can use the backslash to escape these characters. For example:
      ~~~
      string4 = “First line\nSecond line”
      string5 = “Name:\tJohn Smith\nAge:\t25”
      string6 = “Hello\rWorld”
      ~~~

In the first example, the \n character is used to insert a new line between the two lines of text. In the second example, the \t character is used to insert a tab between the label and the value. In the third example, the \r character is used to return the cursor to the beginning of the line.

In summary, the backslash character () is used to escape special characters in a string in Python. It allows you to include characters that would otherwise be interpreted as part of the string syntax.

string1 = 'He said, "I\'m going to the store."'
string2 = "She said, 'He\\'s not here.'"
print(string1)  # Output: He said, "I'm going to the store."
print(string2)  # Output: She said, 'He's not here.'
36
Q

Adding new line within a string using \, how would you do it?

A

To add a new line within a string using the backslash () in Python, you can use the escape sequence \n. The \n sequence represents a newline character, which tells Python to start a new line when the string is printed.

Here’s an example of how to use \n to add a new line within a string:
~~~
message = “Hello,\nWorld!”
print(message)
~~~

In this example, the \n sequence is used to add a new line between “Hello,” and “World!” in the string message. When the string is printed, it will be displayed as:
~~~
Hello,
World!
~~~

37
Q

what does triple quote “”” do in a string in python?

A

In Python, triple quotes (“””) are used to create multi-line strings. A multi-line string is a string that spans across multiple lines of code, and can contain line breaks, tabs, and other special characters without the need for escape sequences.

Here’s an example of how to create a multi-line string using triple quotes:
~~~
message = “"”Hello,
World!”””
print(message)
~~~

In this example, the string message is created using triple quotes, and includes a line break between “Hello,” and “World!”. When the string is printed, it will be displayed as:
~~~
Hello,
World!
~~~

38
Q

What is immutable in Python mean? Give 3 examples of immutable objects in Python.

A

The following operations will raise a TypeError:

In Python, an object that is immutable cannot be changed after it is created. This means that any attempt to modify the object will result in the creation of a new object with the modified value, rather than changing the original object in place.

Immutable objects are useful for situations where you need to ensure that the value of an object cannot be accidentally or maliciously changed.

Here are three examples of immutable objects in Python:

    1. Integers: Integers are immutable in Python, which means that you cannot change their value after they are created. For example:
      ~~~
      x = 5
      y = x + 2 # This creates a new integer object with the value 7
      print(x) # Output: 5
      print(y) # Output: 7
      ~~~
    1. Tuples: Tuples are also immutable in Python. Once a tuple is created, you cannot change its elements or add or remove elements. For example:
      ~~~
      t = (1, 2, 3)
      t[0] = 4
      t.append(4)
      t.remove(2)
      ~~~
    1. Strings: Strings are another example of an immutable object in Python. Once a string is created, you cannot change its characters. For example:
      ~~~
      s = “hello”
      # The following operations will raise a TypeError:
      s[0] = “H”
      s.append(“!”)
      s.replace(“e”, “E”)
      ~~~

In general, immutable objects are any objects in Python that cannot be changed after they are created. In addition to integers, tuples, and strings, some other examples of immutable objects in Python include frozensets, booleans, and None.

39
Q

In the following which is variable and which is string ?
my_string = "Hello, world!"

A

In the statement my_string = "Hello, world!", my_string is the variable and "Hello, world!" is the string literal.

In Python, a variable is a named reference to a value that is stored in memory. In this case, my_string is the variable that is being assigned the value of the string literal “Hello, world!”.

A string literal is a sequence of characters enclosed in quotation marks (“ or ‘). In this case, “Hello, world!” is a string literal that represents the text “Hello, world!”. When the program runs, this string literal is evaluated and a string object is created in memory that contains the same characters as the string literal. This string object is then assigned to the my_string variable, so that my_string now refers to the string object in memory.

It’s worth noting that in Python, variables do not have a specific data type associated with them. Instead, variables are dynamically typed and can refer to objects of any type (such as strings, numbers, lists, etc.). In this case, my_string is initially assigned a string object, so it is considered a string variable. However, you could later assign a different type of object to my_string, and it would become a variable of that type instead.

40
Q

What is the use of len() function?

A

In Python, the len() function is used to get the length or size of a sequence, such as a string, list, tuple, or set. It returns the number of elements in the sequence.

Here’s an example of how to use the len() function to get the length of a string:
~~~
text = “Hello, World!”
length = len(text)
print(length)
~~~

In this example, the len() function is used to get the length of the string text. The value returned by len() is then assigned to the variable length. Finally, the length of the string is printed to the console, which outputs: 13.

41
Q
variable_one = "string literal"

now how will you change variable_one into all upper case letter using method? and also what method will use for lower casing?

A

In Python, the .upper() method is a built-in string method that returns a new string with all the characters converted to uppercase. The original string is not modified, and the new string is returned as the result of the method call.

To change the value of variable_one to all uppercase letters, you can use the upper() method in Python. This method returns a new string with all the characters converted to uppercase:

variable_one = "string literal"
variable_one = variable_one.upper()
print(variable_one)  # Output: STRING LITERAL

In this example, the upper() method is called on the variable_one string, which returns a new string with all the characters in uppercase. The new string is then assigned back to the variable_one variable.

42
Q

explain .format in python?

A

In Python, the .format() method is used to format a string by replacing placeholders with values. It allows you to construct a string that includes variable parts, such as numbers, strings, and other data types.

Here’s an example of how to use the .format() method in Python:
~~~
name = “John”
age = 30
message = “My name is {} and I’m {} years old.”.format(name, age)
print(message)
~~~

In this example, the .format() method is called on the string “My name is {} and I’m {} years old.”. The curly braces {} are used as placeholders for the variables name and age. The variables are then passed as arguments to the .format() method, in the order they should appear in the string. Finally, the formatted string is assigned to the message variable and printed to the console:

My name is John and I'm 30 years old.
43
Q

what does all this: .upper(), .lower(), .title(), .capitalize(), .str(), help(str) mean in python?

A

In Python, these are string methods that can be used to manipulate strings. Here’s what each of these methods does:

  1. .upper(): This method returns a new string with all the characters in uppercase.
  2. .lower(): This method returns a new string with all the characters in lowercase.
  3. .title(): This method returns a new string with the first character of each word in uppercase and the rest in lowercase.
  4. .capitalize(): This method returns a new string with the first character in uppercase and the rest in lowercase.
  5. .str(): A built-in function that returns a string representation of an object. For example: str(123) returns the string “123”.
  6. .help(str): A built-in function that displays the documentation for the string class, including a list of all the string methods available and their usage. It provides useful information about the built-in string methods and how they can be used in Python.

All of these tools are related to working with strings in Python. The .upper(), .lower(), .title(), and .capitalize() methods are used to modify the case of the letters in a string, while the str() function is used to convert non-string objects to strings. The help(str) function provides a way to access the documentation for the string class and learn more about how to use these and other string-related functions in Python.

44
Q

what does ‘method’ mean in python? what is the difference between method and function?

A

In Python, a method is a function that is associated with an object. A method is accessed using dot notation and is called on an instance of a class. Methods typically act on the data stored in an object and can modify that data or return information about it.

Eg. string.method()
introduce = "Hello World"
introduce.upper()

Here .upper() is the method.

A function, on the other hand, is a standalone block of code that performs a specific task. Functions can be defined outside of a class and can be called by passing arguments to them. Functions can also return values, modify input arguments, or have side effects such as printing to the console.

Eg: function(string)
introduce = "Hello World"
print(introduce)
Here print is the function

The main difference between a method and a function is the way they are called and the context in which they are used. A method is called on an instance of a class and can access and modify the data stored in that object. A function, on the other hand, is standalone and is not associated with any particular object. It operates on the data passed as arguments to it and returns a value or modifies the input data.

45
Q

What is boolean?

A

Assigning Boolean values to variables

In programming, a Boolean is a data type that represents one of two possible values: True or False. Boolean values are often used in conditional statements and logical operations, where they help determine whether a particular condition is true or false.

In Python, the bool class is used to represent Boolean values. The values True and False are reserved keywords in Python and represent the two Boolean values.

Here are some examples of how to use Boolean values in Python:
~~~
is_raining = True
is_sunny = False

Using Boolean values in conditional statements
if is_raining:
print(“Remember to bring an umbrella”)

if not is_sunny:
print(“It’s not sunny today”)

Combining Boolean values with logical operators
if is_raining and not is_sunny:
print(“It’s raining but not sunny”)

if is_raining or is_sunny:
print(“It’s either raining or sunny”)
~~~

In these examples, the Boolean values True and False are used to control the flow of the program based on certain conditions. The if statement checks whether the given Boolean expression is true, and executes the code inside the block if it is. The logical operators and and or are used to combine Boolean values together to form more complex conditions.

In summary, a Boolean is a data type that represents one of two possible values: True or False. In Python, Boolean values are often used in conditional statements and logical operations to help control the flow of the program based on certain conditions.

46
Q

what does bool(1) and bool(0) do in python code?

A

In Python, the bool() function is used to convert a value into a Boolean (either True or False) based on its truthiness.

When you call bool(1), it converts the integer value 1 into a Boolean. In Python, any non-zero value is considered “truthy,” meaning it evaluates to True. Therefore, bool(1) would return True.

Similarly, when you call bool(0), it converts the integer value 0 into a Boolean. In Python, 0 is considered “falsy,” meaning it evaluates to False. Therefore, bool(0) would return False.

Here are a few examples to illustrate this:
~~~
print(bool(1)) # Output: True
print(bool(0)) # Output: False
~~~

In these examples, bool(1) evaluates to True because 1 is a non-zero value, and bool(0) evaluates to False because 0 is considered falsy.

47
Q

(False or False or True) and (True and False) what will this return in python?

A

The expression (False or False or True) and (True and False) will return False in Python.

To understand why, let’s break it down step by step:

  1. (False or False or True) evaluates to True because it uses the or operator, which returns True if at least one of the operands is True. In this case, True is encountered as the last operand, so the expression as a whole evaluates to True.
  2. (True and False) evaluates to False because it uses the and operator, which returns False if any of the operands is False. In this case, the first operand is True, but the second operand is False, so the expression as a whole evaluates to False.
  3. Finally, the whole expression True and False is evaluated as False because it uses the and operator, and one of its operands is False.

Therefore, (False or False or True) and (True and False) evaluates to False.

48
Q

Explain this Python Code:
~~~
first_name=input(“What is your first-name? “)
print(“Hello!”, first_name)
if first_name==”Sethu”:
print(first_name, “is learning coding”)
elif first_name==”Mickey”:
print(first_name, “is learning Python with everyone”)
else:
print(“You should definitely be learning {}, {}!”.format(“Python”, first_name))
print(“Have a great day! {}”.format(first_name))
~~~

A

This code is a simple program that greets the user and provides a personalized message based on the user’s input. Here’s what each line does:

  1. first_name=input("What is your first-name? "): This line prompts the user to enter their first name and stores the input in the first_name variable.
  2. print("Hello!", first_name): This line greets the user by printing the string “Hello!” followed by the value of first_name.
  3. if first_name=="Sethu":: This line starts an if statement that checks if the user’s first name is equal to the string “Sethu”.
  4. print(first_name, "is learning coding"): If the user’s first name is “Sethu”, this line prints the string “Sethu is learning coding” to the console.
  5. elif first_name=="Mickey":: If the user’s first name is not “Sethu”, this line starts an elif statement that checks if the user’s first name is equal to the string “Mickey”.
  6. print(first_name, "is learning Python with everyone"): If the user’s first name is “Mickey”, this line prints the string “Mickey is learning Python with everyone” to the console.
  7. else:: If the user’s first name is neither “Sethu” nor “Mickey”, this line starts an else statement.
  8. print("You should definitely be learning {}, {}!".format("Python", first_name)): This line prints the string “You should definitely be learning Python, followed by the value of first_name, to the console.
  9. print("Have a great day! {}".format(first_name)): This line prints the string “Have a great day!” followed by the value of first_name to the console.

Overall, this program asks the user for their first name, greets them, and provides a personalized message based on their name. If the user’s name is “Sethu”, the program tells them they are learning coding. If the user’s name is “Mickey”, the program tells them they are learning Python with everyone. For all other names, the program recommends learning Python.

49
Q

List down all the operators of Python and operators that can be used on boolean and if statements?

A

Sure! Here’s a list of all the operators in Python:

1. Arithmetic Operators: +, -, *, /, // (integer division), % (modulo)
2. Comparison Operators: ==, !=, >, <, >=, <=
3. Logical Operators: and, or, not
4. Bitwise Operators: & (and), | (or), ^ (xor), ~ (not), << (left shift), >> (right shift)
5. Assignment Operators: =, +=, -= , *= , /= , %= , //= , **=, &= , |= , ^= , >>= , <<=
6. Identity Operators: is, is not
7. Membership Operators: in, not in

Operators that can be used on boolean and if statements include:

1.Boolean Operators: and, or, not
2.Comparison Operators: ==, !=, >, <, >=, <=
3.Identity Operators: is, is not
4.Membership Operators: in, not in

These operators can be used to create complex boolean expressions and conditions in if statements to control the flow of program execution.

50
Q

How will you write a code that gives output:

What is your first-name? Hermione (input)
Hello! Hermione
How old are you? 5 (input)
Wow you are 5! If you are conifdent with reading then….
You should definitely be learning Python, Hermione! Have a great day! Hermione

Few conditions, if name is Sethu, disaply “Sethu is learning coding”, if name is Mickey display that “Mickey is learning Python with everyone”, if age < 6 display “If you are confident with reading…”.

A
first_name = input("What is your first name? ")
print("Hello!", first_name)

if first_name == "Sethu":
    print(first_name, "is learning coding")
elif first_name == "Mickey":
    print(first_name, "is learning Python with everyone")
else:
    # This is a comment, just in case if we have a younger user who can't yet read
    age = int(input("How old are you? "))
    if age <= 6:
        print("Wow, you are {}! If you are confident with reading then....".format(age))
    print("You should definitely be learning {}, {}!".format("Python", first_name))

print("Have a great day! {}".format(first_name))
51
Q

Explain this code:
~~~
first_name = input(“What is your first name? “)
print(“Hello!”, first_name)

if first_name == “Sethu”:
print(first_name, “is learning coding”)
elif first_name == “Mickey”:
print(first_name, “is learning Python with everyone”)
else:
# This is a comment, just in case we have a younger user who can’t yet read
age = int(input(“How old are you? “))
if age <= 6:
print(“Wow, you are {}! If you are confident with reading then….”.format(age))
print(“You should definitely be learning {}, {}!”.format(“Python”, first_name))

print(“Have a great day! {}”.format(first_name))
~~~

A

Certainly! This is a Python program that prompts the user to enter their first name, greets them, and provides a personalized message based on their name. Here’s a breakdown of how the code works:

  1. first_name=input("What is your first-name? "): This line prompts the user to enter their first name and stores the input in the first_name variable.
  2. print("Hello!", first_name): This line greets the user by printing the string “Hello!” followed by the value of first_name.
  3. if first_name=="Sethu":: This line starts an if statement that checks if the user’s first name is equal to the string “Sethu”.
  4. print(first_name, "is learning coding"): If the user’s first name is “Sethu”, this line prints the string “Sethu is learning coding” to the console.
  5. elif first_name=="Mickey":: If the user’s first name is not “Sethu”, this line starts an elif statement that checks if the user’s first name is equal to the string “Mickey”.
  6. print(first_name, "is learning Python with everyone"): If the user’s first name is “Mickey”, this line prints the string “Mickey is learning Python with everyone” to the console.
  7. else:: If the user’s first name is neither “Sethu” nor “Mickey”, this line starts an else statement.
  8. # This is a comment, just in case if we have younger user who can’t yet read: This line is a comment that explains why the next prompt might appear.
  9. age=int(input("How old are you? ")): This line prompts the user to enter their age as an integer and stores the input in the age variable.
  10. if age <= 6:: If the user’s age is less than or equal to 6, this line starts an if statement.
  11. print("Wow you are {}! If you are confident with reading then....".format(age)): If the user’s age is less than or equal to 6, this line prints a message congratulating the user for their age.
  12. print("You should definitely be learning {}, {}!".format("Python", first_name)): This line prints a message indicating that the user should be learning Python, followed by the value of first_name, to the console.
  13. print("Have a great day! {}".format(first_name)): This line prints the string “Have a great day!” followed by the value of first_name to the console.

In summary, this program prompts the user for their first name, greets them, and provides a personalized message based on their name. If the user’s name is “Sethu”, the program tells them they are learning coding. If the user’s name is “Mickey”, the program tells them they are learning Python with everyone. For all other names, the program prompts the user to enter their age and congratulates them if they are 6 years old or younger. Then, the program recommends learning Python and wishes the user a great day.

52
Q

what does this Python code mean:

if logged_in:
    display_profile_avatar()
else:
    show_signup_and_login_buttons()
A

This Python code contains an if-else statement that checks whether the variable logged_in is True or False. Here’s a breakdown of what the code does:

  1. if logged_in:: This line starts the if statement, which checks if the value of the logged_in variable is True. If the value is True, the code block under the if statement will be executed.
  2. display_profile_avatar(): This line is inside the code block under the if statement. If the logged_in variable is True, the display_profile_avatar() function is called to display the user’s profile avatar.
  3. else:: If the value of the logged_in variable is False, this line starts the else statement.
  4. show_signup_and_login_buttons(): This line is inside the code block under the else statement. If the logged_in variable is False, the show_signup_and_login_buttons() function is called to display the signup and login buttons.

In summary, this code checks whether a user is logged in by checking the value of the logged_in variable. If the user is logged in (logged_in is True), the display_profile_avatar() function is called to show the user’s profile avatar. If the user is not logged in (logged_in is False), the show_signup_and_login_buttons() function is called to display the signup and login buttons. This code could be used to conditionally display different parts of a webpage or application depending on whether a user is logged in or not.

53
Q

In REPL, when “python” > “chocolate” it comes true, why?

A

In Python, the comparison operator > compares two strings based on their lexicographical order. In lexicographical order, strings are compared based on the alphabetical order of their characters, starting from the first character of each string.

In the case of “python” > “chocolate”, the first characters of the two strings are “p” and “c”, respectively. Since “p” comes after “c” in the alphabet, “python” is considered to be greater than “chocolate” in lexicographical order. Therefore, the expression “python” > “chocolate” evaluates to True.

It’s important to note that the comparison operators >, <, >=, and <= have different meanings for strings than they do for numerical values. When comparing strings with these operators, the lexicographical order of the strings is used to determine the result of the comparison.

54
Q

what does // operator mean in python?

A

In Python, the // operator is called the floor division operator. It performs division between two numbers and returns the quotient rounded down to the nearest integer.

Here’s how the // operator works:
If both operands are integers, the result will be an integer. For example:
~~~
result = 7 // 3
print(result) # Output: 2
~~~

If at least one of the operands is a floating-point number, the result will be a floating-point number. For example:
~~~
result = 7.0 // 3
print(result) # Output: 2.0
~~~

The floor division operator always rounds down towards negative infinity, meaning it discards the fractional part of the division result.

It’s worth noting that the floor division operator was introduced in Python 2.2, so it’s available in all subsequent versions of Python, including Python 3.

55
Q

How do you create a function in Python?

A

To create a function in Python, you can use the def keyword followed by the function name, parentheses (), and a colon : to define the function’s signature. The function block is indented below the def statement.

Here’s the general syntax for creating a function in Python:
~~~
def function_name(parameter1, parameter2, …):
# Function body
# Code statements
# Return statement (optional)
~~~

Let’s break down the components:

  • def is the keyword used to define a function in Python.
  • function_name is the name you choose for your function. Make sure it follows the naming conventions (e.g., no spaces, starts with a letter or underscore, etc.).
  • parameter1, parameter2, … are optional parameters that you can specify to pass values into the function. You can have zero or more parameters.
  • : is used to end the function signature and indicate the start of the function body.
  • The function body is indented below the def statement. It consists of the code statements that make up the function’s logic.
  • You can include a return statement to specify the value that the function should return. This is optional, and if omitted, the function will return None by default.

Here’s an example of a simple function that takes two parameters and returns their sum:
~~~
def add_numbers(a, b):
sum = a + b
return sum
~~~

Once you define a function, you can call it by using its name followed by parentheses and passing appropriate arguments. For example:
~~~
result = add_numbers(3, 5)
print(result) # Output: 8
~~~

This will call the add_numbers function with arguments 3 and 5, and the function will return their sum, which is then printed.

56
Q

Explain this python code and how can this be shortened:

praise = “You are doing great!”
praise = praise.upper()
number_of_characters = len(praise)
result = praise + “!” * (number_of_characters // 2)
print(result)

advice = “Don’t forget to ask for Advice!”
advice = advice.upper()
number_of_characters = len(advice)
result = advice + “!” * number_of_characters
print(result)

advice2 = “Don’t Repeat Yourself! Keep things DRY!”
advice2 = advice2.upper()
number_of_characters = len(advice2)
result = advice2 + “!” * number_of_characters
print(result)

A

The provided Python code involves repeating similar operations on different strings and aims to capitalize the strings, calculate the number of characters, and append exclamation marks based on certain conditions. Here’s an explanation of the code:

praise = "You are doing great!"
praise = praise.upper()
number_of_characters = len(praise)
result = praise + "!" * (number_of_characters // 2)
print(result)

In this code snippet, the string praise is initially set to “You are doing great!”. Then, praise.upper() is used to convert the string to uppercase letters. The len(praise) function is used to calculate the number of characters in the string, which is stored in the variable number_of_characters. Finally, result is constructed by concatenating praise with exclamation marks (“!”) repeated half the number of characters in praise. The resulting result is printed.

Similarly, the same operations are repeated for the advice and advice2 strings.

To shorten the code and avoid repeating the same operations, you can define a function that encapsulates the common functionality. Here’s an example:
~~~
def process_string(input_string):
processed_string = input_string.upper()
number_of_characters = len(processed_string)
result = processed_string + “!” * number_of_characters
return result

praise = “You are doing great!”
print(process_string(praise))

advice = “Don’t forget to ask for Advice!”
print(process_string(advice))

advice2 = “Don’t Repeat Yourself! Keep things DRY!”
print(process_string(advice2))
~~~

In this updated version, the process_string() function takes an input string, performs the common operations (capitalization, character count, appending exclamation marks), and returns the resulting string. The function is called for each input string, eliminating the need to repeat the code.

57
Q

Explain this code:

def yell(text):
text = text.upper()
number_of_characters = len(text)
result = text + “!” * (number_of_characters // 4)
print(result)

praise = yell(“You are doing great”)
advice = yell(“Don’t forget to ask for Advice!”)
advice2 = yell(“Don’t Repeat Yourself! Keep things DRY!”)

A

This code defines a function called yell that takes in a string parameter text. Inside the function, the text string is converted to uppercase using the .upper() method, and its length is found using the len() function. A new string called result is then created by concatenating the text string with a number of exclamation points equal to one-fourth of the length of the text string (rounded down to the nearest integer). Finally, the result string is printed to the console.

The function is called three times with different input strings, and the resulting modified strings are assigned to the variables praise, advice, and advice2. However, note that these variables are not used for anything since the yell function does not return any value. The purpose of calling the function seems to be just to print the modified strings to the console.

Here’s an example output of running this code:

YOU ARE DOING GREAT!! DON'T FORGET TO ASK FOR ADVICE!!! DON'T REPEAT YOURSELF! KEEP THINGS DRY!!!

In this example output, the text strings have been converted to uppercase and appended with a number of exclamation points based on their lengths. The ! character appears one time for every four characters in the text string.

58
Q

what is DRY principle in Python?

A

DRY stands for “Don’t Repeat Yourself”. It is a software development principle that emphasizes the importance of avoiding duplication of code and ensuring that code is reusable.

In Python, the DRY principle can be applied in several ways, such as:

  1. Using functions to encapsulate reusable code and avoid duplication.
  2. Using loops and list comprehensions to avoid repeating the same code for each element in a list or other iterable.
  3. Using inheritance and polymorphism to create reusable and extensible code.
  4. Using constants and configuration files to avoid repeating values or settings in multiple places in the code.

By following the DRY principle, Python developers can write more efficient, readable, and maintainable code that is easier to modify and less prone to errors.

59
Q

what does math.ceil do in python?

A

In Python, the math.ceil() function is a method from the math module that rounds a given number up to the nearest integer, returning the smallest integer greater than or equal to the input.

The syntax for using math.ceil() is as follows:
~~~
import math

result = math.ceil(x)
~~~

Here, x is the number you want to round up to the nearest integer, and result will be the rounded-up value.

Here are a few examples to illustrate the usage of math.ceil():
~~~
import math

result1 = math.ceil(3.2)
print(result1) # Output: 4

result2 = math.ceil(7.8)
print(result2) # Output: 8

result3 = math.ceil(-2.5)
print(result3) # Output: -2
~~~

In these examples, math.ceil() is used to round the given numbers up to the nearest integer. The function returns the smallest integer greater than or equal to the input, regardless of whether the input is positive or negative.

60
Q

Explain this code:
~~~
import math

def split_check(total, number_of_people):
return math.ceil(total / number_of_people)

total_due = float(input(“What is the total? “))
number_of_people = int(input(“How many people? “))

amount_due = split_check(total_due, number_of_people)
print(“Each person owes {}”.format(amount_due))
~~~

A

In this code:

  1. The import math statement imports the math module, which provides various mathematical functions and constants.
  2. The split_check() function is defined with two parameters, total and number_of_people. It calculates the amount that each person owes by dividing the total by the number of people using math.ceil() to round up the result.
  3. The total_due variable prompts the user to enter the total amount due, converted to a floating-point number using float(input()).
  4. The number_of_people variable prompts the user to enter the number of people, converted to an integer using int(input()).
  5. The amount_due variable calls the split_check() function, passing the total_due and number_of_people as arguments, and stores the calculated result.
  6. Finally, the calculated amount due is printed using print(), where the placeholder {} is replaced with the value of amount_due using the .format() method.

Overall, this code takes user input for the total bill amount and the number of people, and then calculates and displays the amount each person owes, ensuring that the total is split evenly by rounding up using math.ceil().

61
Q

What does murphy’s law state and how is it useful in programming?

A

Murphy’s Law is a popular adage that states: “Anything that can go wrong, will go wrong.” It is a humorous reminder that no matter how well we plan or how confident we are in our abilities, unexpected issues can and will arise.

In programming, Murphy’s Law can be useful as a reminder to anticipate and plan for potential problems or errors. By being aware that things can and will go wrong, programmers can take steps to prevent or mitigate the impact of issues, such as by writing code that is robust, well-tested, and easily maintainable. They can also implement defensive programming techniques, such as error handling and exception handling, to prevent unexpected behavior and ensure that the program continues to run smoothly even in the face of errors.

In addition, Murphy’s Law can also serve as a reminder to be humble and open-minded in the face of unexpected problems or failures. Programmers can use these experiences as opportunities to learn and improve their skills, rather than becoming discouraged or frustrated by the setback.

Overall, while Murphy’s Law may seem like a negative or pessimistic outlook, it can be a useful mindset for programmers to adopt in order to anticipate and prepare for potential issues, as well as to approach problems with a constructive and learning-oriented attitude.

62
Q

what is try: and except: in python?

A

In Python, try and except are keywords used in exception handling to handle potential errors or exceptions that may occur during the execution of a block of code. The general syntax for using try and except is as follows:

try:
    # Code block where an exception may occur
except ExceptionType:
    # Code block to handle the exception

Here’s how it works:

  1. The code inside the try block is the section where you anticipate potential exceptions or errors. If an exception occurs within this block, the program flow immediately jumps to the corresponding except block.
  2. The except block specifies the type of exception you want to catch and handle. ExceptionType represents the specific type of exception you expect to encounter. For example, you can use except ValueError to catch a ValueError exception.
  3. If an exception of the specified type occurs within the try block, the code inside the corresponding except block is executed. This allows you to handle the exception gracefully, perform error recovery, or display an appropriate error message.
  4. You can have multiple except blocks after a single try block to handle different types of exceptions. The code inside the first matching except block that matches the raised exception type will be executed.

Here’s a simple example that demonstrates the use of try and except:
~~~
try:
num = int(input(“Enter a number: “))
result = 10 / num
print(“The result is:”, result)
except ZeroDivisionError:
print(“Error: Cannot divide by zero.”)
except ValueError:
print(“Error: Invalid input. Please enter a number.”)
~~~

In this example:

  1. The code inside the try block prompts the user to enter a number, converts it to an integer using int(), and then performs a division operation.
  2. If a ZeroDivisionError exception occurs (e.g., if the user enters 0 as the input), the program flow jumps to the corresponding except ZeroDivisionError block, and an error message is printed.
  3. If a ValueError exception occurs (e.g., if the user enters a non-numeric value), the program flow jumps to the corresponding except ValueError block, and an error message is printed.

By using try and except, you can handle potential errors or exceptions and ensure that your program does not terminate abruptly when encountering such situations.

63
Q

What result will this python code give and explain this code:

print("A")
try:
    result = 5 + 5
    print("B")
except ValueError:
    print("C")
except TypeError:
    print("D")
else:
    print("E")
print("F")
A

Explanation:

  • The code starts with print(“A”), which prints the letter “A” on the console.
  • The subsequent lines are part of a try-except block, which is used for exception handling.
  • Inside the try block, result is assigned the value of the sum 5 + 5. This line performs a basic arithmetic operation.
  • Following that, print(“B”) is executed and the letter “B” is printed on the console.
  • If an exception occurs during the execution of the try block, Python checks whether the exception type matches any of the specified except blocks.
  • In this case, there are no specified except blocks for ValueError or TypeError, so if an exception of either type occurs, it will not be caught by those blocks.
  • Since there is an else block present, if no exception occurs in the try block, the code inside the else block will be executed.
  • In this code, the else block contains print(“E”), which prints the letter “E” on the console.
  • Finally, outside of the try-except block, print(“F”) is executed, printing the letter “F” on the console.

Therefore, the code will output:
~~~
A
B
E
F
~~~

Explanation: The code will print “A”, “B”, “E”, and “F” in order because there are no exceptions raised within the try block. The else block will be executed, printing “E” before proceeding to print “F” outside of the try-except block.

64
Q

What is ValueError and TypeError in Python?

A

In Python, ValueError and TypeError are built-in exception classes that represent specific types of errors that can occur during the execution of a program. Both ValueError and TypeError are subclasses of the base Exception class.

Here’s an explanation of each of these exception types:

  1. ValueError:
    * ValueError is raised when a function receives an argument of the correct type but an inappropriate value.
    * It typically occurs when a built-in function or method expects a certain value or format, and the provided value does not meet the expected criteria.
    * Examples of situations that may raise a ValueError include converting a string to an integer or float where the string does not represent a valid number, or passing an invalid argument to a function that expects specific input.
  2. TypeError:
    * TypeError is raised when an operation or function is performed on an object of an inappropriate type.
    * It occurs when an operation or function is applied to an object that does not support that operation or is not of the expected type.
    * Examples of situations that may raise a TypeError include attempting to perform mathematical operations on incompatible data types, such as adding a string to an integer or dividing a string by a string.

Here’s an example illustrating the use of ValueError and TypeError:
~~~
try:
number = int(“abc”) # Raises ValueError: invalid literal for int() with base 10
result = 10 / “2” # Raises TypeError: unsupported operand type(s) for /: ‘int’ and ‘str’
except ValueError as ve:
print(“ValueError:”, ve)
except TypeError as te:
print(“TypeError:”, te)
~~~

In this example, the code attempts to convert the string “abc” to an integer using int(), which raises a ValueError due to the invalid literal. Additionally, dividing the number 10 by the string “2” causes a TypeError because division is not supported between an integer and a string.

By using try-except blocks and catching specific exception types like ValueError and TypeError, you can handle these errors gracefully and provide appropriate error messages or perform error recovery actions in your code.

65
Q

what will raise do in python?

A

In Python, the raise keyword is used to manually raise an exception or error during the execution of a program. When you raise an exception, it interrupts the normal flow of execution and transfers control to the exception handling code.

The general syntax for using raise is as follows:
~~~
raise ExceptionType(“Error message”)
~~~

Here’s how it works:

  1. ExceptionType represents the type of exception you want to raise. It can be any built-in or user-defined exception class that inherits from the base Exception class.
  2. The optional “Error message” argument provides a description or additional information about the exception. It is typically a string, but it can be any object that can be converted to a string.
  3. When the raise statement is encountered, an instance of the specified exception type is created with the provided error message (if any). The created exception is then immediately raised.
  4. The program flow jumps to the nearest matching except block that handles the raised exception type. If there is no matching except block, the program terminates, and a traceback is printed.

Here’s a simple example that demonstrates the use of raise:
~~~
def calculate_average(numbers):
if len(numbers) == 0:
raise ValueError(“Cannot calculate average of an empty list.”)
total = sum(numbers)
average = total / len(numbers)
return average

try:
data = []
result = calculate_average(data)
print(“Average:”, result)
except ValueError as ve:
print(“Error:”, ve)
~~~

In this example:

  • The calculate_average() function takes a list of numbers as an argument.
  • If the list is empty, it raises a ValueError with the error message “Cannot calculate average of an empty list.”
  • In the try block, an empty list data is passed to calculate_average().
  • Since the list is empty, the raise statement is triggered, raising a ValueError.
  • The program flow jumps to the matching except ValueError block, where the error message is printed.
  • If the list were non-empty, the code after the raise statement would not be executed, and the program flow would continue normally.
  • By using the raise statement, you can explicitly raise exceptions to handle exceptional conditions or to indicate errors in your program.
66
Q

Format this code:
In the following code, what does except ValueError as err: mean?

import math

def split_check(total, number_of_people):
    if number_of_people <= 1:
        raise ValueError("More than 1 person is required to split the check")
    return math.ceil(total / number_of_people)

try:
    total_due = float(input("What is the total? "))
    number_of_people = int(input("How many people? "))
    amount_due = split_check(total_due, number_of_people)
except ValueError as err:
    print("Oh no! That's not a valid value. Try again...")
    print("({})".format(err))
else:
    print("Each person owes {}".format(amount_due))
A

In this formatted code:

  1. The code starts with the import math statement, importing the math module to use the math.ceil() function.
  2. The split_check() function is defined, taking two parameters: total and number_of_people. It checks if number_of_people is less than or equal to 1 and raises a ValueError with an appropriate error message if that condition is met. Otherwise, it calculates the split amount using math.ceil() and returns it.
  3. The code inside the try block prompts the user to input the total amount and the number of people, converts them to the appropriate data types, and calls the split_check() function to calculate the amount due.
  4. If a ValueError exception occurs within the try block (raised by the split_check() function), the program flow jumps to the corresponding except ValueError block. The exception is assigned to the variable err, allowing access to the exception object.
  5. Inside the except block, an error message is printed, indicating that an invalid value was entered. The error message from the exception object is also printed using string formatting.
  6. If no exception occurs within the try block, the code inside the else block is executed. In this case, it prints the calculated amount due per person.

By using try-except blocks, the code handles the possibility of a ValueError being raised when dividing the total by the number of people. If such an error occurs, it provides a specific error message, allowing the program to recover gracefully.

67
Q

What is loop in python and how do you use it?

A

In Python, a loop is a programming construct that allows you to repeatedly execute a block of code. It enables automating repetitive tasks or processing a collection of items. Python provides two main types of loops: for loops and while loops.

for loop:
A for loop is used to iterate over a sequence (such as a list, tuple, string, or range) or any iterable object. It executes a block of code for each element in the sequence.
Here’s the general syntax of a for loop:
~~~
for element in sequence:
# Code block to be executed for each element
~~~

The loop variable element represents the current element from the sequence in each iteration. You can choose any name for the loop variable. The code block indented below the for statement is executed for each element in the sequence.

Here’s an example of a for loop that prints each element of a list:
~~~
fruits = [“apple”, “banana”, “orange”]
for fruit in fruits:
print(fruit)
~~~

In this example, the loop iterates over the fruits list, assigning each fruit to the fruit variable. The code block inside the loop then prints each fruit.

while loop:
A while loop is used to repeatedly execute a block of code as long as a certain condition is true. It continues executing until the condition becomes false.
Here’s the general syntax of a while loop:
~~~
while condition:
# Code block to be executed as long as the condition is true
~~~

The loop continues executing the code block as long as the condition remains true. The condition is evaluated before each iteration.

Here’s an example of a while loop that prints numbers from 1 to 5:
~~~
count = 1
while count <= 5:
print(count)
count += 1
~~~

In this example, the loop continues printing the value of count as long as it is less than or equal to 5. After each iteration, the count variable is incremented by 1 using count += 1.

Loops allow you to automate repetitive tasks and perform iterative operations over sequences or based on specific conditions. You can combine loops with other programming constructs to accomplish various tasks efficiently.

68
Q

what does import sys mean in Python?

A

In Python, import sys is a statement that imports the sys module. The sys module provides access to some variables and functions that interact with the Python interpreter and the system on which it is running.

Some of the functions and variables provided by the sys module include:

  • sys.argv: A list that contains the command-line arguments passed to the Python script.
  • sys.path: A list that contains the directories where Python searches for module files.
  • sys.platform: A string that specifies the platform on which Python is running.
  • sys.exit(): A function that terminates the Python interpreter with a given exit status.

By importing the sys module, you can use these functions and variables in your Python code. For example, the following code uses the sys.argv variable to print the command-line arguments passed to a Python script:

import sys for arg in sys.argv: print(arg)

This code imports the sys module, and then uses a for loop to iterate over the sys.argv list and print each argument to the console.

Overall, importing the sys module can be useful in a wide range of Python programs, particularly those that need to interact with the command line, the file system, or the operating system in some way.

69
Q

Explain this code:

import sys

MASTER_PASSWORD = "opensesame"
password = input("Please enter the super secret password: ")
attempt_count = 1

while password != MASTER_PASSWORD:
    if attempt_count > 3:
        sys.exit("Too many invalid password attempts")
    password = input("Invalid password, try again: ")
    attempt_count += 1

print("Welcome to the secret room")
A

This Python code prompts the user to enter a password and checks if it matches a predefined master password. If the user enters an incorrect password, they are prompted to enter it again up to a maximum of three attempts. If the user enters an incorrect password three times, the program exits with an error message. If the user enters the correct password, they are granted access to a “secret room” and a message is printed to the console.

Here’s a step-by-step explanation of how the code works:

  1. The first line imports the sys module, which provides access to some variables and functions that interact with the Python interpreter and the system on which it is running.
  2. The second line defines a constant variable MASTER_PASSWORD and assigns it the string value “opensesame”. This is the password that the user needs to enter in order to access the “secret room”.
  3. The third line prompts the user to enter a password by displaying the message “Please enter the super secret password: “ and waits for the user to enter a response.
  4. The fourth line initializes a variable attempt_count to 1. This variable will be used to keep track of how many attempts the user has made to enter the correct password.
  5. The while loop on line 5 checks if the user-entered password matches the master password MASTER_PASSWORD. If the passwords don’t match, the code inside the loop is executed.
  6. The if statement on line 6 checks if the number of password attempts attempt_count is greater than 3. If the user has made more than three invalid attempts, the sys.exit() function is called with the error message “Too many invalid password attempts”. This terminates the program and exits with an error code.
  7. If the user has not made too many attempts, the password variable is reassigned to a new value based on the user’s input on line 8.
  8. The attempt_count variable is incremented by 1 on line 9.
  9. The loop continues to repeat until the user enters the correct password or has made three invalid attempts.
  10. If the user enters the correct password, the loop exits, and the message “Welcome to secret room” is printed to the console.

Overall, this code demonstrates how to prompt a user for a password and check if it matches a predefined value in Python. It also shows how to use loops and conditional statements to control program flow and handle errors.

70
Q

Explain this code:
~~~
banner = “happy birthday”
for letter in banner:
print(letter.upper())
~~~

A

In this code:

  • The banner variable stores the string “happy birthday”.
  • The for loop iterates over each character (letter) in the banner string.
  • In each iteration, the letter.upper() function is called to convert the character to uppercase.
  • The converted uppercase letter is then printed using print().

This code will output each character of the banner string in uppercase on a separate line. It effectively prints “HAPPY BIRTHDAY” as each character is individually transformed to uppercase using the upper() method.