Is there an "ignore" function for Python 2.7? - python

total newbie here.
So is there any way to stop a functioning from being executed if certain condition is met?
Here is my source code:
answer = raw_input("2+2 = ")
if answer == "4":
print "Correct"
else:
print "Wrong answer, let's try something easier"
answer = raw_input("1+1 = ")
if answer == "2":
print "Correct!"
else:
print "False"
So basically, if I put 4 on the first question, I will get the "False" comment from the "else" function below. I want to stop that from happening if 4 is input on the first question.

Indentation level is significant in Python. Just indent the second if statement so it's a part of the first else.
answer = raw_input("2+2 = ")
if answer == "4":
print "Correct"
else:
print "Wrong answer, let's try something easier"
answer = raw_input("1+1 = ")
if answer == "2":
print "Correct!"
else:
print "False"

You can place the code inside a function and return as soon any given condition is met:
def func():
answer = raw_input("2+2 = ")
if answer == "4":
print "Correct"
return
else:
print "Wrong answer, let's try something easier"
answer = raw_input("1+1 = ")
if answer == "2":
print "Correct!"
else:
print "False"
output:
>>> func()
2+2 = 4
Correct
>>> func()
2+2 = 3
Wrong answer, let's try something easier
1+1 = 2
Correct!

Related

How do I clear an "if" condition

I'm trying to figure out how to clear an "if" condition and how to fix the result = print(x) part of my code. I'm trying to create a little search code based on the variable data, but I can't figure a few things out:
import time
def start():
data = ["Lucas_Miguel", "João_Batista", "Rafael_Gomes", "Bruna_Santos", "Lucas_Denilson"]
print("1" + " - Check Name")
print("2" + " - Register a New Name")
option = input("Choose an option: ")
if option == "1":
def other():
name = input("Type the first name: ")
for x in data:
if name in x:
result = print(x)
while True:
print("Yes " "or " "No")
confirm = input("Is the name you want in the options?: ")
if confirm == "Yes":
break
if confirm == "No":
print("Yes", " or", " No")
try_again = input("Do you want to write again?: ")
if try_again == "Yes":
return other()
other()
else:
print("Option not available")
time.sleep(1)
return start()
start()
The first problem is in the result = print(x) part. It works, but when the answer is more than one name, only the first one appear and I don't know how to fix it.
The second problem is in the "confirm = input" part. Basically, if the person answered with "No", when they go back, the answer will still be saved and the input will run twice, the first time with the saved answer and the second with the new answer. So I want to be able to clear that before the person answer it again.
I want to apologize already if the code is ugly or weird, but I started a few days ago, so I'm still learning the basics. Also thanks in advance for the help.
There is quite a bit here to unpack and like the comment on the question suggests you should aim to look at how to ask a more concise question.
I have some suggestions to improve your code:
Split the other into its own function
Try to use more accurate variable names
As much as you can - avoid having multiple for loops happening at the same time
Have a look at list comprehension it would help a lot in this case
Think about whether a variable really belongs in a function or not like data
What you're asking for is not immediately clear but this code should do what you want - and implements the improvements as suggested above
import time
data = ["Lucas_Miguel", "João_Batista", "Rafael_Gomes", "Bruna_Santos", "Lucas_Denilson"]
def other():
name_input = input("Type the first name: ")
matches = [name for name in data if name_input in name]
if len(matches) == 0:
print ("No matches")
for name in matches:
print(name)
while True:
print("Yes " "or " "No")
confirm = input("Is the name you want in the options?: ")
if confirm == "Yes":
break
if confirm == "No":
print("Yes", " or", " No")
try_again = input("Do you want to write again?: ")
if try_again == "Yes":
return other()
else:
return
def start():
print("1" + " - Check Name")
print("2" + " - Register a New Name")
option = input("Choose an option: ")
if option == "1":
other()
else:
print("Option not available")
time.sleep(1)
return start()
start()
The first problem will be solved when you remove 8 spaces before while True:.
The second problem will be solved when you add return (without arguments) one line below return other() at the indentation level of if try_again == "Yes":
Everybody can see that you are just learning Python. You don't have to apologize if you think, your code is "ugly or weird". We all started with such small exercises.

Python, code doing the first thing then looping to the end

I am making a small quiz and trying to learn python. The quiz takes the first answer then loops all the way to the bottom instead of asking the user the rest of the questions. It will print the first question, then ask for the answer , then it will run throught the rest of the code but it won't actually ask for the input or anything like that.
question_1 = ("ex1")
question_2 = ("ex2")
question_3 = ("ex3")
question_4 = ("ex4")
answer = input ("Please type the letter you think is correct: ")
count = 0
# answers
print (question_1)
print ("A. ")
print ("B. ")
print ("C. ")
print ("D. ")
if answer == "b" or answer == "B":
print ("Correct")
count +=1
else:
print ("Incorrect")
print (question_2)
print ("A. ")
print ("B. ")
print ("C. ")
print ("D. ")
if answer == "a" or answer == "A":
print ("Correct")
count +=1
else:
print ("Incorrect")
print (question_3)
print ("A. ")
print ("B. ")
print ("C. ")
print ("D. ")
if answer == "d" or answer == "D":
print ("Correct")
count +=1
else:
print ("Incorrect")
print (question_4)
print ("A. ")
print ("B. ")
print ("C. ")
print ("D. ")
if answer == "c" or answer == "C":
print ("Correct")
count +=1
else:
print ("Incorrect")
You are only asking for one input and then checking that answer against every question.
You will need to add a new input for every question and then check against that input
e.g.
count = 0
print('Q1')
ans1 = input('A/B/C?')
if ans1.lower() == 'c': # Checks for it as a lowercase so no need to repeat it
print('Correct')
count += 1
else:
print('Incorrect')
print('Q2')
ans2 = input('A/B/C?')
if ans2.lower() == 'b':
print('Correct')
count += 1
else:
print('Incorrect')
You need to have the input() function after each question. An input is asked for at each input, writing it once before all the questions won't work.
By the way, you might want to use lists and a loop to get the same done with less code.

want to print answer if q is answered incorrectly, and give two more chances

So I have an assessment due tomorrow (it is all finished) and was hoping to add a few more details in.
How would I:
a. Make it so that if you answer the question wrong, you can retry twice
b. if you completely fail, you get shown the answer
How would i do this? thanks
ps. The code lloks retarded, i couldn't get it in
} output = " " score = 0 print('Hello, and welcome to my quiz on Ed Sheeran!') for question_number,question in enumerate(questions): print ("Question",question_number+1)
print (question)
for options in questions[question][:-1]:
print (options)
user_choice = input("Make your choice : ")
if user_choice == questions[question][-1]:
print ("Correct!")
score += 1
print (score)
print (output)
else:
print ("Wrong!")
print (score)
print (output)
print(score)
What I have understood from your query is that you want user to input the option twice before we move to the next question.
Also you want to display the answer if the user has incorrectly answered in both the chances.
I don't know how your questions and answers are stored but you can use the below code as a pseudo code.
The below code should work:
print('Hello, and welcome to my quiz on Ed Sheeran!')
for question_number,question in enumerate(questions):
print ("Question",question_number+1)
print (question)
tmp = 0
for options in questions[question][:-1]:
print (options)
for j in range(2):
user_choice = input("Make your choice : ")
if user_choice == questions[question][-1]:
print ("Correct!")
score += 1
break
else:
print ("Wrong!")
tmp += 1
if tmp == 2:
print ('You got it wrong, Correct answer is: ' output)
print(score)

How to ask a string again if the wrong answer is entered?

I'm trying to get a string to keep repeating if the answer is wrong. How would I go about doing this? The code I have is below which works but doesn't repeat the answer.
print("Hello there, what is your name?")
MyName = input()
print ("Nice to meet you " + MyName)
print ("What is 2 + 2?")
answer = input()
if answer is '4':
print("Great job!")
elif answer != '4':
print ("Nope! please try again.")
while answer != '4':
print ("What is 2 + 2?")
break
There are a couple of things wrong with your code. Firstly, you are only asking for the answer once at the moment. You need to put answer = input() in a while loop. Secondly, you need to use == instead of is:
print("Hello there, what is your name?")
MyName = input()
print ("Nice to meet you " + MyName)
print ("What is 2 + 2?")
answer = 0
while answer != '4':
answer = input()
if answer == '4':
print("Great job!")
else:
print ("Nope! please try again.")
There are a number of ways you can arrange this code. This is just one of them
print('Guess 2 + 2: ')
answer = int(input())
while answer != 4:
print('try again')
answer = int(input())
print('congrats!')
I think this is the simplest solution.
By now you've got more answers than you can handle, but here are another couple of subtleties, with notes:
while True: # loop indefinitely until we hit a break...
answer = input('What is 2 + 2 ? ') # ...which allows this line of code to be written just once (the DRY principle of programming: Don't Repeat Yourself)
try:
answer = float(answer) # let's convert to float rather than int so that both '4' and '4.0' are valid answers
except: # we hit this if the user entered some garbage that cannot be interpreted as a number...
pass # ...but don't worry: answer will remain as a string, so it will fail the test on the next line and be considered wrong like anything else
if answer == 4.0:
print("Correct!")
break # this is the only way out of the loop
print("Wrong! Try again...")
You only need the wrong-answer check as loop condition and then output the "great job" message when the loop is over (no if is needed):
print("Hello there, what is your name?")
MyName = input()
print ("Nice to meet you " + MyName)
print ("What is 2 + 2?")
answer = input()
while answer != '4':
print ("Nope! please try again.")
print ("What is 2 + 2?")
answer = input()
print("Great job!")
Here is my two cents for python2 :
#!/usr/bin/env python
MyName = raw_input("Hello there, what is your name ? ")
print("Nice to meet you " + MyName)
answer = raw_input('What is 2 + 2 ? ')
while answer != '4':
print("Nope ! Please try again")
answer = raw_input('What is 2 + 2 ? ')
print("Great job !")

python: import random for multiple question

I have already created a login(). Trying to ask a random question each time and if answered correctly to run login().
feel that i am on the right track with the latest answer . but running into some trouble .
Below is the outline of what I am trying to do:
>>> def human_check():
random_question = random.choice(questions)
question, answer = random_question
user_answer = raw_input(question)
if user_answer != answer:
print "Sorry, try again."
else:
return login()
File "", line 5
if user_answer != answer:
^
IndentationError: unindent does not match any outer indentation level
this is what i had to begin with :
>>> def human_check():
question1 == raw_input('1+1=')#question.1#
while question1 !== '2':
print 'sorry robot , try again'
else:
return login()
question2 == raw_input('the cow jumped over the ....')#question.2#
while question2 !== '2':
print 'sorry robot , try again'
else:
return login()
import random
random.question
#
I imported the random module but how do I group the questions so that random. will work?#
SyntaxError: invalid syntax
>>>
You can do something like this:
import random
questions = []
questions.append(("1+1=", "2"))
questions.append(("the cow jumped over the ....", "moon"))
def human_check():
random_question = random.choice(questions)
question, answer = random_question
user_answer = raw_input(question)
if user_answer != answer:
print "Sorry, try again."
else:
return login()
Basically, if you maintain some list of questions, you can use random.choice to make a random selection from that list.

Categories