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.
Related
If my_input == "n" I want to my program to loop again, which works fine.
But if my else statement is True I dont want it to run the whole program again and just "start" at the my_input variable.
How can I achieve this?
def name_user_validation():
while True:
full_name = input("What is your name? ")
print(f"Hello {full_name}, nice to meet you.")
full_name.split()
print(f"If I understood correctly, your first name is {full_name[0]} and your last name is {full_name[-1]}.")
my_input = input("Is that right? (y/n) ")
if (my_input == "y"):
print("Great!")
break
elif my_input == "n":
print("Oh no :(")
else:
print("Invalid input, try again.")
name_user_validation()
I misunderstood your question, I would probably restructure your code a bit, so you get rid of your while loops and use recursive function calling to go back when you need to,
something like the below
def name_user_validation():
full_name = input("What is your name? ")
print(f"Hello {full_name}, nice to meet you.")
full_name.split() # This line actually doesn't do anything
print(f"If I understood correctly, your first name is {full_name[0]} and your last name is {full_name[-1]}.")
if not accept_input():
name_user_validation()
def accept_input():
my_input = input("Is that right? (y/n) ")
if my_input == "y":
print("Great!")
return True
elif my_input == "n":
print("Oh no :(")
return False
else:
print("Invalid input, try again.")
accept_input()
name_user_validation()
Add another loop that doesn't terminate until user enters acceptable input.
def name_user_validation():
while True:
full_name = input("What is your name? ")
print(f"Hello {full_name}, nice to meet you.")
full_name.split()
print(f"If I understood correctly, your first name is {full_name[0]} and your last name is {full_name[-1]}.")
while True:
my_input = input("Is that right? (y/n) ")
if (my_input == "y"):
print("Great!")
break
elif my_input == "n":
print("Oh no :(")
break
else:
print("Invalid input, try again.")
if my_input == 'y':
break
name_user_validation()
Edit: The program terminates only when my_input = y.
I have written some code that contains several while loops.
answer = "yes"
while answer == "yes":
name = input("what is your name?")
while len(name) > 0 and name.isalpha():
print("okay")
break
else:
print("error")
continue
job = input("what is your job?")
while job.isalpha():
print("great")
else:
print("not so great")
continue
age = input("how old are you?")
while age.isnumeric():
print('nice')
else:
print("not so nice")
continue
What I want the code to do is check for a valid name entry, and if it is invalid re-ask the user for their name. I want it to do the same thing with their job. Unfortunately, when I use continue after the job statement, instead of just re-asking for their job, it re-asks for their name as well. Does anyone know how to make it only re-ask for the job, and not re-do the whole program? Does anyone know how I could replicate this for multiple while loops I.e. Asking for job, name, age, star sign etc.?
Thank you.
You can use while True because answer never change.
It's useless while for 1 expression and 1 break.
You should put everything on a while True and check:
while True:
name = input("what is your name?")
job = input("what is your job?")
if len(name) > 0 and name.isalpha() and job.isalpha():
print("great")
break
print("error")
I moved the question into a seperate fuction to de-duplicate the code. It will ask again and again as long as the answer is not satisfactory.
def ask(s):
r = ""
while not r or not r.isalpha():
r = input(s)
return r
name = ask("What is your name?")
print("Okay. Your name is {}.".format(name))
job = ask("What is your job?")
print("Great. Your job is {}.".format(job))
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
answer = input('Hi! Would you like to say something? (No or Yes)')
if answer == No or no:
print('Okay then, have a good day!')
elif answer == Yes or yes:
answertwo = input('What would you like to say?')
print(answertwo, 'Hmmmmmm, Intresting.')
**if answer == No or no:
NameError: name 'No' is not defined**
I would suggest you using .lower() for every input. This ensures that if some types "nO" or "YeS" it takes the lowercase equivalent. Example:
ui = input("Type \"Hi\"").lower()
Next, you should really add an else option to your code. This is for answers you don't want them to type. This should be held in a while loop Example:
while(True):
ui = input("Type \"Hi\"").title()
if(ui == "Hi"):
print("Hello")
break
else:
print("That isn't a choice!")
I have researched this subject, and cannot find a relevant answer, here's my code:
#Imports#
import random
from operator import add, sub, mul
import time
from random import choice
#Random Numbers#
beg1 = random.randint(1, 10)
beg2 = random.randint(1, 10)
#Variables + Welcoming message#
correct = 0
questions = 10
print ("Welcome to the Primary School Maths quiz!!")
print ("All you have to do is answer the questions as they come up!")
time.sleep(1)
#Name#
print("Enter your first name")
Fname = input("")
print ("Is this your name?" ,Fname)
awnser = input("")
if awnser == ("yes"):
print ("Good let's begin!")
questions()
if input == ("no"):
print("Enter your first name")
Fname = input("")
print ("Good let's begin!")
#Question Code#
def questions():
for i in range(questions):
ChoiceOp = random.randint (0,2)
if ChoiceOp == "0":
print (("What is " +beg1 ,op ,beg2))
begAns = input("")
if int(begAns) == beg1*beg2:
print("That's right -- well done.\n")
correct = correct +1
else:
print("No, I'm afraid the answer is ",begAns)
if ChoiceOp == "1":
print (("What is " +beg1 ,op ,beg2))
begAns = input("")
if int(begAns) == beg1-beg2:
print("That's right -- well done.\n")
correct = correct +1
else:
print("No, I'm afraid the answer is ",begAns)
if ChoiceOp == "2":
print (("What is " +beg1 ,op ,beg2))
begAns = input("")
if int(begAns) == beg1+beg2:
print("That's right -- well done.\n")
correct = correct +1
else:
print("No, I'm afraid the answer is ",begAns)
questions()
If I'm perfectly honest I'm not quite sure what's wrong, I have had many problems with this code that this wonderful site has helped me with, but anyway this code is designed to ask 10 random addition, subtraction and multiplication questions for primary school children any help I am thankful in advance! :D
You have both a function def questions() and a variable questions = 10. This does not work in Python; each name can only refer to one thing: A variable, a function, a class, but not one of each, as it would be possible, e.g. in Java.
To fix the problem, rename either your variable to, e.g., num_questions = 10, or your function to, e.g., def ask_question()
Also note that you call your questions function before it is actually defined. Again, this works in some other languages, but not in Python. Put your def quesitons to the top and the input prompt below, or in another function, e.g. def main().