Why is my function executing twice? - python

A function in my code repeats twice. In the chooseName() function, it asks the question, and once you answer, it repeats the question and then moves on with the rest of the code. Why does it do this?
# -*- coding: utf-8 -*-
from __future__ import print_function
import random
import time
def displayIntro():
print("Hello, there! Glad to meet you!")
print("Welcome to the world of Pokémon!")
print("My name is Maple.")
print("People affectionately refer to me as the Pokémon Professor.")
print("This world is inhabited far and wide by creatures called Pokémon.")
print("For some people, Pokémon are pets.")
print("Others use them for battling.")
print("As for myself, I study Pokémon as a profession.")
print("But first, tell me a little about yourself.")
def chooseGender():
gender = ""
while gender != "boy" and gender != "girl":
gender = raw_input("Now tell me. Are you a boy? Or are you a girl? ")
return gender
def chooseName():
name = ""
name = raw_input("Let's begin with your name. What is it? ")
return name
def nameConfirmation():
name = chooseName()
answer = ""
while answer != "yes" and answer != "no":
answer = raw_input("Right... So your name is " + str(name) + "? (yes or no) ")
return answer
if answer == "yes":
print("I have a grandson.")
print("He's been your rival since you both were babies.")
print("...Erm, what was his name now?")
# raw_input for their name
print("...Er, was it") #raw_input for name
# Let user pick yes or no
# If yes, move on
# If no, ask name again
print("That's right! I remember now! His name is") #raw_input for name
print("your name!") # raw_input for name
print("Your very own Pokémon legend is about to unfold!")
print("A world of dreams and adventures with Pokémon awaits! Let's go!")
if answer == "no":
chooseName()
displayIntro()
chooseGender()
chooseName()
nameConfirmation()
I apologize for not posting the rest of the code sooner.
This is the output.
Let's begin with your name. What is it? Raven
Let's begin with your name. What is it? Raven

Remove the chooseName( ) call below chooseGender( ) as it has already been called in nameConfirmation( ) definition. It worked for me.

Some modification in your code , Here is updated code:
First edit :
You are calling chooseName() two times ,
Second edit :
You are returning before main logic of your program.
Here
def nameConfirmation():
name = chooseName()
answer = ""
while answer != "yes" and answer != "no":
answer = raw_input("Right... So your name is " + str(name) + "? (yes or no) ")
return answer
You should keep in mind that function is not going to execute anything after you return from it so your code from if answer == "yes": is not going to execute even if user type yes or no
So return it at the last of the program or if you want to return at the same place then use print there instead of 'return'.
# -*- coding: utf-8 -*-
from __future__ import print_function
import random
import time
def displayIntro():
print("Hello, there! Glad to meet you!")
print("Welcome to the world of Pokémon!")
print("My name is Maple.")
print("People affectionately refer to me as the Pokémon Professor.")
print("This world is inhabited far and wide by creatures called Pokémon.")
print("For some people, Pokémon are pets.")
print("Others use them for battling.")
print("As for myself, I study Pokémon as a profession.")
print("But first, tell me a little about yourself.")
def chooseGender():
gender = ""
while gender != "boy" and gender != "girl":
gender = input("Now tell me. Are you a boy? Or are you a girl? ")
return gender
def chooseName():
name = ""
name = input("Let's begin with your name. What is it? ")
return name
def nameConfirmation():
name = chooseName()
answer = ""
while answer != "yes" and answer != "no":
answer = input("Right... So your name is " + str(name) + "? (yes or no) ")
if answer == "yes":
print("I have a grandson.")
print("He's been your rival since you both were babies.")
print("...Erm, what was his name now?")
# raw_input for their name
print("...Er, was it") #raw_input for name
# Let user pick yes or no
# If yes, move on
# If no, ask name again
print("That's right! I remember now! His name is") #raw_input for name
print("your name!") # raw_input for name
print("Your very own Pokémon legend is about to unfold!")
print("A world of dreams and adventures with Pokémon awaits! Let's go!")
if answer == "no":
chooseName()
return answer
displayIntro()
chooseGender()
nameConfirmation()

As chooseName() is getting called twice first below call of chooseGender() and second inside nameConfirmation() so that's the reason it is getting executed twice. As a fixed you can comment or remove chooseName() which is below chooseGender() as shown.
displayIntro()
chooseGender()
# chooseName()
nameConfirmation()
So updated code will be as follows:
# -*- coding: utf-8 -*-
from __future__ import print_function
import random
import time
def displayIntro():
print("Hello, there! Glad to meet you!")
print("Welcome to the world of Pokémon!")
print("My name is Maple.")
print("People affectionately refer to me as the Pokémon Professor.")
print("This world is inhabited far and wide by creatures called Pokémon.")
print("For some people, Pokémon are pets.")
print("Others use them for battling.")
print("As for myself, I study Pokémon as a profession.")
print("But first, tell me a little about yourself.")
def chooseGender():
gender = ""
while gender != "boy" and gender != "girl":
gender = raw_input("Now tell me. Are you a boy? Or are you a girl? ")
return gender
def chooseName():
name = ""
name = raw_input("Let's begin with your name. What is it? ")
return name
def nameConfirmation():
name = chooseName()
answer = ""
while answer != "yes" and answer != "no":
answer = raw_input("Right... So your name is " + str(name) + "? (yes or no) ")
return answer
if answer == "yes":
print("I have a grandson.")
print("He's been your rival since you both were babies.")
print("...Erm, what was his name now?")
# raw_input for their name
print("...Er, was it") #raw_input for name
# Let user pick yes or no
# If yes, move on
# If no, ask name again
print("That's right! I remember now! His name is") #raw_input for name
print("your name!") # raw_input for name
print("Your very own Pokémon legend is about to unfold!")
print("A world of dreams and adventures with Pokémon awaits! Let's go!")
if answer == "no":
chooseName()
displayIntro()
chooseGender()
# chooseName()
nameConfirmation()

You call the function choseName() and then right after you call nameConfiguration() wich starts by calling choseName(), that's why it is called twice. You can simply remove the choseName() before nameConfiguration().

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.

I cannot use a input check to verify if the person has put in the correct code

This is my code
name=""
name=input("What is your name?")
print ("For clarification, is your name",name,"?")
input("Please enter yes or no")
if input==("yes"):
print ("Thank you")
else:
name=input("What is your name?")
and I was wondering if anyone could help me sort it out. In the lines below.
input("Please enter yes or no")
if input==("yes"):
print ("Thank you")
else:
name=input("What is your name?")
print ("Thank you",name,)
I am trying to ask people if they have put the correct names by asking them directly. If the answer is yes, they can move on, otherwise they will have to input their name again. Unfortunately I am not able to find the way to do it. Can anyone send me a correct code version. (An explanation would be nice but not necessary.)
Try :
while True:
n = input("Please enter yes or no")
if n == "yes":
print ("Thank you")
break
else:
name = input("What is your name?")
print ("Thank you",name)
You need to remember the second input to use it in the if statement.
response = input("Please enter yes or no")
if response == "yes":
print("Thank you")
else:
name = input("What is your name?")
You could use a recursive function.
It will loop until it returns the name.
#!python3
def get_name():
name=input("What is your name?")
print("For clarification, is your name",name,"?")
sure = input("Please enter yes or no")
if sure==("yes"):
print("Thank you")
return name
else:
get_name()
name = get_name()

reading quiz text file no longer working

I am trying to ask the user to pick a quiz, read the relevant questions from a txt file, ask for user answers, validate and check they are correct then add up to scores. I am completely self taught so have picked this code up from various sites but as I have adapted it it no longer works - what have I done wrong? I know its probably something really obvious so please be gentle with me!
getting the message global name the_file not defined
import time
def welcome():
print ("Welcome to Mrs Askew's GCSE ICT Quiz")
print()
def get_name():
firstname = input("What is your first name?:")
secondname = input("What is your second name?:")
print ("Good luck", firstname,", lets begin")
return firstname
return secondname
def displaymenu():
print("-------------------------------------------------------")
print("Menu")
print()
print("1. Input and Output Devices")
print("2. Collaborative working")
print("3. quiz3")
print("4. quiz4")
print("5. view scores")
print("6. Exit")
print()
print("-------------------------------------------------------")
def getchoice():
while True:
print("enter number 1 to 6")
quizchoice = input()
print("You have chosen number "+quizchoice)
print()
if quizchoice >='1' and quizchoice <='6':
print("that is a valid entry")
break
else:
print("invalid entry")
return quizchoice
def main():
welcome()
get_name()
while True:
displaymenu()
quizchoice = getchoice()
print ("please chooses from the options above: ")
if quizchoice == ("1"):
the_file = open("questions.txt", "r")
startquiz()
elif quizchoice == ("2"):
collaborativeworking()
startquiz()
else:
break
def collborativeworking():
the_file = open("Collaborative working.txt", "r")
return the_file
def next_line(the_file):
line = the_file.readline()
line = line.replace("/", "\n")
return line
def next_block(the_file):
category = next_line(the_file)
question = next_line(the_file)
answers = []
for i in range(4):
answers.append(next_line(the_file))
correct = next_line(the_file)
if correct:
correct=correct[0]
explanation = next_line(the_file)
time.sleep(2)
return category, question, answers, correct, explanation
def startquiz():
title = next_line(the_file)
score = 0
category, question, answers, correct, explanation = next_block(the_file)
while category:
# ask a question
print(category)
print(question)
for i in range(4):
print("\t", i + 1, "-", answers[i])
# get answer and validate
while True:
answer =(input("What's your answer?: "))
if answer >= '1' and answer <='4':
break
else:
print ("the number needs to be between 1 and 4, try again ")
# check answer
answer=str(answer)
if answer == correct:
print("\nRight!", end=" ")
return score
main()
Couple of things I noticed. You haven't provided the error you are getting (/ problems you are having) so these are the things I noticed in my quick look:
First: enter code hereimport time should be import time
Second: All function definitions (def func():) should have the code in them indented e.g.
def get_name():
firstname = input("What is your first name: ")
Third: print () should be print()
Fourth: Multiline strings do exist
"""
Look at me mum!
WOWWWW!
"""
Fifth: It looks like a lot of this has been copied from elsewhere, if you are learning, I suggest you don't copy, but try to understand what things are doing and then hand write it
Sixth: There are a lot of bugs. I think I got most of them, but you should really change something in the way you're working. It really does fail in so many places
Seventh: Here is your code with some improvements:
import time
def welcome():
print("Welcome to Mrs Askew's GCSE ICT Quiz\n")
def get_name():
firstname = input("What is your first name: ")
secondname = input("What is your second name: ")
print("Good luck" + firstname + ", lets begin") # or print("Good luck {}, lets begin".format(firstname))
return firstname, secondname
def displaymenu():
print("""-------------------------------------------------------
Menu
1. Input and Output Devices
2. Collaborative working
3. quiz3
4. quiz4
5. view scores
6. Exit
-------------------------------------------------------""")
def getchoice():
while True:
quizchoice = input("Enter number 1 to 6: ")
print("You have chosen number " + quizchoice "\n")
if quizchoice >= "1" and quizchoice <= "6":
print("That is a valid entry")
break
else:
print("invalid entry")
return quizchoice
def main():
welcome()
get_name()
while True:
displaymenu()
quizchoice = getchoice()
print("Please chooses from the options above: ")
if quizchoice == ("1"):
the_file = open("questions.txt", "r")
startquiz()
elif quizchoice == ("2"):
collaborativeworking()
startquiz()
else:
break
def collborativeworking():
the_file = open("Collaborative working.txt", "r")
return the_file
def next_line(the_file):
line = the_file.readline()
line = line.replace("/", "\n")
return line
def next_block(the_file):
category = next_line(the_file)
question = next_line(the_file)
answers = []
for i in range(4):
answers.append(next_line(the_file))
correct = next_line(the_file)
if correct:
correct = correct[0]
explanation = next_line(the_file)
time.sleep(2)
return category, question, answers, correct, explanation
def startquiz():
title = next_line(the_file)
score = 0
category, question, answers, correct, explanation = next_block(the_file)
while category:
# ask a question
print(category)
print(question)
for i in range(4):
print("\t", i + 1, "-", answers[i])
# get answer and validate
while True:
answer =(input("What's your answer?: "))
if answer >= '1' and answer <='4':
break
else:
print ("the number needs to be between 1 and 4, try again ")
# check answer
answer=str(answer)
if answer == correct:
print("\nRight!", end=" ")
return score
main()
Eighth: Please take time to make an answer before you post. People here want to answer questions, and try to answer them with the most effort they can put in, so we expect questioners to put in the same effort, to spend time on their questions (basically pretend you are asking the person you respect most in your life this question, then behave appropriately e.g. Dear your royal highness, beloved master and benefactor, who I so dearly love, please, oh please, do me the great kindness to answer my humble question that I have taken 2 days to write properly so you wouldn't be offended and have to waste as little time as possible with such a small thing as me...)
Ninth: There are much better ways to do what you want.
I suggest you:
Try perfecting parts of your program, before writing 108 lines
Try not having so many functions
Try to decrease the length of your code, make it not so verbose, but succinct
Use consistent formatting (e.g. only one type of quotes; only, spaces or tabs)
Also read up on some basic python (learn python the hard way is good)
I also highly recommend PEP (Python Enhancement Proposals) 8 and the other PEP's
Look at test-driven development in python

How can I restart my python 3 script?

I am making a program on python 3. I have a place that I need the script to restart. How can I do this.
#where i want to restart it
name= input("What do you want the main character to be called?")
gender = input("Are they a boy or girl?")
if gender == "boy":
print("Lets get on with the story.")
elif gender == "girl":
print("lets get on with the story.")
else:
print("Sorry. You cant have that. Type boy or girl.")
#restart the code from start
print("Press any key to exit")
input()
It's a general question about programming an not specific to Python ... by the way you can shorten your code with the two conditions on boy and girl...
while True:
name= input("What do you want the main character to be called?")
gender = input("Are they a boy or girl?")
if gender == "boy" or gender == "girl":
print("Lets get on with the story.")
break
print("Sorry. You cant have that. Type boy or girl.")
print("Press any key to exit")
input()
Simple but bad solution but you get the idea. I am sure, you can do better.
while True:
name= input("What do you want the main character to be called?")
gender = input("Are they a boy or girl?")
if gender == "boy":
print("Lets get on with the story.")
elif gender == "girl":
print("lets get on with the story.")
else:
print("Sorry. You cant have that. Type boy or girl.")
#restart the code from start
restart = input("Would you like to restart the application?")
if restart != "Y":
print("Press any key to exit")
input()
break
Don't have the program exit after evaluating input from the user; instead, do this in a loop. For example, a simple example that doesn't even use a function:
phrase = "hello, world"
while (input("Guess the phrase: ") != phrase):
print("Incorrect.") //Evaluate the input here
print("Correct") // If the user is successful
This outputs the following, with my user input shown as well:
Guess the phrase: a guess
Incorrect.
Guess the phrase: another guess
Incorrect.
Guess the phrase: hello, world
Correct
or you can have two separate function written over, It's same as above(only it's written as two separate function ) :
def game(phrase_to_guess):
return input("Guess the phrase: ") == phrase_to_guess
def main():
phrase = "hello, world"
while (not(game(phrase))):
print("Incorrect.")
print("Correct")
main()
Hope this is what you are looking for .

How to validate on python to check for no user input

Hi i wrote some code for a maths program and wanted some help to validate user input. I want the program to, when the user ignores a question and simply presses the enter key for the next question, to show them the exact same question again and notify them saying every question must be attempted. Heres the code i have so far
import time
import random
msg=0
questionsAsked=0
score=0
op = ["-","*","+"]
username= input("What is your name? ")
print("Okay "+username+ " lets begin the test. Good luck!")
praise= ["Well done!","Great job!", "Spot on!", "Perfect!"]
wrong = ["Unlucky!", "Not quite", "Incorrect"]
def actual(num1,num2,operation):
actual=eval(str(num1) + operation + (str(num2)))
return actual
def useranswer(num1,num2,operation):
useranswer=int(input(str(num1)+operation+str(num2)+"= "))
return useranswer
while questionsAsked <10:
num1 = random.randint(0,12)
num2 = random.randint(0,12)
operation = random.choice(op)
praiseMsg= random.choice(praise)
wrongMsg= random.choice(wrong)
if useranswer(num1,num2,operation) != actual(num1,num2,operation):
print(wrongMsg)
else:
print(praiseMsg)
score= score+1
questionsAsked=questionsAsked+1
else:
if score>5:
msg= str("Well done "+username+"! You scored over 50%")
else:
msg=str("Better luck next time " + username)
print("You scored " +str(score)+ " out of 10. \n" +msg )
time.sleep(3)
username = raw_input("What is your name? ")
while not username:
username = raw_input("Not understood. What is your name?")
You could wrap this in a function:
def insist_upon_answer(prompt):
answer = raw_input(prompt)
while not answer:
answer = raw_input("All questions must be answered. {}".format(prompt)
return answer
and call it:
name = insist_upon_answer("What is your name?")
Like triphook's answer, for Python 3:
username = input("Input: ")
while username=="":
username = input("Input (again): ")

Categories