I'm trying to create a program to create a questionaiire, ultimately giving back info the user inputs. Here's my code:
. Def questionaiire:
>>. Loop = 0
>>
>> While loop != 1:
>> Print "A: name"
>> Print "B: age"
>> Print "B: Favorite color".
>> Zen = raw_input("choose a, b, or c") #my problem line
>> If zen == "a" or "A":
>> A = raw_input("Input your name: ")
>>. Elif zen == "b" or "B":
>>. B = raw_input:("Input your age: ")
>>. Elif zen == "C" or "c":
>> C = raw_input("Input your favorite color")
>> Else:
>> Print A, B, C
>> Break
The ending bit is a little more sophisticated, but essentially thats my function. Help?
I also tried inserting return after the if and elifs, but that made the program stuck(couldnt input) so i took them out
There are a number of syntax errors in your code.
You must not capitalize def, while, print, if, elif, else, break, or any other python keyword, they must be all lower case.
You need to be consistent in the casing of your variable names. Zen and zen are two different variables!
You must put parenthesis after the name of the function, like this: def questionaiire():
The period in this line is a syntax error. Remove it.
print "B: Favorite color".
The colon following raw_input in this line is a syntax error. Remove it.
B = raw_input:("Input your age: ")
I don't know what the >>s at the start of each line is, I presume it's not part of the actual source code. If it is, remove all occurances of > at the start of a line.
This line does not do what you think it does:
if zen == "a" or "A":
It's interpreted like this:
if (zen == "a") or "A":
So it's always true, since "A" evaluates to True. Write it like this instead:
if zen.lower() == "a":
Here's a working example. I've made as few changes as possible to the code, to ease comparison.
def questionaiire():
a = b = c = ""
while True:
print "a: name"
print "b: age"
print "c: favorite color"
zen = raw_input("choose a, b, or c: ")
if zen.lower() == "a":
a = raw_input("input your name: ")
elif zen.lower() == "b":
b = raw_input("input your age: ")
elif zen.lower() == "c":
c = raw_input("input your favorite color: ")
else:
print a, b, c
break
You never used the loop variable, so I've removed it. Since you use break, there's no real need for it in this code example.
The number and variety of mistakes you've made writing this short code indicates that you would really benefit from reading through at least the first few chapters of the python tutorial before programming any more python or asking further python-related questions on this site.
Related
Write a python program to display the outputs of following arithmetic operations on two numbers,which is accepted from user side ? a)Addition b)Subtraction c)Multiplication d)Division//
i wrote this code but it is not working
a = int(input("Enter First Number: "))
b = int(input("Enter Second Number: "))
print("Enter which operation would you like to perform?")
ko= input("Enter any of these char for specific operation +,-,*,/: ")
result = 0
if ko == '+':
result = a + b
elif ko == '-':
result = a - b
elif ko == '*':
result = a * b
elif ko == '/':
result = a / b
else:
print("Error")
print(num1, ko , num2, ":", result)
can anybody please tell me what i did wrong or post the correct code
Firstly, the first line of your program isn't indented properly - You need to remove the indentation before the first line.
Here's a guide to proper indentation in python: https://docs.python.org/2.0/ref/indentation.html
Secondly, the variables that you call in the final print function do not exist. "num1" and "num2" aren't defined - you need to use "a" and "b", because that's what you name the return values of the input functions you call in the beginning of the program. So you can either change "num1" and "num2" to "a" and "b", or vice versa.
The final code would look something like this:
a = int(input("Enter First Number: "))
b = int(input("Enter Second Number: "))
print("Enter which operation would you like to perform?")
ko = input("Enter any of these char for specific operation +,-,*,/: ")
result = 0
if ko == '+':
result = a + b
elif ko == '-':
result = a - b
elif ko == '*':
result = a * b
elif ko == '/':
result = a / b
else:
print("Error")
print(a, ko, b, ":", result)
Also, while programming in any language, it's advised to use descriptive names for variables - It might take some extra typing, but it will save a lot of hassle in bigger and more complex programs, and also it's a good practice.
Finally, this program (even though it gets the job done), isn't the most efficient or beginner-friendly solution for a calculator program. Here are some resources to help you understand it:
"Building a Basic Calculator | Python ": https://www.youtube.com/watch?v=HBbrSDGGOkw
or, if you prefer reading:
https://www.digitalocean.com/community/tutorials/how-to-make-a-calculator-program-in-python-3
I'd also like to tell you that reading the error messages you get in the console would've helped you understand the problem better, and maybe even come up with a solution, but we're here to help you :)
The error was in your last print statement...num1 and num2 should replace as a and b.
So the last line should be:
print(a, ko , b, ":", result)
I'm reasonably new to Python. I wanted to know if I could use an input and ask a question like 'are you sure?', and if the answer is no to go back to the original input. I've got this so far:
variable = input("Make a choice between a, b, c or d. ")
while variable not in ("a","b","c","d"):
variable = input("Make a correct choice. ")
if variable == "a":
do things
if variable == "b":
do other things
etc etc
I want to ask, after they have typed in their choice, are you sure about your choice? If they say yes, that's fine, carry on, but if they say 'no' I want to be able to go to the same input without typing the whole thing out again. Is there any way to do that?
You could embed the bit that you want to repeat in a while True block that you break out of? For example:
while True
answer = input("What is the correct answer, a, b, or c? ")
check = input("Are you sure (y/n)? ")
if check=="y" or check=="Y":
break
Take the code you already have and wrap it in another while loop:
# loop forever until they confirm their choice
while True:
variable = input("Make a choice between a, b, c or d. ")
while variable not in ("a","b","c","d"):
variable = input("Make a correct choice. ")
confirm = input("You entered %s. Is this correct?" % variable)
if confirm == "yes":
break
ok=False
while not OK:
variable = input("Make a choice between a, b, c or d. ")
while variable not in ("a","b","c","d"):
variable = input("Make a correct choice. ")
ishesure=input("You chose {}, Are you sure? (Y or N)".format(variable))
if ishesure=="Y":
ok=True
Should work. You surround everything by a while loop that will loop until the customer enters "Y" to your second question, that is asked once he entered a valid value for variable
Something like this will work (though it's not the cleanest thing right now).
def prompt_for_something():
variable = input("Make a choice between a, b, c or d. ")
while variable not in ("a","b","c","d"):
variable = input("Make a correct choice. ")
confirm = input("Are you sure?")
if confirm == "No": return False
return variable
option = prompt_for_something()
while option == False:
option = prompt_for_something()
if option == "a":
do something
It is not easy to have editable console output. If it is just for you, you can press the 'up' arrow key to go back to your last input, but if you want to embed it into the code it may be easier to use a proper GUI (i.e. tkinter) than what you are doing.
If you have a while loop with two raw_input lines, where you want each raw_input line to be repeated until a correct input is provided AND you also want the loop to continue until a specific outcome is achieved; is this even doable in Python without a goto option?
#For example:
while True:
a = raw_input("What is your name?: ")
#Hypothetically assuming "Sam" is the only acceptable answer
if a not in ["Sam"]:
print "Error, try again."
else:
b = raw_input("How old are you?: ")
#Hypothetically assuming 28 is the only acceptable answer
if b not in [28]:
print "Error, try again."
else:
continue
#no break out of loop provided, this is just a quick hypothetical
This is a pretty quick example (and not the best...), but it's just to give the gist of what I am trying to do with my code (complete beginner here). As you can see, the first error would work out just fine as things would loop back to the beginning and the first raw_input line, but an error on the second raw_input line would go also back to the first raw_input line (is there any way to repeat in the middle of the while loop where the second raw_input line is?) I'd like to try and salvage my code if possible, so if there is any way to make things work using this awfully long while loop, I would really appreciate your input.
An elegant albeit little advanced solution -
def ask_questions():
yield "Sam" == raw_input("What is your name?: ")
yield "28" == raw_input("How old are you?: ")
while True:
repeat = False
for answer in ask_question():
if not answer:
repeat = True
break
if not repeat:
break
You could use a variable for keeping track of which question is due, like this:
def ask(question, validator):
a = input(question)
return a if validator(a) else None
progress = 0
while progress < 2:
if progress == 0:
ok = a = ask("What is your name?: ", lambda a: a in ["Sam"])
else:
ok = b = ask("How old are you?: ", lambda b: b in [28])
if ok == None:
print ("Error, try again.")
progress += int(ok != None)
Alternative
You could initialise the answers as None and keep going until the last answer is not None, while asking the questions that still have no no-None answer value.
You could raise an exception if the validation fails for an answer:
def ask(question, validator):
a = input(question)
if not validator(a):
raise ValueError
return a
progress = 0
a = None
b = None
while b == None:
try:
if a == None: a = ask("What is your name?: ", lambda x: x in ["Sam"])
if b == None: b = ask("How old are you?: ", lambda x: x in [28])
except ValueError:
print ("Error, try again")
print (a, b)
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 8 years ago.
I am a novice coder who's just started coding about 4-5 weeks ago. The best I have achieved is a basic Python username and password login page for a 'top secret' website (the website is fake). However, just to refresh my memory of basic coding (I've been doing some un-related things lately), I tried making a basic childrens game to do with the alphabet. Here's my current code:
name = input("What's Your Name?: ")
print("Welcome" , name , "to the 3 lucky guess alphabet skills builder!")
print("Let's get started:")
C = input("What Is The 3rd Letter of The Alphabet: ")
if C == 'C' or 'c':
print("Congraulations!")
else:
print("Think We Should Retry That!")
C
if C == 'C' or 'c':
print("That's Better!")
Z = input("What Is The Last Letter of The Alphabet: ")
if Z == 'Z' or 'z':
print("You're Really Good At This! One More!")
else:
print("Have Another Go!")
Z
if Z == 'Z' or 'z':
print("That's More Like It! Last One!")
J = input("What Is The 10th Letter Of The Alphabet: ")
if J == 'J' or 'j':
print("Great! How Many Did You Get In Total?")
else:
print("Unlucky, Better Luck Next Time!")
total = input("How Many Did You Get In Total?: " , print("Out Of 3!")
print("Wow! You Got" , total , "! Well Done" , name , "!!!")
exit
Why aren't any of the 'else' arguments working?
Also, why won't the second to last bit of code work - it just states a syntax error!
I have tried indenting all the else statements but that results in a syntax error too!
Please help! :)
The if statement you wrote, like the following
if C == 'C' or 'c':
doesn't do what you mean. The expression after or just checks whether 'c' evaluates to true, which it always will. That's why the code after else: won't execute.
You have to write it like this:
if C == 'C' or C == 'c':
It's difficult to know what you mean by "not working" - you should be more specific about the error you're seeing. Are you referring to this?
else:
print("Have Another Go!")
Z
if Z == 'Z' or 'z':
print("That's More Like It! Last One!")
The second line of the body simply evaluates the variable Z - it doesn't change anything. Therefore, the conditional following it still returns the same result as the last time you evaluated it.
Also, as the other answer points out,
if a = "foo" or "bar"
will always be True, because "bar" is a non-false value, and an or with any non-false value is True.
shift = raw_input("Enter the shift the employee works in: ")
shift = shift.upper()
print shift
while (shift != "A" or shift != "B" or shift != "C" ):
shift = raw_input("Invalid Input- Please Enter a, b or c: ")
shift = shift.upper()
I need to validate that the user is choosing "a, b or c" I also must use string.upper().
However, it keeps going into the while loop even when I input "a, A, b, B, c or, C" I have the "print shift" to make sure it's inputing correctly and it is.
When I only have "shift != "A"" and type in "a or A" it won't go into the loop. It's only when I add the "B and C" that it starts to mess up. How do I fix this?
You need to use and instead of or (because x != 1 or x != 2 is always true):
while (shift != "A" and shift != "B" and shift != "C" ):
But you can do better:
while shift not in "ABC":