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")
Related
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 2 years ago.
I was trying to play around with the input function. However, it seems that this code is not correct, I looked to see examples online but they tend to be basic and what i was trying to do was slightly above basic. Also, is it possible to put the return function instead of the print one? if not why? I'm new to this so if these all sound stupid please forgive me.
cheers!
def user_data(x):
age = input("how old are you?")
if age == 20:
print("you win")
else:
print("you lose")
input returns a string, while you are comparing age (a string) to an integer.
You have to either compare age to a string (so age == "20"), or convert age to an int (so int(age) == 20).
See docs to find out how input works.
def user_data(age):
if age == 20:
print("you win")
else:
print("you lose")
age = int(input("how old are you?"))
user_data(age)
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 7 years ago.
I'm trying to write a piece of code with that repeats the question until the correct answer is given, with a few different responses for likely answers. This is what I have so far, but after it responds to the input given, the program moves on. I can't figure out how to do this with a while loop since it ends with a specific answer and not with else.
answer = input("What is your favorite eldest daughter's name? ").lower()
if answer == "a" or answer == "al":
print("Of course, we all knew that")
elif answer == "c" or answer == "chris":
print("""Oh she must be standing right there.
But that\'s not it, try again.""")
elif answer == "e" or answer == "ed":
print("Not even the right gender. Try again.")
elif answer == "n" or answer == "nic":
print("Only biological children please.")
else:
print("I'm sorry. Only children. Were you thinking of the dogs?")
break is what you want. Use it like so:
while 1:
answer = input("What is your favorite eldest daughter's name? ").lower()
if answer == "a" or answer == "al": #assuming this is the right answer
print("Of course, we all knew that")
break
elif answer == "c" or answer == "chris":
print("""Oh she must be standing right there.
But that\'s not it, try again.""")
elif answer == "e" or answer == "ed":
print("Not even the right gender. Try again.")
elif answer == "n" or answer == "nic":
print("Only biological children please.")
else:
print("I'm sorry. Only children. Were you thinking of the dogs?")
You basically need to keep repeating the question until the answer is considered to be acceptable by the program.
Code
#!/usr/bin/python3 -B
answers = ['alice', 'chris', 'bob']
answer = None
while answer not in answers:
answer = input('Enter your answer: ')
print('Your answer was: {}'.format(answer))
Basically the code here has a list of acceptable answers and it initializes the user's answer to None. Then it enters a while loop that keeps repeating itself until the user's answer is found within the list of acceptable answers.
Output
➜ ~ ./script.py
Enter your answer: alice
Your answer was: alice
➜ ~ ./script.py
Enter your answer: no
Enter your answer: no
Enter your answer: yes
Enter your answer: bob
Your answer was: bob
Improving the Code
You can now adapt the code to use the messages of your choice. Note, too, that if you want to provide a different response for any of the acceptable entries, you could use a dictionary and update the code slightly.
For example, you could have something like this:
answers = {
'bob': 'This was the best choice',
'alice': 'Everyone picks the hot gal',
# ... and so on
}
Then you'd keep iterating just like before by checking the keys of the answers dictionary (e.g. while answer not in answers.keys():).
When the loop exits with an acceptable answer, you'd simply
print(answers[answer])
If answers == 'alice', then the program would print Everyone picks the hot gal.
It would significantly simplify your code and make it easier for you to understand and work with :)
Use the while loop, and the break statement:
while True:
# . . .
if correct_answer:
break
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 7 years ago.
Learning python and currently learning the bisection method of solving problem. I'm writing code that should take in a users guess from 0 to 100 and attempt to find that guess using bisection. Here's the code:
answer = raw_input('Please think of a number between 0 and 100')
#I've been using 80 as my test case
low = 0
high = 100
guess = (low+high)/2
while guess != answer:
if guess < answer:
low = guess
else:
high = guess
guess = (low+high)/2
What I've realized is that when my guess < answer is false the else block doesn't execute, so my high number never changes. Why is this happening? Am I overlooking something here?
You need to convert user input to integer (raw_input() returns a string):
answer = int(raw_input(...))
Comparison fails because you are later comparing an integer to a string (which works in Python2, but would not work in Python3):
>>> 10 < "50"
True
>>> 75 < "50"
True
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!"
This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 8 years ago.
I have been having trouble with my python code and have been asking around for help. I have heard mixed things about this website but i have no where else to turn so i was hoping someone on here could show me the light and see if they can find out what's wrong with my code (other then it being messy and inefficient). here it is
D=False
while D==False:
input=raw_input("please type 1 for 10p, 2 for 20p, 3 for 50p, 4 for 1 pound")
while input not in ['1', '2', '3', '4']:
print "That is not a correct coin value"
input = raw_input("input: ")
else:
if input=="1":
m=m+10
if input=="2":
m=m+20
if input=="3":
m=m+50
if input=="4":
m=m+100
print("your current credit in pennys is:")
print(m)
D2=raw_input("are you done")
if D2=="yes" or "Yes":
D=True
else:
D=False
I kind of mucked up the implantation of the code on here but you get the picture. It all works fine until you get to the bit asking you if you are done. For some reason it carries on even if you don't put yes. Can any nice coders out there tell me what's up with it
This
if D2=="yes" or "Yes":
always evaluates to true, as it's essentially parsed like this:
if (D2=="yes") or "Yes":
You probably wanted:
if D2 == "yes" or D2 == "Yes":
Which is better written as:
if D2.lower() == "yes":
Or:
if D2 in ["yes", "Yes"]: