Python Invalid Syntax: Print and Elif statements [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I am really new to Python and programming (2 days to be exact). I was messing around in idle trying to come up with a more complicated process than just print "Hello world." I was wondering if any of you could tell me why it is marking my print and elif statements invalid. I am using Python 2.7.10, thanks!
A = raw_input("Do you live in the US or Canada?")
if A == " US" or "Canada":
print "Welcome!"
else:
print "We're sorry, but your country is currently not supported!"
B = int(raw_input("How much is your package?")
if B >= 25
print "Your shipping is $4.00"
elif B >= 50
print "Your shipping is $8.00"
else:
print "Congrats, your shipping is free!"

Probably the first thing you notice about python is that consistent indentation is not just a good idea, it is mandatory. Experienced programmers, whether they write Python or not, always do that anyway so it is no big deal. Use spaces (4 is the norm) and avoid tabs - change your editor to replace a tab with 4 spaces.
It is a bad idea to use float on money amounts because of rounding. Better to use a large type, like Decimal, or store the amount as an int in cents, then insert a decimal point when you display. For simplicity I have stuck with using float, but be warned.
You have a number of logic errors in your code, as well as issues with style. Programming style is not just about what looks nice, it is whether you can understand your code later, when you come back to it.
Style points:
Don't use UPPERCASE for variables. By convention UPPERCASE is reserved for constants
Use meaningful variable names, not A and B
Here is a corrected program, with comments. Please read the comments! :
# This is a comment, it is ignored by python
# This is used later on by sys.exit()
import sys
# Logically the user would enter "Yes" or "No" to this quesion,
# not US or Canada!
ans = raw_input("Do you live in the US or Canada? ") # Notice the space after ?
# Note how the condition has been expanded
if ans == "US" or ans == "Canada":
print "Welcome!"
else:
print "We're sorry, but your country is currently not supported!"
# Now what? Your program just carried on. This will stop it
sys.exit()
# I'm using a floating point number for simplicity
amount = float(raw_input("How much is your package? "))
# I changed this around, since 50 is also >= 25!
# However, this is strange. Usually the more you spend the LESS the shipping!
# You were missing the : after the condition
if amount >= 50:
print "Your shipping is $8.00"
amount += 8 # This adds 8 to the amount
elif amount >= 25:
print "Your shipping is $4.00"
amount += 4 # This adds 4 to the amount
else:
print "Congrats, your shipping is free!"
# print the amount showing 2 decimal places, rounding
print "Amount to pay: $%.2f" % (amount)
You have plenty more to do. Maybe cope with the user entering lower or mixed case letters for the country name - and ask yourself if the question is logical to the user.
Later you might want to have a list of valid countries, and use in to test if the user entered a valid country. Then expand it to use a dictionary, indicating currency symbols, shipping amounts, and currency conversion rates for each country.
Enjoy Python!

Fixed it for you :). Take a look to see what's different, and you will learn, young padawan:
A = raw_input("Do you live in the US or Canada?")
if A == "US" or A == "Canada":
print "Welcome!"
else:
print "We're sorry, but your country is currently not supported!"
B = float(raw_input("How much is your package?"))
if B >= 25:
print "Your shipping is $4.00"
elif B >= 50:
print "Your shipping is $8.00"
else:
print "Congrats, your shipping is free!"

Related

I have a problem with a math quiz in python

I am very new at python and i just wanted to make a pprogramm with a question how much is 23*10? and if the user answers 230 it will print true but if not it would print false and i dont know how to ... this is my first attempt
Question = input("How much is 23 * 10? ") if Question == "230":print("True")
It is pretty much what you made, lacking indentation and the else. Also, I'm adding int() before input() because otherwise, the value provided will be considered as a string instead of a number. It doesn't make much difference if you are then comparing it with a string "230" but I just thought I'll change it a bit to show you another perspective.
question = int(input("How much is 23 * 10? "))
if question == 230:
print("True")
else:
print("False")
As I explained before, if you do not wish to use int then you must compare the value to a string:
question = input("How much is 23 * 10? ")
if question == "230":
print("True")
else:
print("False")

Python Code information needed [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 6 years ago.
This is what I am trying to code: ask the user to deposit an amount of money of at least $20 to open the shopper card.
The store will then give the first-time bonus of $10 to spend on items.
The program will total the amount and generate the balance.
If the amount originally deposited is less than $20, the customer will be told that the amount is too little to open the account (use of conditional expression).
If the amount is greater than or equal to $20, then $10 will be added, and the total amount on the shopper card will be displayed.
So far I have done this much but have gotten stuck.
print ('''Hi my name is Richard. Welcome to Buymore.''')
user = input( 'First name : ')
user = input( 'Last name : ')
user = input('ZIP code : ')
print ("Please deposit$20 into your account for your new shopper's card.")
user=input('20 dollars : ')
if num <20:
print ("Congratulation’s on opening your new card")
print ("As a gift we are giving you 10 dollars towards your first purchase")
if num >20 :
print('Need to deposit more minimum is 20 dollars')
Stuck at what level? What is working and was isn't?
From looking at your code, the condition should be reversed.
if num >= 20:
# this is ok, give bonus.
else :
#give error
The user input should be retrieved in a num variable, and converted to an integer.
int(num)
retrieving the user information like you do is useless since you overwrite the name with the zip code, get them in separate variables.

Python vending machine snacks and drinks [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
Hi guys I have been trying to create a working python vending machine for over a month now and it doesn't look like I am making any progress. If somebody could help me that could be great :) Here is my program so far:
print ("Welcome to the Vending Machine\n")
total = 0
dr = 1
sn = 3
money=int(input("How much money do you want to insert"))
print ("Prices: Drinks: £1, Snacks: £3\n")
Drinks = {'Coke','Pepsi','Orange Juice', 'Apple Juice','Water'}
Snacks = {'Chocolate', 'Snickers','Twix','Peanuts','Crisp'}
state = 'subtotal'
while total <= money:
if state != 'total':
print('')
print('')
print ("\nDrinks Menue:")
print(Drinks)
print ("Snacks Menue:")
print(Snacks)
choice = input("\nEnter the item of your choice: ")
if choice in Drinks:
total += dr
elif choice in Snacks:
total += sn
else:
state = 'total'
print("\n\nThat will be a",state,"of £",total)
else:
print("You have exceeded your inserted money good bye")
I'm trying to make the code reject invalid input and stop when the user has gone over his spending limit.
There is only one problem with this when I run this. So, here is the fix with some explanation so you can learn something. It may seem like a simple mistake but we all make them at some point and eventually, indenting will be second nature.
Indents
Unlike some langues, in Python the indentation matters. A lot. Let's look at your first if statement.
if state != 'total':
print('')
print('')
print ("\nDrinks Menue:")
print(Drinks)
print ("Snacks Menue:")
print(Snacks)
choice = input("\nEnter the item of your choice: ")
Can you see the problem? After an if statment, or more precisely, after the :, we need to indent everything else that we want to be carried out by the if statement otherwise Python won't know where to stop! So by making this simple change:
if state != 'total':
print('')
print('')
print ("\nDrinks Menue:")
print(Drinks)
print ("Snacks Menue:")
print(Snacks)
We have no more error and your program now runs. Notice the indents? Just check that they are always right.

Python Help Again [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I am using Python 3.2 Just so you know what I am doing, here is the assignment:
~The function random.randint from the random module can be used to produce an integer from a range of values. For example, random.randint(1,6) produces the values 1 to 6 with equal probability. A simple tutoring program may randomly select two numbers between 0 and 12 and ask a question such as the following: What is 6 times 8? Upon receiving user response, the computer checks to see if the answer is correct and gives encouraging remarks. Write a program that will loop 10 times producing questions of this form and gives a score for the user at the end.
Here is what I have in my program:
print ("Hello. Let's begin")
for i in range (1,10):
from random import randint
x=randint (0,12)
y=randint (0,12)
print (x,"*" y,"=?")
product= int(input ("What is the product?")
if (product==x*y):
print ("Awesome! That is correct!")
else:
print ("Sorry, that is not correct, but let's try another one!")
I have everything working with all of this. It asks the user a random multiplication question and responds ten times. What I do not understand how to do is to give the user a score at the end. I'm brainstorming ideas and not much is really working. I think I would have to do something like:
score=
But I don't know how to tell the program to calculate the number of correct answers... Do I say score=number of if?
And then when I print the score I can just say:
if (score>5) :
print: ("Great job! You scored a",score,"out of ten!")
else:
print: ("Not the best score, but you can try again! You scored a",score,"out of ten.")
Or is there maybe an easier way to do this?
It seems like it would be simplest to just make a new variable ("score" or suchlike) and initialize it as 0 before the loop. Then, when you check if a user was correct, just increment it by one if it was right, and leave it alone if it was wrong.
Hope this helps!
First, set score to 0
score = 0
then in the loop, try something like
if (product==x*y):
print ("Awesome! That is correct!")
score += 1
else:
print ("Sorry, that is not correct, but let's try another one!")
the important part being the score += 1 this increases the score by one when you get a correct answer. You can the put your score > 5 in after the loop.

Could anyone give me some advice on program formatting and efficiency? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I am a newbie on python. I have just create a program taking a 2's complement binary number and convert it to decimal value. (The way of conversion is described at http://sandbox.mc.edu/~bennet/cs110/tc/tctod.html.)
I am aware that there are some certain rules on how to format your program and some "good habits" on how to design your program. Like how you put a header, comment, etc. And how you design the structure of it. I could not find a guide on Internet so I decide to ask here.
This is my first time making post on stackoverflow, so please bear with me if I make any mistakes. : )
Here is my code.
def secBiToDecimal(number):
""" This program takes a 2's complement binary number as input and returns its decimal value
"""
output = ""
" Check the sign of this number and calculate its value in according way."
if number[0]=='0':
output += "+"
temp = 0
for i in range(1,len(number)):
temp += (int(number[i]) * (2**(len(number)-i-1)))
output += str(temp)
print output
elif number[0]=='1':
output += "-"
carryout = 1
" flip the digits"
number = list(number)
for i in range(len(number)):
if number[i] == "1":
number[i]='0'
else:
number[i]='1'
" add 1 to number in binary sense "
for i in range(1,len(number)):
if carryout == 0 and number[len(number)-i]=='0':
break
elif carryout == 1 and number[len(number)-i]=='0':
number[len(number)-i]='1'
break
elif carryout == 0 and number[len(number)-i]=='1':
number[len(number)-i]='1'
break
elif carryout == 1 and number[len(number)-i]=='1':
number[len(number)-i]='0'
number = "".join(number)
temp = 0
for i in range(1,len(number)):
temp += int(number[i]) * (2**(len(number)-1-i))
output += str(temp)
print output
One of the most important things to consider with regard to code formatting, styling and conventions is the "house rules". If your "house" (i.e. work place, team, school, teacher, etc.) expects things done in a certain way, then that is the way you should do it.
Standards and conventions found on the internet can be used as source material for discussions on changing the house rules, or to develop your own personal standard for personal projects.
But do use some standard, and keep an offline copy of the documentation for that standard if you can, so that you can read your own code 6, 12, 24 months down the line ;).

Categories