exercises_for_programmers_archive's People
exercises_for_programmers_archive's Issues
Question on exercise output
I want to check if my output matches what this question is asking.
Here are the instructions: Generate a single output statement with line breaks in the appropriate spots.
(I took that to mean to print all of the output together. Is this correct?)
import math
number_1 = int(input("Enter one number: "))
number_2 = int(input("Enter a second number: "))
sum = number_1 + number_2
difference = number_1 - number_2
product = number_1 * number_2
quotient = number_1 / number_2
print(f"""
The math operations are:
{number_1} + {number_2} = {sum}
{number_1} - {number_2} = {difference}
{number_1} * {number_2} = {product}
{number_1} / {number_2} = {math.ceil(quotient)}
""")
Tuple - question 2
Question 1:
len(((1, 2),)) --->evaluates to 1.
I thought that the comma on the far right denoted a place holder for a value, so the len would be 2? Why doesn't the comma count as a value?
-----> ,))
Question 2:
len((1, 2,(1, 2, 3)))
Why is there a comma after the two in the parent tuple ----> (1, 2,....
And there's not a comma after the child tuple ----> (1,2,3)....
Is the comma in the first instance to tell Python that you're not multiplying the parent 2 to the child ()? That is, to tell python that 2 is a number in a () and not a math operation?
String question
Is it a rule when concatenating integers to make them strings?
Ex:
a=1
b=2
c=a/b
add = str(a)+"/"+str(b)+"="+str(c)
print(add)
Math Equations
I'm trying to print math equations and have Python solve them -- without any commas or parentheses.
Example:
addition = ("4 + 4 =", 4+4)
Is there a way to do that without using variables for each number?
Conditionals
Instructions: Ask the user for two numbers. Print their sum. If the sum is less than zero, also print "Wow, negative sum!"
number_1 = int(input("Enter a number: "))
number_2 = int(input("Enter a second number: "))
sum = number_1 + number_2
print(sum)
If number_1+number_2 < 0:
print("Wow, negative sum!")
Decimals
3 Questions:
-
Am I correct to use "float"?
-
I'm not clear why this last line of code isn't working (I get an error):
print(f"The tip amount is ${:.2f}".format(tip_calculation))
- To convert a number to a decimal is "{:.2f}".format" something I just need to memorize?
Here's the code:
#step1: ask user for bill amount
bill_amount = float(input("What was the bill amount? "))
#step2: ask user for tip rate
tip_rate = float(input("What is your tip rate? "))
#step3: calculate tip from an integer to a decimal
tip_calculation = tip_rate/100 * bill_amount
#print statement with tip amount
print(f"The tip amount is ${:.2f}".format(tip_calculation))
Indexing
I'm working on indexing and unclear about this problem:
secret = "mai p455w_zero_rD"
secret [-1:-8]
I have to evaluate the expression. The answer is: "empty string b/c the start index is further in the string than the stop index." However, isn't the start index "D" and the stop index "_"? So the answer should be "Dr_orez" (the step is "1" since it's not defined).
What is a module
What is a module? Not clear after researching it.
String commands
Question 1: find() is case sensitive, but is rfind()?
The reason I ask is because of this:
a = "python 4 ever&EVER"
a.rfind("rev") --->evaluates to -1. Why?
Conditional exercise
Can you take a quick look at this:
Instructions: Create a variant of the program that prompts for the number of people and the number of pieces each person wants, and calculate how many full pizzas you need to purchase.
#import sys to test for validity later in program
import sys
#step1: set constant
SLICES_PER_PIZZA = 10
#step2: get input
total_people = int(input("How many people are eating pizza? "))
desired_pizza_slices = int(input("How many slices does everyone want? "))
#step3: write conditionals to determine how many full pizzas they need
if desired_pizza_slices < 1:
print("Please enter a valid number.")
sys.exit()
if desired_pizza_slices <= 5:
total_pizza_slices = SLICES_PER_PIZZA * desired_pizza_slices
total_pizzas = total_pizza_slices // total_people
print(f"You'll need {total_pizzas} full pizzas.")
else:
print("That's too much pizza!")
Conditionals - 2
Two examples I have questions about:
Example 1:
word = input("Enter a word: ")
if " " in word:
print("User didn't follow directions.")
--->The code above works, but why can't the code below work as well (using the ==):
word = input("Enter a word: ")
if word == " ":
print("User didn't follow directions.")
Example 2:
This code works and I understand why:
user_info = "words"
if type(user_info) == str:
print("I'm a words person")
----->But why can't I type something like this:
user_info = "words"
if str in user.info:
print("I'm a words person")
.format
I'm not clear about how to reduce the amount of code when using .format() twice in the same line of code. I get an error when I remove the first instance of ".format(....)":
Step 1: set constant
WI_TAX = 5.5
Step 2: get input from user
order_amount = int(input("Enter the order amount:$"))
state = input("Enter your state (use state abbreviations): ")
normalized_state = state.lower()
Step 3: write conditional
if normalized_state == "wi":
tax = (WI_TAX / 100) * order_amount
print("You're going to pay ${:.2f}".format(tax) + " in tax.")
subtotal = order_amount + tax
--> print("Your order total is
#The above line is the one in question and the one I get an error. How does Python know what to print #if I remove the first .format()?
else:
print(f"Your subtotal is ${order_amount}.")
Function question
The program should ask the user to enter the balance of a credit card and the APR of the card. The program should then return the number of months needed. Use a function called calculateMonthsUntilPaidOff, which accepts the balance, the APR, and the monthly payment as its arguments and returns the number of months. Don’t access any of these values outside the function.
Questions:
-I'm not sure what I should use as parameters here? So I use *months_to_pay_cc
to allow an infinite number of arguments to be passed. Is this correct?
-The problem stated not to get user input outside of the function, which is why I include it inside of it. However, this seems confusing with the arguments (the problem states what to include as arguments).
-I can't get the calculation to run properly, which is why I divided it into several lines. But it still doesn't work. What's going on?!
import math
def calc_months_until_paid_off(*months_to_pay_cc):
"""Write a function to determine the number of months until credit card is paid off"""
# Get input from user
credit_card_balance = int(input("Enter your credit card balance: $"))
apr = int(input("Enter the APR as a percent: "))
monthly_payment = int(input("Enter your monthly payment: $"))
# Calculate apr as a decimal and the apr daily rate
apr_as_decimal = apr / 100
apr_daily_rate = apr_as_decimal / 365
# Calcuate number of months to pay off credit card
top_of_calculation = math.log(1 + credit_card_balance / monthly_payment (1 - (1 - apr_daily_rate) ** 30))
bottom_of_calculation = math.log(1 + apr_daily_rate)
months_to_pay_cc = -1/30 * top_of_calculation / bottom_of_calculation
return(months_to_pay_cc)
calc_months_until_paid_off(credit_card_balance, apr, monthly_payment)
# print statement
loops
I'm not clear how and when the first line of a loop should be written:
user_names = 100
option 1:
for name in range(user_names):
option 2:
user_names = 100
for name in user_names:
---> I sometimes see option 2 (using a variable name). In this instance I get an error when I use a variable name associated with a number. How do I know when to use either format?
Rounding decimals
I'm getting an error when I use the feature to round two decimal places, and I'm not sure why. I've tried various combinations but still run into the error. Ultimately I want to round 4 decimal places, but am starting with two, as I have round two decimal places later on. Can you spot what I'm doing wrong here?
#step1: create variable for miles and set it to 5
miles = 5
#step2: write calculation to convert 5 miles to kilometers using provided equation
miles_to_kilometers = miles / 0.62137
#step3: print statement with miles, kilometers, and meters and their totals
print(f"{:.2f}.format(miles_to_kilometers)")
----->Why do I get an error in step 3?
Variables
Confirm:
apple = 5 -----> that variable and expression is an assignment, correct? Yes
Confirm:
greeting = "hello"
Constants
Constant must be a single value, such as a string or number, that never changes. area = L * W is a statement that changes with different values of L and W.
Tuples
len((1, 2, (1, 2, 3)))
--Why does this evaluate to 3?
len((1, 2, 3,("abc")))
--Why does this evaluate to 4? Isn't "1, 2, 3" it's own tuple and "abc" it's own?
len((1, 2, ("abc",))
--I'm not sure how to make this one work to get the length? I've tried many combinations, moving the comma but it's not working.
Relative vs absolute paths
I'm not entirely clear about relative vs absolute paths. Where do I find/use these? Absolute paths start with a '/', correct? And Relative paths don't?
Math and tuples
len("abc") * ("no",)
-Why would I multiply the above line of code with "len" in front? If I don't use "len" I get an error.
-Why does this evaluate to:
('no', 'no', 'no')
Why is "abc" removed? I thought when multiplying tuples it would look something like this:
(abc)(no)
Ex #27 question
@paulghaddad I have two questions about the function we spoke about yesterday:
-First, the program prints the line "This ID is invalid" for every character that's not in the correct spot. For example, if the employee enters the ID: AA-aaaa, then I'll get four lines of code saying that this entry is invalid -- one for each of the invalid characters -- and just for the numbers section:
numbers_employee_id = e_id[3:]
for number in numbers_employee_id:
if number not in numbers:
print(f"{e_id} is not a valid ID.")
How can I prevent this from happening? Is a while loop needed here? I need to print a general statement that no errors were found if there are no errors after all of my checks, which is why I was thinking a while loop may be good to use.
-Second, below is my version and this is the main difference: I specify the index in each for loop. Is this fine to do?
for letter in employee_id[:2]:
if letter not in letters:
print("This ID is invalid.")
vs:
two_characters_in_employee_id = e_id[:2]
for character in two_characters_in_employee_id:
if character not in letters:
print(f"{e_id} is not a valid ID.")
Conditional ex question
Instruction:
You're given the following two statements:
"x is an odd number" and "x + 1 is an even number"
Write a conditional statement and outcome.
if x % 2 != 0:
print("x is an odd number")
print("x + 1 is an even number")
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.