How do I get multiple user inputs in python? - python

Hi I got the following problem, I'm trying to build a program that reads a txt file that contains lines with name of fruits and their respective base prices as the following example:
apple $ 2.00
pearl $ 4.00
guava $ 2.50
and so it goes on.
Yesterday I had some help with people here and I've learned how to make python recognize their prices as a number instead of string, and i was able to multiply their values by one number that was asked to the user. Now I want to make this in a such way that I'm able to take each one of those prices and multiply them for different numbers (one different number for each price) that will be asked for the user to choose.
So far, with the help that I got yesterday I've done this:
print "this program will calculate the total price of the fruits"
y = input('insert a value = ')
with open('fruits.txt') as f:
for line in f:
name, price = line.rstrip().split('$')
price = float(price)
cost = price * (0.76+y)
tcost = cost + price
print name, tcost
Any ideas how to do this?

mult_by = int(raw_input('gimme a number for something: '))
try and familiarize yourself with the basic built in functions, should be helpful.
http://docs.python.org/library/functions.html

Related

Python - integrate different variables to each user input from a for loop without using list

I need some help here, without using lists and strictly for loop, how do I implement my for loop to insert different variable with different user input?
def prompt():
total = int(input("How many books do you have in your basket? "))
return total
x = prompt()
book = 0
for i in range(x):
book = (float(input('What is the price of book number ' + str(i+1))))
""" book(i) = book """
""" I do not know how to implement the next code to put the book into a different variable to declare that e.g book = book1, book = book2 etc."""
Appreciate if someone can help me out. thanks!
You don't need to create variable here. Here is how you would do the sum, I'll leave the average to you:
def prompt():
total = int(input("How many books do you have in your basket? "))
return total
total_price = 0
N = prompt()
for i in range(N):
msg = 'What is the price of book number '+str(i+1)+' '
price = float(input(msg))
total_price += price
print("The total price is ", total_price)
Creating dynamic variables is generally a very bad practice, and is almost certainly not what your instructor is expecting you to do. Indeed, how would you know how to refer to them? Even if you did do that, it would require using much more arcane things than a list.

FinexApi : Keyprice should be a decimal number, e.g. "123.456"

I'm trying to edit a simple code for automated put and take action on bitfinex market using FinexApi.
I get this error while performing a subtraction
Keyprice should be a decimal number, e.g. "123.456"
this is the code
#!/usr/bin/env python
#Places a put and take above and below current market price
import FinexAPI
diff = 0.00000150 #The amount above or below market price you want
ticker = FinexAPI.ticker()
available = float(FinexAPI.balances()[2]["available"])
ask = float(ticker["ask"])
amount = 1 #Amount of XRP to place orders
marketPrice = ticker["last_price"]
buyPrice = float(marketPrice) - diff
sellPrice = float(marketPrice) + diff
print FinexAPI.place_order(str(amount), str(buyPrice), "buy", "exchange limit")
print FinexAPI.place_order(str(amount), str(sellPrice), "sell", "exchange limit")
I get error on:
print FinexAPI.place_order(str(amount), str(buyPrice), "buy", "exchange limit")
Keyprice should be a decimal number, e.g. "123.456"
Let's assume marketPrice is 0.00003500
I would like the code to make a buy order at marketPrice - diff ( 0.00003500 - 0.00000150 ) and a sell order at marketPrice + diff ( 0.00003500 + 0.00000150 )
but I keep getting the same error.
I tried to put the diff number inside " ", I tried using decimal, I tried a few bunch of things but I got other errors or no solution at all.
I'm quite noobish at python, can someone help me and tell me what am I doing wrong, or how to fix it?
Thank you.

The formula for "Two-for" price is 20% off the total price of two items. Prompt the user for each of the values and calculate the result

The following is what the output should look like:
Enter price 1: 10.0
Enter price 2: 20.0
The 'two-for' price is $24.0
The code I entered is:
price_one = float(input('Enter price 1: '))
print(price_one)
price_two = float(input('Enter price 2: '))
print(price_two)
two_for_price = (price_one + price_two)-((price_one + price_two)*(20/100))
print("The 'two-for' price is $",two_for_price)
(The inputs are 10.0 and 20.0 respectively.)
But the output I am getting is:
Enter price 1: 10.0
Enter price 2: 20.0
The 'two-for' price is $ 24.0
In the last line I need:
The 'two-for' price is $24.0
Please help me out!!
If i'm reading this correctly you just need to remove a space from your output.
Change your last line to this:
print("The 'two-for' price is ${0}".format(two_for_price))
Your underlying problem is that the print function behavior, given a list of items, is to print each item, separated by a space. This is often convenient for quick-and-dirty print-outs, but you want something more refined.
What you need to do is create a string with the proper spacing and then print that string out.
So you could do this:
print("The 'two-for' price is $" + str(two_for_price) + ".")
The problems are (a) that's kind of clumsy and unreadable and (b) it does not format properly, it's "$2.6" instead of "$2.60".
You can use either of two formatting mechanisms offered by Python, either explicit, like this:
print("The 'two-for' price is ${0}".format(two_for_price))
or implicit, like this
print("The 'two-for' price is $%f" % two_for_price)
Both of them look a little better, but the formatting errors are the same and worse ("$2.600000"!) respectively. Fortunately, both offer nice customizable formatting:
print("The 'two-for' price is ${0:.2f}".format(two_for_price))
and
print("The 'two-for' price is $%0.2f" % two_for_price)
Both of which look reasonably clean and display perfectly.

Python Car Sales Project having a bit of an issue

Hello I'm a college student whose just begun to take a computer programming class and have hit a bit of a snag I'm struggling to figure out. The program I'm supposed to create using python is a car sales program that calculates the weekly gross pay that is the total of made from the cars sold in the week. I have to input the number of cars sold and the value given back should be how much was made that week, this is the code I have written :
def main():
car_number = float(input('enter number cars sold'))
def calculate_total('car_number,price,commission'):
price = 32,500.00
commission = .025
total = car_number * price * commission
return total
main()
on the line 'def calculate_total('car_number, price, commission'): I am receiving a syntax error declaring 'formal parameter expected' How do I fix this issue?
That line should be
def calculate_total(car_number,price,commission):
You are instead writing a string there.
Also, as you are changing the values of price and commission it is better defined as
def calculate_total(car_number):
You have forgotten to call the function at the end
return calculate_total(car_number)
def calculate_total('car_number,price,commission'): this line should be
def calculate_total(car_number):

Python car sales code issue

Ok so, I have an assignment to make a carsales program which is suppose to calculate how much the salesperson will make in a week. I already know how much all the cars sell for and how much commission he makes. Here is my code:
def main():
print ('This program will compute the comission earned for the week based on your sales for the week.')
car_number = float(input('Enter number of cars sold :'))
def calculate_total(car_number,price,commission_rate):
price = 32,500.00
commission_rate = .025
calculate_total = car_number * price * commission_rate
return calculate_total(car_number)
print('The weekly gross pay is $',calculate_total)
main()
The program isn't working for some reason but I decided to submit it to my professor anyway. He then replied by saying that I wasn't asked to create a new function and that I have to delete it and work just in main. Can someone please tell me what this means?
Two things:
'Working in main' as your professor said means that you don't define any functions. All your code just sits in the file, without any def ... statements. I know that's probably not clear. Here's an example:
import os
print "Your current working directory is:"
print os.getcwd()
This kind of programming has more the feel of a 'script' - you're not defining parts of the program that you're going to use more than once, and you're not taking the trouble to break down what the program does into single-purpose functions.
Second, you've entered price in such a way that Python thinks you're creating a tuple of numbers instead of a single value.
price = 32,500.00 is interpreted by Python as creating a tuple, with values 32 and 500.00 in it. What you actually want is: price = 32500.00.
I broke down and completed the process for you.
print ('This program will compute the comission earned for the week based on your sales for the week.')
car_number = float(input('Enter number of cars sold :'))
price = 32500.00
commission_rate = .025
calculate_total = car_number * price * commission_rate
print('The weekly gross pay is $',calculate_total)
Sorry i did not saw the complete question before but anyway this is the correct answer without a function
The keywords try and except are for error handling. If you give as input something invalid let's say a letter instead of number will throw a message
(Could not convert input data to a float.)
def main():
print ('This program will compute the comission earned for the week based on your sales for the week.')
try:
#before: car_number = float(raw_input('Enter number of cars sold :'))
car_number = float(input('Enter number of cars sold :'))
except ValueError:
#before: print 'Could not convert input data to a float.'
print('Could not convert input data to a float.')
print('The weekly gross pay is ${}'.format(car_number * 32500.00 * 0.025 )))
main()
If you don't even want main() function here is the answer:
print ('This program will compute the comission earned for the week based on your sales for the week.')
try:
car_number = float(input('Enter number of cars sold :'))
except ValueError:
print('Could not convert input data to a float.')
print('The weekly gross pay is ${}'.format(car_number * 32500.00 * 0.025 )))

Categories