1. Python Beginner (3h) Flashcards
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!")
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.
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?
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.
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)
~~~
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.
Command to list all files in console
ls
how to write hello world in python
print("Hello world")
How to run a python script in console/terminal if python script is saved in file hello.py?
python hello.py
What is REPL in Python?
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»_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 will you see the version of Python you are running in terminal/console?
By typing “python” and entering.
python –version
or
python3 –version
How to open REPL in Terminal?
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»_space;> print(“Hello World”)
How will you call for help in Python to learn about a function? Let’s say you want to learn about print function.
help(print)
How would you quit/exit REPL?
By entering the function called exit: exit()
Or just by pressing q
Or by pressing Ctrl+D
unexpected EOF while parsing, what does this error mean?
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.
What does EOL error mean?
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.
Rules of Language in Python is called as?
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
What are object, variables, string, classes, attributes, methods mean in Python?
In Python, these are the basic concepts related to Object-Oriented Programming:
- 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).
- 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.
- Strings: A string is a sequence of characters. In Python, strings are represented using quotes, either single quotes or double quotes.
- 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.
- 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.
- 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.
first_name = "Ada"
Which is variable and string here?
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.
first_name = "ada" print("hello!", first_name) print(first_name, "is the first", "programmer")
What output will this give?
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 will you create a varible where users can enter there own input?
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.
Use snake_case for variables means?
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.
what is camelCase and PascalCase?
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_case
is 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.
What are whole numbers and what are integers?
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.
What is floating point or float?
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.
what does _ represent in REPL?
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.
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?
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.
what does CTRL+L do in REPL in terminal?
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.
What does PEMDAS mean? What is the acronym/mnemonics expansion for PEMDAS?
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 will use PEMDAS on this equation: 5 + 6 * (7 - 3) / 2^2 ?
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.
Difference between BODMAS and PEMDAS? And how can this equation be solved with both methods: 4 + 5 * (8 / 2) - 3^2 + 6 / 2 ?
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.