I am trying to print an output but I just can't figure out method.
keepAsking = True
author = ""
booktitle = ""
purchaseprice = float()
sellprice = float()
stockcount = int()
margin = float()
bookList = []
priceList = []
while keepAsking == True :
print("Enter Book Data: -")
author = input("Author: ")
if author == "" :
print("Blank Entry")
else :
booktitle = input("Title: ")
if booktitle == "" :
print("Blank Entry")
else :
purchaseprice = input("Purchase Price: ")
if purchaseprice == "" :
print("Incorrect Value")
else :
sellprice = input("Sell Price: ")
if sellprice == "" :
print("Incorrect Value")
else :
bookList.append(author)
bookList.append(booktitle)
if purchaseprice > sellprice :
bookList.remove(author)
bookList.remove(booktitle)
else :
priceList.append(purchaseprice)
priceList.append(sellprice)
stockcount = input("In Stock: ")
if stockcount == "" :
print("Incorrect Value")
else :
priceList.append(stockcount)
margin = ((float(sellprice)-float(purchaseprice))/float(purchaseprice))*100
marginround = round(margin,2)
priceList.append(marginround)
checkContinue = True
while checkContinue == True :
continues = input("Continue? [y/n]")
continuesLower = continues.lower()
if continues == "y" :
checkContinue = False
if continues == "n" :
checkContinue = False
keepAsking = False
and I am trying to get an output like this:
output
I don't really understand array and I have tried a few methods but failed to output it as the image shows. If possible, I would need some explanation too because I want to learn rather than get the answer straight out. So, if you have a solution, I might ask for more information on it too. (you don't have to explain it if you are not comfortable, but I just wish to learn more)
Thank you for attempting to help me. I am sorry if this is just a simple task but I am less than a beginner and trying to improve myself.
I am currently not outputting anything enter image description here
my print code is
for a in bookList :
counter = 0
while counter == len(bookList) :
print(bookList[0] + bookList[1])
print("Purchase Price: " + priceList[0] + "Sell Price: " + priceList[1] + "In Stock: " + priceList [2] + "Margin: " + priceList [3])
If you want to print multiple Book names and prices, etc you should put each one of them into a separate list in this case. (with append)
If you want to print them out you can do like this:
for i in range(0, len(booklist)):
print(author[i] + ' Purchase:' + purchase[i] + ' Sell:' + sell[0]))
... etc to the right format in wich purchase and sell are all lists. Don't forget to add spaces.
To check if the person actually input numbers you can use the method .isdigit()
if purchaseprice.isdigit() != true :
print("Incorrect Value, input numbers")
Related
I am trying to improve this program. I am working with Linux. I want to add a menu function where the user can pick an option and based on the option call the respective function, but the program is not working, when I run it in the Terminal it doesn't do anything and doesn't show any errors. Please, I need help to solve the problem and make the program works. Thanks!
Here's what I have so far, still there are some functions that need to develop:
#! /usr/bin/python3
import sys
def menu(self):
print ("""
1. Add an Expense
2. Remove an Expense
3. Add revenue
4. Remove Revenue
5. Exit
""")
option = input ("What would you like to do [Number Only]?")
if option == "1":
self.add_expense()
elif option == "2":
self.remove_expense()
elif option == "3":
self.add_revenue()
elif option == "4":
self.remove_revenue()
else:
self.reset_program()
self.close_program()
return option
def add_expense(self):
def __init__(self):
self.month_balance = 0
self.expenses = 0
self.expense_list = []
self.expense_name = []
self.month_balance_name = []
self.month_balance_list = []
self.prompt_income()
def month_balance_ask(self):
add_month_balance = input('Add monthly balance? [y/n]: ')
return add_month_balance
def month_balance_sum(self):
self.month_balance = sum(self.month_balance_list)
def expense_ask(self):
add_expense = input('Add expense? [y/n]: ')
return add_expense
def expense_sum(self):
self.expenses = sum(self.expense_list)
def month_balance_check(self):
if not self.month_balance_list:
print('Please enter at least one monthly balance. ')
self.prompt_month_balance()
def expense_check(self):
if not self.expense_list:
print('Please enter at least one expense. ')
self.prompt_expense()
def prompt_month_balance(self):
x = False
while not x:
result = self.month_balance_ask()
if result == 'y':
month_balance_input = int(input('Enter monthly balance. [Numbers Only]: '))
self.month_balance_list.append(month_balance_input)
month_balance_name = input('Enter monthly balance name. [Name Only]: ')
self.month_balance_name.append(month_balance_name)
else:
self.month_balance_check()
x = True
self.month_balance_sum()
name = [name for name in self.month_balance_name]
month_balance = [month_balance for month_balance in self.month_balance_list]
month_balancedict = dict(zip(name, month_balance))
for k in incomedict:
print(k + ': ', '$' + str(month_balancedict[k]))
print('Total user monthly balance: ', '$' + str(self.month_balance))
self.prompt_expense()
def prompt_expense(self):
x = False
while not x:
result = self.expense_ask()
if result == 'y':
expense_input = int(input('Enter expense amount. [Numbers Only]: '))
self.expense_list.append(expense_input)
expense_name = input('Enter expense name. [Name Only]: ')
self.expense_name.append(expense_name)
else:
self.expense_check()
x = True
self.expense_sum()
name = [name for name in self.expense_name]
expense = [income for income in self.expense_list]
expensedict = dict(zip(name, expense))
for k in expensedict:
print(k + ': ', '$' + str(expensedict[k]))
print('Total user expenses: ', '$' + str(self.expenses))
self.added_expense()
def added_expense(self):
expenseadded = self.month_balance - self.expenses
if expenseadded < 0:
print('You are in the negative, you have a deficit of ' + '$' + str(expenseadded))
if expenseadded == 0:
print('You have broken even, you are spending exactly as much as you make.')
if expenseadded > 0:
print('You are in the positive, you have a surplus of ' + '$' + str(expenseadded))
another = input('Would you like to run another analysis? [y/n]: ')
if another == 'y':
self.menu()
else:
self.reset_program()
self.close_program()
def remove_expense(self):
print("code goes here")
def add_revenue(self):
print("code goes here")
def remove_revenue(self):
print("code goes here")
def reset_program(self):
self.month_balance = 0
self.expenses = 0
del self.expense_list[0:]
del self.expense_name[0:]
del self.month_balance_name[0:]
del self.month_balance_list[0:]
self.prompt_month_balance()
def close_program(self):
print('Exiting Program.')
sys.exit(0)
So I'm trying to make a calculator but when i do plus (also with other things but for example) it does work but after the outcome comes it asks for number 2 again, I just want the code to start again.
this is the plus piece of the code:
q = input(str("Wil je de bewerkingsteken legende zien? (j/n): "))
if q == "J" or q == "j" :
print ("\nplus = + ")
print ("min = -")
print ("maal = X")
print ("delen door = :")
print ("quadrateren = Q")
print ("tot de kracht van = P")
print ("Worteltrekken = W")
print ("Procent = %")
num1 = float(input("\n Nummer 1: "))
bew = input("\n Bewerkingsteken: ")
num1_word = (str(num1))
if bew == "+" :
plus_num2 = input(float("\nNummer 2: "))
plus_num2_con = (str(plus_num2))
plus_out = (num1 + plus_num2)
plus_out1 = (str(plus_out))
print ("\n" + num1_con +" + " + num2_con + " = " + plus_out1)
First, you write the input wrong for plus_num2. Try this;
plus_num2 = float(input("\nNummer 2: "))
Second, you define the number's name different from last print function. Try This;
print ("\n" + num1_word +" + " + plus_num2_con + " = " + plus_out1)
Third, if you want to start the code again you can add while True on first line.
First time posting so apologizes if formatting is incorrect. My program has 2 lists for now. I I will be adding 4 more after solving this initial issue. One for and item the user selects, and a second with prices for the each item. I have written a code for user selection which runs.
My issue comes with the code for the program associating the item selected with the price list. My first if statement registers item_price as a float, which I gives me what I need. Item_price in the following elif statements are being seen as a list. How can I change them to a float so that the price prints instead of the list?
food=["burger", "pizza", "hotdogs", "tacos"]
food_price=[8.99, 22.50, 3.50, 6.00]
def get_menu_item(item,item_list,):
phrase = "Would you like" + item + "? [y/n] "
response = input(phrase)
if response == "y":
print("Here are your menu options:", item_list)
idx = input("please enter the item you would like from our menu[1,2,3,4]: ")
idx = int(idx) -1
return item_list[idx]
#if user selects [n]
else:
return (None)
#item price function
def get_item_price(item_price,item,item_list):
if item == item_list[0]:
item_price = item_price[0]
elif item == item_list[1]:
item_price == item_price[1]
elif item == item_list[2]:
item_price == item_price[2]
elif item == item_list[3]:
item_price == item_price[3]
return item_price
entree_choice = get_menu_item(" dinner",food)
print('You have selected: ' + entree_choice + ".")
entree_price = get_item_price(food_price,entree_choice,food)
print(entree_price)
I answered this for myself shortly after. I was using == instead of = for all of my elif statements. I feel dumb but writing this out helped me solve it.
You could simplify things further by using a dictionary to store your data :
food_price = {"burger":8.99, "pizza":22.50, "hotdogs":3.50, "tacos":6.00}
def get_menu_item(item,item_list,):
phrase = "Would you like" + item + "? [y/n] "
response = input(phrase)
if response == "y":
print("Here are your menu options:", item_list)
idx = input("please enter the item you would like from our menu[1,2,3,4]: ")
idx = int(idx) -1
return item_list[idx]
else:
return (None)
entree_choice = get_menu_item(" dinner",food)
print('You have selected: ' + entree_choice + ".")
# if entree_choice is not found in the food_price dictionary, the output becomes the string "Entree choice not available."
entree_price = food_price.get(entree_choice, "Entree choice not available.")
print(entree_price)
Trying to figure out how to work a list of user input integers into separate categories and adding those categories together, and I'm stuck. This is what I have so far:
def main():
again = 'y'
while again == 'y':
pos_values = []
neg_values = []
value = int(input("Please enter value: "))
if value > 0:
pos_values.append(value)
print('Would you like to add another value?')
again = input('y = yes; n = no: ')
elif value < 0:
neg_values.append(value)
print('Would you like to add another value?')
again = input('y = yes; n = no: ')
else:
print(sum.pos_values)
print(sum.neg_values)
print('Would you like to add another value?')
again = input('y = yes; n = no: ')
total = 0
all_values = neg_values + pos_values
print[all_values]
print(total + pos_values)
print(total + neg_values)
main()
I'm just a first year student with no prior experience, so please be gentle!
Once you fix the logic error pointed out by Mike Scotty, the other problems are really just syntax errors. sum.pos_values will give you AttributeError: 'builtin_function_or_method' object has no attribute 'pos_values' (because sum is a built-in function and so needs () not .); and print[all_values] will give you a syntax error (because print is also a built-in function and so needs () not []). Your original code doesn't store zeroes in either list: I haven't changed that. And the output format is a guess on my part.
def main():
again = 'y'
pos_values = []
neg_values = []
while again == 'y':
value = int(input("Please enter value: "))
if value > 0:
pos_values.append(value)
elif value < 0:
neg_values.append(value)
else: #edit: terminate also on 0 input
break
print('Would you like to add another value?')
again = input('y = yes; n = no: ')
all_values = neg_values + pos_values
print(sum(all_values),all_values)
print(sum(pos_values),pos_values)
print(sum(neg_values),neg_values)
I'm trying to get this problem fixed. I'm creating a program which stores the score in a spreadsheet but when it does, it does not write the score and name in different cell. I have tried adding the column string/row string but always getting error, some guide and help will be appreciated.
So far this is what I have done:
!(http://postimg.org/image/6zn9l43bj/)!
I tried to get a heading saying name and the users name below in each cell and same with score and need some starting point/help
ClassA = open('classa.csv', 'w')
ClassB = open('classb.csv', 'w')
ClassC = open('classc.csv', 'w')
start = True
while start:
user =(input("What is your name?"))
form =(input("Which Group are you in A/B or C ")).lower()
import re
import random
from random import randint
score = 0
for i in range(3):
first_num = random.randint(1,10)
second_num = random.randint(1,10)
choice = (first_num+second_num)
if choice == first_num+second_num:
print ("Question (%d)" % (i+1))
print (first_num)
print("Add (+)")
print(second_num)
check = True
while check:
answer = (input('enter the answer: '))
if not (re.match('-?[0-9]\d*(\.\d+)?$', answer)):
print("Only input numbers")
else:
check = False
answer = int(answer)
if answer == (choice):
print("It's correct!")
score +=1
else:
print("It's wrong!")
print ("The correct answer is: ", choice)
print('')
print(user)
if form == 'a':
ClassA.write("Name: "+str(user) + ' ' + "Score: "+str(score)+"/10" + '\n')
elif form == 'b':
ClassB.write("Name: "+str(user) + ' ' + "Score: "+str(score)+"/10" + '\n')
elif form == 'c':
ClassC.write("Name: "+str(user) + ' ' + "Score: "+str(score)+"/10" + '\n')
yesorno = input("Restart?, Y or N ").lower()
if yesorno == 'y':
start = True
elif yesorno == 'n':
start = False
ClassA.close()
ClassB.close()
ClassC.close()
Thanks
A bit of background: CSV stands for Comma Separated Values, oddly enough Values are quite often separated by semicolons in CSV files and, in fact, (I think) Excel won't recognise columns if you use commas, but it will if you use semicolons. Edit: As pointed out in the comments, this probably depends on regional settings, if in your country the decimal point is usually a comma (e.g. most of Europe) use ;, if it's usually a point use , as separator.
So, back to your question: you are not separating your values, use this instead (notice the semicolon):
ClassA.write("Name: "+str(user) + '; ' + "Score: "+str(score)+"/10" + '\n')
I wouldn't recommend writing the Name: and Score: prefixes either, I would go with a header row (Name; Score; Max Score) and something like this:
ClassA.write("{0}; {1}; {2}\n".format(user, score, max_score))
See also: str.format