I'm trying to multiply inputs using functions and arguments [duplicate] - python

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 1 year ago.
I'm new to functions and arguments (actually new to python in general) and I'm having a bit of a problem making this program multiply the unit given by the user and output it. It just keeps coming up as whatever the variable is up top, and if I don't include that it says it isn't defined. May someone help, please?
# Variables
inches = 0
item_length = 0
unit_value = 0
# Your unit (smooots for general purposes) function
def inches_to_smoots(inches):
## inches = item x unit value
inches = item_length * unit_value
## return the number of inches
return inches
## main function
def main():
unit = input("What is the name of your unit? ")
unit_value = input (str("What is the length of your unit in inches? "))
item = input("What is the name of the object you'd like to convert to your unit? ")
item_length = input ("What is the length of your item in inches? ") # Is there a way to print a variable inside an input statement?
answer = inches_to_smoots(item_length)
## print the answer
print(item_length,'inches is', inches, unit, 's!')
## call main
main()

Instead of declaring the variables up at the top, your function should take the necessary inputs as arguments. Since you're doing unit conversion, it's very helpful to give each variable a name that indicates what units it's in! For example, your inches_to_smoots function is presumably (according to its name) supposed to take an inch measurement and return a smoot measurement, but you're returning a value called inches. It would make more sense for one of its arguments to be inches and for it to return something that's in smoots. When your code itself makes sense, you'll find that it's not necessary to comment each individual line to explain it.
Make sure to keep the Python types straight as well -- input() gives you a str, but for any kind of mathematical operation you want values to be int or float.
def inches_to_smoots(inches: float, smoots_per_inch: float) -> float:
smoots = inches * smoots_per_inch
return smoots
def main():
smoot = input("What is the name of your unit? ")
inches_per_smoot = float(input(
f"What is the length of one {smoot} in inches? "
))
item_name = input(
f"What is the name of the object you'd like to convert to {smoot}s? "
)
item_inches = float(input(f"What is the length of your {item_name} in inches? "))
item_smoots = inches_to_smoots(item_inches, 1 / inches_per_smoot)
print(f"{item_inches} inches is {item_smoots} {smoot}s!")
if __name__ == '__main__':
main()
Note that your function inches_to_smoots expects to be told how many smoots are in an inch, but you asked the user for the number of inches in a smoot -- hence you want to take the reciprocal! smoots_per_inch == 1 / inches_per_smoot.
Example output:
What is the name of your unit? finger
What is the length of one finger in inches? 4.5
What is the name of the object you'd like to convert to fingers? hand
What is the length of your hand in inches? 7
7.0 inches is 1.5555555555555554 fingers!

To make math with elements inputed by the user, you need to convert it to int or float using the int() or float() methods.
unit = input("What is the name of your unit? ")
unit_value = int(input (str("What is the length of your unit in inches? ")))
item = int(input("What is the name of the object you'd like to convert to your unit? "))
item_length = int(input ("What is the length of your item in inches? ") # Is there a way to print a variable inside an input statement?)
That is because it is seeing inputs as strings and python does not know how to properly multiply those together.

Related

How to get user input for multiple arguements in a function in Python3

Essentially I want to use the input() function to take user input for multiple arguements in this function and return the value
def object_distance(f,di):
do = 1/((1/f)-(1/di))
return do
odistance = input(object_distance())
print("The object distance is: {0:3.1f} cm".format(odistance))
you can call input multiple times.
f_input = input('Enter f:')
di_input = input('Enter di:')
odistance = object_distance(f_input, di_input)
You can enter 2 values one after another. I also cast the input to int when calling the function.
def object_distance(f, di):
do = 1/((1/f)-(1/di))
return do
f, di = input ('Input 2 values separated by a space').split()
odistance = object_distance(int(f) , int(di))
print("The object distance is: {0:3.1f} cm".format(odistance))
Output
Input 2 values separated by a space
7 9
The object distance is: 31.5 cm```
You have to get the input first, and then call the function.
a1 = input("Enter f: ")
a2 = input("Enter di: ")
# TODO Convert the strings a1 and a2 to values of the appropriate
# type for object_distance.
distance = object_distance(a1, a2)
The argument to input is just a string to display as a prompt, not a function (and certainly not a call to that function) that it "works with" to determine how many arguments are needed.

Python Input and Output? [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 1 year ago.
I am working on learning python and I for some reason the output I get is always incorrect. Not sure what I'm doing wrong or how to fix it and any help is greatly appreciated:
##a. 3 variables —
## The name of a movie
## The number of tickets to purchase
## The total cost of tickets purchased
##
##b. 1 Constant —
## The cost of a single ticket
##2. Create four print statements that will display the values of the variables and the constant along with labels that describe them
##
#Initialize
movieNm = str("")
numTickets = int(0)
totalTicketPrice = float(0.0)
SINGLE_TICKET = int(10)
#input
name = input("Enter the name of the movie you would like to see:")
numTickets = input("Enter the number of tickets you wish to purchase:")
#process
totalTicketPrice = SINGLE_TICKET * numTickets
#output
print("Feature Film", name)
print("Cost of single ticket", SINGLE_TICKET)
print("Number of Tickets purchased", numTickets)
print("Your Total", SINGLE_TICKET * numTickets)
When you test the code the output is always just so wrong and I'm not sure how to fix it. thanks!
in this line numTickets = input("Enter the number of tickets you wish to purchase:") when you got user input you got string you should convert this input to int like below:
numTickets = int(input("Enter the number of tickets you wish to purchase:"))
see this example maybe help you (this example happen in your code):
print('2'*10)
# 2222222222

How do I fix this TypeError in Python concerning non-int and floats?

I'm working with Python 3 on Visual Studio Code and the project I'm working on is to calculate the user's lunar weight after receiving their terrestrial weight, then output how their weight changes overtime given an increase and a period of time.
This is the error message I've received multiple times, no matter how many times I've re-code:
TypeError: can't multiply sequence by non-int of type 'float'
This specifically happens whenever I use the input() and/or sys.stdin.readline() functions, but all of the pertaining variables are integers or floats, whether or not I try to convert them to floats by using the float() function around my inputs.
Here is my code:
# this programs converts your terra weight to your lunar weight, then it takes increase over a period of time
# error whether I use float() or not
terraWeight = float(input("Terra Weight: "))
ask = input("Is this in LBS or KG? ")
# converts pounds to kilograms
# 2.204... is used to convert lbs to kgs
if ask == "lbs" or "LBS":
initial = terraWeight / 2.2046223302272
# didn't need this, but assignment error popped up
x = 0
# or replace input() with sys.stdin.readline()
increase = input("Increase: ")
period = input("Period: ")
# gets lunar weight over time
def lunarWeight():
global increase
global period
global x
global initial
print("Earth Weight = %s kgs." % terraWeight)
year = 0
lunarWeight = initial * 0.165
print("Moon Weight = %s kgs. \n" % lunarWeight)
postIncrease = lunarWeight * increase
for x in range(0, period):
year += 1
lunarWeight += postIncrease
print("Year %s = %s kgs." % (year, lunarWeight))
lunarWeight()
The terminal directs to the this section of my code:
postIncrease = lunarWeight * increase
Which is on line 28. I'm not sure what the problem is, and I tried debugging but I still get the same error messages. I saw other posts with the same problem but they had problems using lists, which I'm pretty sure I'm not using. Any advice please?
Screenshot
I think you should write this lines as:
increase = float(input("Increase: "))
period = int(input("Period: "))
period is used in range() so it should be integer

Why are my non-active variables picking up prices?

A simple program to help me calculate costs for some new flooring, but my final outputs are not what i expect.
In particular, when underlay is "No", the variable for underlayarea is still picking up a value and being printed at the end.
If it isn't painfully obvious, this is my first crack at it. Ever.
I was expecting that while the variables for 'edging' and 'underlay' remained "No" that no values would be stored in that while loop.
underlay='No'
edging=input('Are you ordering Edging?').title()
underlay=input('Are you ordering underlay?').title()
roomsize=input('How many square meters is the room?')
roomflt=float(roomsize)
while edging =='Yes':
#ask for user inputs
edgeprice=input("How much is the edging per meter?")
edgeperim=input('What is the perimeter of the room?')
#convert to float for calculation
one=float(edgeperim)
two=float(edgeprice)
#calculate
edgearea=one*two
#reset flag
edging='No'
while underlay=='Yes':
#ask for user input
underlayprice=input('How much per square meter for the Underlay?')
#convert to float for calculation
three=float(underlayprice)
four=float(roomflt)
#calculate
underlayarea=three*four
#reset flag
underlay='No'
#set the floor price
floorprice=input("How much is the floor per square meter?")
#convert to float for calculation
five=float(floorprice)
six=float(roomflt)
#calculate
area=five*six
#get the cost
addemup=(edgearea+underlayarea+area)
print("\n----------------------------------------------\nThe total is £{0:.2f} to purchase the flooring.".format(addemup))
print("This is made up of £{0:.2f} for the floor itself,".format(area))
print("This is made up of £{0:.2f} for the edging,".format(edgearea))
print("and £{0:.2f} for the underlay".format(underlayarea))
You should use simple if-statements instead of using a while-loop and "resetting the flag" at the bottom of the loop. I also improved readability of your code by giving the variables telling names (never give variables names such as one, two and so on). You also have to define edgearea and underlayarea, because else a NameError would be raised in case the user does enter "No" in at least one of the inputs.
edgearea = 0
underlayarea = 0
edging = input('Are you ordering Edging?').title()
underlay = input('Are you ordering underlay?').title()
roomsize = input('How many square meters is the room?')
roomsize = float(roomsize)
if edging == 'Yes':
edgeprice = float(input("How much is the edging per meter?"))
edgeperim = float(input('What is the perimeter of the room?'))
edgearea = edgeperim * edgeprice
if underlay == 'Yes':
underlayprice = float(input('How much per square meter for the Underlay?'))
underlayarea = underlayprice * roomsize
floorprice = float(input("How much is the floor per square meter?"))
area = floorprice * roomsize
total_price = edgearea + underlayarea + area
print(f"\n----------------------------------------------\nThe total is {total} to purchase the flooring.")
print(f"This is made up of {area} for the floor itself,")
if edgearea:
print(f"This is made up of {edgearea} for the edging,")
if underlayarea:
print(f"and {underlayarea} for the underlay")
I would also like to recommend having a look at the DRY principle, aka "Don't repeat yourself". The three calculations have basically the same form. That's why it would be better code style to define a function for these calculations which takes the necessary parameters. A DRY solution could look similar to the following:
def calculate(
name: str,
dimension: str,
unit: str,
mandatory: bool = True,
) -> float:
mandatory = mandatory or input(f"Do you order {name}?") == "Yes"
if mandatory:
relative_price = float(input(f"How much is the {name} per {unit}?"))
size = float(input(f"How much {dimension} is the room?"))
return size * relative_price
return 0
floor_price = calculate("floor", "area", "squaremeters")
edging_price = calculate("edging", "perimeter", "meters", False)
underlay_price = calculate("underlay", "area", "squaremeters", False)
total_price = floor_price + edging_price + underlay_price

Currency Converter - can't multiply sequence by non-int of type 'float' error

I'm relatively new to Python and coding in general, and was recently tasked with designing a Currency Converter in Python. I've almost finished the code, but an issue arose on the final line.
currenctcurrency = input ("Select a starting currency: ")
print ('You selected %s' %currentcurrency)
value = input ("Input your current value: ")
new currency = input ("Select a new currency: ")
if currentcurrency == 'Pound' and newcurrency == 'Pound':
convertor = 1
The above part of the code repeats for each combination of the four supported currencies - pound, euro, dollar and yen.
rint ("Do you want to convert", (value), (currentcurrency), "to", (newcurrency), "?")
answer = input ("Yes/No: ")
if answer == 'No':
quit(1)
if answer == 'Yes':
result = (convertor) * (value)
print (result)
When I run the code, the inputs run successfully but when it tries to multiply the two variables together I get an error which reads:
TypeError: can't multiply sequence by non-int of type 'float'
As I said earlier, I'm new to Python and don't properly understand what I need to do to fix this. I would really appreciate if anyone could give me a simple/explained answer to my issue.
Thank you all for reading, have a great day!
Just change this line:
value = input ("Input your current value: ")
to this:
value = float(input("Input your current value: "))
The reason you get the error is that the input function returns a string. You can multiply strings (or any sequence) with integers, for example "foo" * 3 evaluates to "foofoofoo". But that obviously doesn't work with floating-point numbers, and it isn't what you want. Instead, you want to turn the string into a number, and then multiply it with your convertor value.
input returns a string (a sequence of characters). You need to parse the string to a numerical value.
You might want to try:
value = float(input("Input your current value: "))

Categories