Doing my homework rn and a bit stuck, why does the code execute "else" even thought the "if" has been satisfied? Ignore the sloppy code, I'm very new :/
order1 = input("What would you like to order?: \n \n" + "1: " + orderBurger + "\n" + "2: " + orderFries + "\n" + "3: " + orderDrink + "\n" + "\nAnswer = ")
while order == True:
if order1 == 1:
print("You have selected to order 1: " + orderBurger)
elif order1 == 2:
print("You have selected to order 1: " + orderFries)
elif order1 == 3:
print("You have selected to order 1: " + orderDrink)
else:
print("Invalid Input")
check = input("Is this your final item?:" + "1: " + q1 + "2: " + q2 + "Answer = ")
if check == 1:
print("Your items have been added to the basket")
break
elif check == 2:
check
elif check == 3:
check
else:
print("Invalid input")
This is the output
If you use type(order1), you'll see if your answer is a string or an int. If it's a string (and I think it is), you can convert it into int using int(order1), or replace your code by if order1 == '1'
Indentation is very important in Python. Based on how the indentations are implemented, the code blocks for conditions get executed.
A misplaced indent can lead to unexpected execution of a code block.
Here is a working demo of the ordering program
# File name: order-demo.py
moreItems = True
while (moreItems == True):
order = input("\n What would you like to order?\n"
+ " 1: Burger\n 2: Fries\n 3: Drink\n Answer = ")
if ((order == "1") or (order == "2") or (order == "3")):
print("You have selected to order " + order)
print("Your item has been added to the basket.\n")
else:
print("Invalid Input")
check = input("Is this your final item?: \n 1: Yes \n 2: No \n Answer = ")
if check == "1":
print("\n Thank you. Please proceed to checkout.")
moreItems = False
elif check == "2":
print("Please continue your shopping")
else:
print("Invalid input")
Output
$ python3 order-demo.py
What would you like to order?
1: Burger
2: Fries
3: Drink
Answer = 1
You have selected to order 1
Your item has been added to the basket.
Is this your final item?:
1: Yes
2: No
Answer = 2
Please continue your shopping
What would you like to order?
1: Burger
2: Fries
3: Drink
Answer = 2
You have selected to order 2
Your item has been added to the basket.
Is this your final item?:
1: Yes
2: No
Answer = 1
Thank you. Please proceed to checkout.
$
replace first line with this :
order1 = int( input("What would you like to order?: \n \n" + "1: " + orderBurger + "\n" + "2: " + orderFries + "\n" + "3: " + orderDrink + "\n" + "\nAnswer = ") )
Related
So, i'm new to python and trying to learn it, i've watched some clips on youtube and came up with this, but the last part to check in the quantity is or is not in the list range is not working....
print ("Hello, my name is Dave, welcome to our coffe shop!!")
name = input ("What is your name?\n")
print("Hello " + name + ", thank you for comming to our coffe shop!")
print ("What can i get you ?")
menu = str("caffe latte, " + "tea, " + "black coffe")
menu_choice = ["caffe latte","tea","black coffe"]
choice1 = input() # anything
print ("This is our menu:")
print (menu)
unavailable = True
# order loop for the coffe
while unavailable:
order = input ()
if order in menu_choice:
unavailable = False
print ("And how many " + order + " would you like?")
else:
print ("Sorry we dont have " + order + ", this is our menu :\n" + menu)
if order == "caffe latte":
price = 13
elif order == "tea":
price = 9
elif order == "black coffe":
price = 15
#quantity loop
list(range(1, 10))
#here is the problem i'm having RN, the part with if not in in list is skipped
choice_number = True
while choice_number:
quantity = input()
total = price * int(quantity)
if quantity not in {list} :
choice_number = False
if quantity == "1" :
print ("Alright " + name, "that will be " + str(total) +"$,", "a", order + " comming at you!")
elif quantity >= "2" :
print ("Alright " + name, "that will be " + str(total) +"$,", quantity + " " + order + " comming at you!")
else:
print ("Quantity invalid, please select a number from 1 to 10.")
Assign this list(range(1, 10)) in a variable like qty_lst = list(range(1, 10)).
or you can simnply write:
if quantity not in list(range(1, 10)):
quantity = input("Enter Quantity")
total = price * int(quantity)
if quantity not in range(1,10) :
print ("Quantity invalid, please select a number from 1 to 10.")
else:
if quantity == "1":
print("Alright " + name, "that will be " + str(total) + "$,", "a", order + " comming at you!")
elif quantity >= "2":
print("Alright " + name, "that will be " + str(total) + "$,", quantity + " " + order + " comming at you!")
I would recommend getting rid of the listed range and just doing it like this, also you don't need a while True loop its not really needed
if quantity < 1 or quantity > 10:
# not in range
else:
# in range
Dont use if ... in range(), i'm not sure about this, but i think that doing so, python will not know that the sequence is in order and will check your value against all the sequence.
If i'm wrong, let's say i learned something :D
I can't figure out how to make this code give me the output I need. It is supposed to ask the user where they want to go on vacation, and then display the location they have chosen.
print("Congratulations! You have won an all-inclusive vacation!" + '\n')
input("Please enter your first and last name" + '\n')
print("Please choose where would you like to go on vacation?" + '\n'
+ "A. The Bermuda Triangle" + '\n'
+ "B. Space" + '\n'
+ "C. Antarctica" + '\n')
def choose_location():
if choose_location == "A":
print("You chose The Bermuda Triangle")
elif choose_location == "B":
print("You chose Space")
elif choose_location == "C":
print("You chose Antarctica")
choose_location()
not sure why you need the function
your code has a few problems.
first, don't use the same function name as the variable name.
second, instead of print, it should be input.
third, you need to save inputs to variables so you can use them.
but you need to use the input instead of print, and save the input to a variable,
print("Congratulations! You have won an all-inclusive vacation!" + '\n')
name = input("Please enter your first and last name" + '\n')
def choose_location():
location = input("Please choose where would you like to go on vacation?" + '\n'
+ "A. The Bermuda Triangle" + '\n'
+ "B. Space" + '\n'
+ "C. Antarctica" + '\n')
if location == "A":
print("You chose The Bermuda Triangle")
elif location == "B":
print("You chose Space")
elif location == "C":
print("You chose Antarctica")
choose_location()
or even a version that make-use of the function.
Notice that I added .upper() so even if the user enters a small letter it will still work
def choose_location(location):
location = location.upper()
if location == "A":
print("You chose The Bermuda Triangle")
elif location == "B":
print("You chose Space")
elif location == "C":
print("You chose Antarctica")
print("Congratulations! You have won an all-inclusive vacation!" + '\n')
name = input("Please enter your first and last name" + '\n')
choose_location(input("Please choose where would you like to go on vacation?" + '\n'
+ "A. The Bermuda Triangle" + '\n'
+ "B. Space" + '\n'
+ "C. Antarctica" + '\n'))
I'm working on a project that will allow me to document my earnings/spending's more efficiently, and I cannot seem to find how to find the latest column within a given text file, keep in mind the code is a prototype, as I only started working on it about an hour ago.
f = open('Money.txt','a')
while True:
while True:
OP = input("Operator: ")
if OP == "+" or OP == "-":
break
else:
print("Invalid Operator, please try again.\n\n")
while True:
try:
MA = int(input("Money amount: "))
break
except ValueError:
print("Numeric value only.\n\n")
while True:
if OP == "+":
MV = input("Where you recived the money: ")
break
elif OP == "-":
MV = input("Where you spent the money: ")
break
while True:
C = input('\n\nIs "' + OP + "/" + str(MA) + "/" + MV + '" correct: ')
if C.lower() == "yes":
break
elif C.lower() == "no":
print("Restarting...\n\n")
break
else:
print("Invalid response, try again.\n\n")
if C.lower() == "yes":
break
elif C.lower() == "no":
continue
fs = OP + " $" + str(MA) + " / " + MV
f.write('\n' + fs)
f.close()
print("Values written.")
# "abcde!mdam!dskm".split("/", 2) - basic idea of the code ill use after i figure out how to get latest column from text file
I'm not too great at programming, so if you see a blatant way to improve my code, go ahead and share it, any help will be appriciated!
I figured it out, its probably not the most efficient method but it works:
fc = f.readlines()
l = -1
for line in fc:
l += 1
You can then use "l" to slice your list and do whatever you need to do to it.
Note: You need to change the "f = open('Money2.txt','a')" to "f = open('Money2.txt','r+')"
I have a text file that has results listed like this:
Welcome to your results
The result of 50+25=75
The result of 60+25=85
The result of 70+25=95
The result of 80+25=105
I need python to read the file and pull out the numbers to the left of the "=" and add them up. I have no idea how to get this to work.
# take input from the user
print("Select operation.")
print("1.Display The Content of the result file")
print("2.Add two numbers")
print("3.Subtract two numbers")
print("4.Multiply two numbers")
print("5.Divide two numbers")
print("6.Append results to file")
print("7.Display Total of inputs")
print("8.Display Average of inputs")
print("9.Exit")
choice = input("Select an option(1-9):")
if choice == 1:
file = open('results.txt', 'r')
print file.read()
elif choice >= 2 and choice <= 5:
l_range = int(input("Enter your Lower range: "))
h_range = int(input("Enter your Higher range: "))
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if num1 < l_range:
print "The input values are out side the input ranges \n Please check the numbers and try again"
elif num2 > h_range:
print "The input values are out side the input ranges \n Please check the numbers and try again"
else:
if choice == 2:
print "The result of", num1,"+", num2,"=", add(num1,num2)
resultstr = "The result of " + str(num1) + "+" + str(num2) + "=" + str(add(num1,num2))
elif choice == 3:
print "The result of", num1,"-",num2,"=", subtract(num1,num2)
resultstr = "The result of " + str(num1) + "-" + str(num2) + "=" + str(subtract(num1,num2))
elif choice == 4:
print "The result of", num1,"*", num2,"=", multiply(num1,num2)
resultstr = "The result of " + str(num1) + "*" + str(num2) + "=" + str(multiply(num1,num2))
elif choice == 5:
print "The result of", num1,"/", num2, "=", divide(num1,num2)
resultstr = "The result of " + str(num1) + "/" + str(num2) + "=" + str(divide(num1,num2))
if num2 == 0:
print "The result of", num1,"/", num2, "=", "You can't divide by zero!"
elif choice == 6:
print("The results have been appended to the file")
file = open('results.txt', 'a')
file.write(resultstr + "\n")
file.close()
elif choice == 7:
print ("Display total inputs")
elif choice == 8:
print ("Display average of total inputs")
elif choice == 9:
print ("Goodbye!")
else:
print("Invalid input")
lp_input = raw_input("Do you want to perform another action? Y/N:")
if lp_input == 'n':
print("Goodbye!")
From what I understand from the question, a simple regex match would solve the problem. You may do it like so:
Read the file line by line.
Make a regex pattern like so, to get the data from the string:
>>> pattern = "The result of (\d+?)[+-/*](\d+?)=(\d+).*"
Say if a line from the file is stored in the variable result:
>>> result = "The result of 25+50=75"
import the re library and use the match function like so which gives you the data from the string:
>>> s = re.match(pattern, result)
>>> print s.groups()
('25', '50', '75')
You can then get the numbers from this tuple and do any operation with it. Change the regex to suit your needs, but given the contents of the file at the start, this should be fine.
I need this program to print out the number of guesses you got right and wrong. I have a dictionary (called ccdict) of cities and countries, e.g. "United Kingdom":"London". This is the code:
def choices (Correct):
list=[Correct]
f=0
cities=ccdict.values()
while f + 1<5:
f=f+1
list.append(cities[random.randint(0, len(cities))])
list.sort()
return list
countries = ccdict.keys()
randcountry = countries[random.randint(0, len(countries))]
print "What is the capital of " + randcountry + "?"
print "If you want to stop this game, type 'exit'"
randlist = choices(ccdict[randcountry])
for i in range(0,5):
print str(i+1) + " - " + randlist[i]
input=raw_input("Give me the number of the city that you think is the capital of " + randcountry + " ")
if input == "exit":
print "Now exiting game!" + sys.exit()
elif randlist[int(input)-1] == ccdict[randcountry]:
print "Correct"
else:
print "WRONG! The capital of " + randcountry + " is " + ccdict[randcountry]
Move your int() until after your if test:
input = raw_input("Give me the number of the city that you think is the capital of " + randcountry + " ")
if input == "exit":
print "Now exiting game!"
sys.exit()
elif randlist[int(input) - 1] == ccdict[randcountry]:
print "Correct"
Note how the above version only converts input to an integer at the last minute.