While loop not ending - python

def getStocks():
stockNames = []
stockPrices = []
done = 0
while done != 1:
stock = input('Enter Stock symbol: ')
if stock == 'done':
done = 1
else:
price = int(input('Enter Price of Stock: '))
print("")
stockNames.append(stock)
stockPrices.append(price)
return stockNames, stockPrices
The issue is that "Enter Stock symbol: " appears even after the user types 'done', how can I get the infinite loop to terminate at this point? I tried using break but it did not provide the results I was looking for

instead of input use raw_input it will fix the problem
def getStocks():
stockNames = []
stockPrices = []
done = 0
while done != 1:
stock = raw_input('Enter Stock symbol: ')
if stock == 'done':
done = 1
else:
price = int(input('Enter Price of Stock: '))
print("")
stockNames.append(stock)
stockPrices.append(price)
return stockNames, stockPrices
python version: 2.7+

you probably want raw_input(), as input() will actually try to evaluate the expression it gets back.

Related

Im trying to generate multiple phone numbers into a list

Im able too generate a number properly how I want but I want too make a custom input so the user can generate an exact amount of numbers not just a set amount of numbers.
if menu == "1":
code = input("")
if code == "":
countrycode = input("Please Enter Country Code: ")
areacode = input("Enter area Code: ")
city = (random.randint(200,999))
last = (random.randint(1000,9999))
number = ("+"+countrycode+areacode+str(city)+str(last))
print(number)
To do this, you can use a while True loop that takes in input every single time they want to input a phone number. If they input something that you don't want, break out of the while True loop. Otherwise, you take in the phone number. To hold the set of numbers, just add them to arrays.
Edited off your code:
if menu == "1":
while(True):
code = input("")
if code == "":
countrycode = input("Please Enter Country Code: ")
areacode = input("Enter area Code: ")
city = (random.randint(200,999))
last = (random.randint(1000,9999))
number = ("+"+countrycode+areacode+str(city)+str(last))
print(number)
else:
break
I'm not sure I fully understand your question, but i'll give it a shot:
import random
class Data():
def __init__(self) -> None:
country_code = ""
area_code = ""
city = ""
last = ""
def __str__(self):
return f"+{self.country_code}-{self.area_code}-{self.city}-{self.last}"
def main():
number_of_entries = int(input("How Many Entries: "))
list_of_information = []
for _ in range(0, number_of_entries):
new_data = Data()
new_data.country_code = input("Please Enter Country Code: ")
new_data.area_code = input("Enter area Code: ")
new_data.city = str(random.randint(200,999))
new_data.last = str(random.randint(1000,9999))
list_of_information.append(new_data)
for entry in list_of_information:
print(entry)
if __name__ == '__main__':
main()
Sample:
How Many Entries: 2
Please Enter Country Code: 1
Enter area Code: 604
Please Enter Country Code: 1
Enter area Code: 30
+1-604-394-5276
+1-30-840-8783

How do I loop an if statement until needed and then stop

I want to loop my driver code and, once done, ask the user if they want to convert another currency into MYR. Everytime through the loop, save the returnedamount to an array and, once the user has no more currencies, they need to convert. The program will add the varibles in the array together to produce the sum and print that. If required, turn that sum into another currency.
class Currency_convertor:
rates = {}
def __init__(self, url):
data = requests.get(url).json()
self.rates = data["rates"]
def convert(self, from_currency, to_currency, amount):
initial_amount = amount
if from_currency != 'EUR' :
amount = amount / self.rates[from_currency]
amount = round(amount * self.rates[to_currency], 2)
print('{} {} = {} {}'.format(initial_amount, from_currency, amount, to_currency))
return amount
Driver code
if __name__ == "__main__":
YOUR_ACCESS_KEY = ''
url = 'https://api.exchangerate-api.com/v4/latest/USD'
c = Currency_convertor(url)
from_country = input("From Country: ")
to_country = input("TO Country: ")
amount = int(input("Amount: "))
returnedamount=c.convert(from_country, to_country, amount)
Use a while statement.
Example:
x = 0
while x < 10:
# This will keep running until the condition is no longer True
print(x)
x += 1
# Then run any final stuff outside of the loop
print('Finished looping')
Use "While" Instead of "if"

While loop not working properly when condition is met

I am trying to append items to a list, and when I type the word "quit" the loop should stop, and then print the items I have on my list, but the loop continues and still asks me the second question on the loop, which I think should not be happening.
itemName = ''
itemPrice = '0.0'
while itemName != 'quit'.lower().strip():
itemName = input('What item would you like to add?')
items.append(itemName + ' $' + itemPrice)
itemPrice = input(f'What is the price of {itemName}?')
for item in items[:-1]:
print(item)
I see one problem, you have your .lower().strip on the wrong side.
Also, I would suggest using break so that your code won't ask for a price if quit is inputted.
items=[]
itemName = ''
itemPrice = '0.0'
while True:
itemName = input('What item would you like to add?')
if itemName.lower().strip() == 'quit':
break
items.append(itemName + ' $' + itemPrice)
itemPrice = input(f'What is the price of {itemName}?')
for item in items[:-1]:
print(item)
The code only checks if you wrote quit after it asks both questions. Also, you should put your .lower().strip() after the input() function. Your code always lowercases and strips the string 'quit'. You can put an if statement after the first question with a break to prevent your code from asking you the second question after you typed 'quit' for the first question.
Try to study this.
items = [] # storage
totalPrice = 0.0
while True:
itemName = input('What item would you like to add? ')
if itemName.lower() == 'quit':
break
itemPrice = input(f'What is the price of {itemName}? ') # ask the price before saving the item
if itemPrice.lower() == 'quit':
break
totalPrice += float(itemPrice) # convert str to float
items.append(f'{itemName} $ {itemPrice}') # Save to storage
print('items:')
for item in items:
print(item)
print()
print(f'total price: $ {totalPrice}')
Output
What item would you like to add? shoes
What is the price of shoes? 600.75
What item would you like to add? bag
What is the price of bag? 120.99
What item would you like to add? quit
items:
shoes $ 600.75
bag $ 120.99
total price: $ 721.74

How can i remove " " and . from a data in a list

So i have this college python project that asks me to make a program to manage an inventory, my question basically is that whenever I try to convert the price and the quantity again to floats this exception rase, so how can I convert them so I can make further process on them?
note that I tried to use .strip but it didn't work
this is the error:
float_price = float(i)
ValueError: could not convert string to float: '.'
this is the code that I have issues with:
from tabulate import tabulate
def read_data():
file = open("inventory.txt", "r")
list_of_lists = []
for line in file:
stripped_line = line.strip()
line_list = stripped_line.split()
list_of_lists.append(line_list)
updated_list = list_of_lists[1:]
file.close()
return updated_list
def list_data():
updated_list = read_data()
index = 0
price = 0
quantity = 0
j = 0
while j < len(updated_list):
for i in updated_list[1][4]:
float_price = float(i)
price += float_price
print(price)
header = ['MAKE', 'MODEL', 'PART ID', 'PART NAME', 'PRICE', 'QUANTITY']
print(tabulate(updated_list, headers=header))
list_data()
this is the code to add data to the file:
def input_parts():
#Taking the parts input from the user
try:
make = input("Enter the make: ")
model = input("Enter the model: ")
part_id = input("Enter part_id: ")
part_name = input("Enter part name: ")
price = float(input("Enter price:QR "))
quantity = int(input("Enter quantity: "))
except ValueError:
print("BOTH PRICE AND QUANTITY CAN NOT BE LETTERS, PLEASE RE-ENTER THE RIGHT DATA")
else:
#transferring both price and quantitiy to strings
price = str(price)
quantity = str(quantity)
list = ['\n' + make,model,part_id,part_name,price,quantity]
return list
#This function is to save the parts information to a file
def add_parts():
#Assignning this sentinal to make the loop repeat if the user didn't want to save
sentinal = True
while sentinal is True:
#Assigning the values of the inputs function to a variable
parts = input_parts()
#Validating user's unput
try:
#Asking the user if he wants to save the information to the file
save = input("Save? (Y/N) or Q to quit ")
except TypeError:
print("YOU CANNOT SAVE WRONG DATA IN THE FILE PLEASE RE-ENTER YOUR DATA")
else:
pass
#A boleen function to import the data to the file if the boleen is true
if save.lower() == 'y':
outfile = open('inventory.txt',"a")
#Validating user's input
try:
#Using a for loop to print the information in the file
for i in parts:
outfile.write(i+ '\t')
except TypeError:
print("YOU CAN NOT SAVE WRONG DATA FILES!!!")
break
else:
pass
outfile.close
print("....Record saved.")
sentinal = False
#Using an elif statment to enable the user to re input his data
elif save.lower() == 'n':
sentinal = True
#Using an elif statment to quit if the user wants to
elif save.lower() == 'q':
break
#Using else statment to tell the user no input a valid choice
else:
print("PLEASE ENTER (Y/N) IF YOU WANT TO SAVE!!!!")
print("YOUR DATA HAS NOT BEEN SAVED")
print("PLEASE RE-ENTER YOUR DATA AND TRY AGAIN.")
sentinal = True
add_parts()
as error message indicates '.' is string and it cannot be converted to float so raises error.. it depends what you want to do with such situation you can use try except as.
from tabulate import tabulate
def read_data():
file = open("inventory.txt", "r")
list_of_lists = []
for line in file:
stripped_line = line.strip()
line_list = stripped_line.split()
list_of_lists.append(line_list)
updated_list = list_of_lists[1:]
file.close()
return updated_list
def list_data():
updated_list = read_data()
index = 0
price = 0
quantity = 0
j = 0
while j < len(updated_list):
for i in updated_list[1][4]:
try:
float_price = float(i)
price += float_price
except ValueError as e:
print('Value Error')
print(price)
header = ['MAKE', 'MODEL', 'PART ID', 'PART NAME', 'PRICE', 'QUANTITY']
print(tabulate(updated_list, headers=header))
list_data()

Getting a Value Error When I Shouldn't Be

I'm trying to have my input move on when enter is pushed on a line with only spaces or just a blank, it doesn't work though it gives me a value error once before it gives me the proper return, which in turn seems to append an extra value to my array and screws over the entire program.
import math
def getItems():
quitNow = False
while not quitNow:
prepTotal = []
paintTotal = []
priceTotal1 = []
priceTotal1d = []
priceTotal2 = []
priceTotal2d = []
names = []
loopQuit = False
index = 1
while not loopQuit:
ans = raw_input("Enter a Name and press Enter to Continue\nEnter \"Q\" to Quit and get the Full Price: ")
if(ans.lower() != "q"):
innerLoopQuit = False
names.append(ans)
print "\nPlease enter your prep hours for " + names[index-1] + ": "
while not innerLoopQuit:
try:
inp = raw_input()
if(inp == ""):
innerLoopQuit = True
else:
float(inp)
prepTotal.append(float(raw_input()))
except ValueError:
print "Please enter a valid number."
You're calling raw_input() again in your else clause. Also, float(inp) doesn't really do anything if you don't assign it anywhere. prepTotal.append(float(inp)) is what you want to do.

Categories

Resources