Get data from another function [closed] - python

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
i have a short question, im trying to make a quiz program, however. i want a functions data to be shared across the program,
so how do i make so the ask function gen get the data from getQuestion?
import random
All_questions = ["whats obamas last name ","Riclug is snygg ","Are traps gay "]
questions_Right = ["care","no","no"]
points = 0
tries = 3
ListNumber = len(All_questions)
def getQuestion():
question_number = random.randint(0, ListNumber - 1)
right_anwser = questions_Right[question_number]
Question = All_questions[question_number]
def ask(Question,right_anwser):
print("The question is: ")
anwser = input(Question+": ").casefold()
if anwser == right_anwser:
print("yes,", right_anwser,"was right\n")
All_questions.remove(Question)
questions_Right.remove(right_anwser)
else:
print("Sorry, but the answer was", right_anwser,"\n")
while True:
if ListNumber == 0:
print("Game over")
break
else:
print(ListNumber)
getQuestion()
ask()
print(All_questions)

import random
All_questions = ["whats obamas last name ","Riclug is snygg ","Are traps gay "]
questions_Right = ["care","no","no"]
def getQuestion(All_questions, questions_Right):
question_number = random.randint(0, len(All_questions) - 1)
right_answer = questions_Right[question_number]
question = All_questions[question_number]
return question, right_answer # added this to return the data
def ask():
Question, right_answer = getQuestion(All_questions, questions_Right)
answer = input(f"The question is :\n{Question} :").casefold()
if answer == right_answer:
print(f"Yes, {right_answer} was right\n")
All_questions.remove(Question)
questions_Right.remove(right_answer)
else:
print(f"Sorry, but the answer was {right_answer}\n")
while True:
if len(All_questions) == 0:
print("Game over")
break
else:
ask()
1 - you can return the needed data by doing:
return question, right_answer
2 - since the questions list will change every round it is better to pass it to the getQuestion method instead of using the global one directly and use len(All_questions) to get the new length every round:
def getQuestion(All_questions, questions_Right)
3 - some advice :
use snake casing
get_question
# instead of :
getQuestion
don't use global variables inside functions:
A = 1
def add(a, b):
return a + b
add(A, 5)
# instead of
A = 1
def add_to_A(b):
return A + b
add_to_A(5):
format your code properly and make sure that you name variables correctly.

Just simply use return:
def getQuestion():
# ... your code
return (Question, rightAnswer)
#... your code
Question, rightAnswer = getQuestion()
And maybe try to use a dictionary, instead of an question and an answer-array. That would fit better.
I recommend you to do further reading and make some tutorials, before you go on with your quiz-game:
About functions:
https://www.programiz.com/python-programming/function
About dictionaries:
https://www.programiz.com/python-programming/dictionary

Related

Why does the following python code print 4 lines instead of 3? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
def beauty():
print("Belle")
return "Beast"
def gaston():
if beauty() == "Beast":
print("No one’s as slick")
elif beauty() == None:
print("No one’s as quick")
if beauty() == "Belle":
print("What a guy")
else:
print("Belle")
gaston()
Can anyone please explain why the code above is printing 4 lines instead of 3?
When you are checking for if beauty() is equal to text, the function is being called. And you have multiple if/elif statements... So the unction is being called more than once. So I suggest calling the function once and storing that in a variable.
def beauty():
print("Belle")
return "Beast"
def gaston(butty):
if butty == "Beast":
print("No one’s as slick")
elif butty == None:
print("No one’s as quick")
if butty == "Belle":
print("What a guy")
else:
print("Belle")
butty = beauty()
gaston(butty)

Add yes/no confirmation in python 3.X [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have a function that allows a user the ability to add data via input. I would like to add a confirmation step that will allow them to answer yes or no to continue. If they select no it should allow them to restart the function of adding data to the list. I also want to make sure they answer with Y, YES, y, yes, N, NO, n, no. What would be the best way to accomplish this? I've tried several solution I've found online but I end up not being able to get out of the loop of asking yes or no. Thanks in advance.
def item_list(): # Create a list
items = []
item_int = 0
while 1:
item_int += 1
item = input("\nEnter item %d or Press Enter: " % item_int)
if item == "":
break
items.append(item)
return items
items = item_list()
print(items)
answer = input("Continue?")
if answer.lower() in ["y","yes"]:
# Do stuff
else if answer.lower() in ["n","no"]:
# Do other stuff
else:
# Handle "wrong" input
My answer would be extension of #B. Plüster but it allows slightly bigger range of the inputs and prevent rejections of case-sensitive typos:
answer = input("Continue?")
if answer.upper() in ["Y", "YES"]:
# Do action you need
else if answer.upper() in ["N", "NO"]:
# Do action you need
You could create a wrapper function which calls your other function. In the wrapper function, use another loop to confirm items.
# wrapper function
def item_list_wrapper():
while True:
# call your function at the start of each iteration
final_items = item_list()
# confirm with the user
print('\nThese are your items:', ', '.join(final_items))
user_input = input('Confirm? [Y/N] ')
# input validation
if user_input.lower() in ('y', 'yes'):
break
elif user_input.lower() in ('n', 'no'): # using this elif for readability
continue
else:
# ... error handling ...
print(f'Error: Input {user_input} unrecognised.')
break
return final_items
# your original function
def item_list():
items = []
item_int = 0
while 1:
item_int += 1
item = input("\nEnter item %d or Press Enter: " % item_int)
if item == "":
break
items.append(item)
return items
Then call it as you'd normally call it.
items = item_list_wrapper()
print(items)
In the item_list_wrapper function, note that the line with items = item_list() will renew the list every time. If you want the user to continue adding existing items, you could switch the order of commands around.
def item_list_wrapper():
final_items = item_list() # call the function at the start
while True:
# confirm with the user
print('\nThese are your items:', ', '.join(final_items))
user_input = input('Confirm? [Y/N] ')
# input validation
if user_input.lower() in ('y', 'yes'):
break
elif user_input.lower() not in ('n', 'no'):
# ... error handling ...
print(f'Error: Input {user_input} unrecognised.')
break
# call your function at the start of each iteration
new_items = item_list()
# add new items to previous items
final_items += new_items
return final_items
Don't know whether this is efficient enough.
items = list()
tr = [" Y", "YES", "y", "yes"]
fs = ["N", "NO", "n", "no"]
item_int = 0
def item_list(): # Create a list
global item_int
global items
response = input("\nDo you want to enter data: ")
if response == "":
return
if response in tr:
item_int += 1
item = input("\nEnter item %d or Press Enter: " % item_int)
items.append(item)
elif response in fs:
item_int=0
print("List cleared!")
items.clear()
item_list()
item_list()
print(items)

Replacing string character in python [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I am making a program where the user inputs some text, and I wan't all the characters in that text that is not in the variable "alfabet" to be changed to "?". How can I do this? I also want a to do it in two functions, main and clean_text. My code looks like this now:
def clean_text():
for char in text:
if char in alfabeth:
continue
elif char not in alfabeth:
#don't know what to do here
#text[] = "?"
def main():
userInput = input("type in text: ")
text = list(userInput)
if__name__ == "__main__":
main()
clean_text(text)
This would be the basic code you need:
alfabeth = 'abcdefghijklmnopqrstuvwxyz'
text_in = list(input('What ever'))
for x in range(len(text_in)):
if text_in[x] in alfabeth:
continue
else:
text_in[x] = '?'
text_in = "".join(text_in)
print(text_in)
If you want you can define everything as one function or two or what ever you like.
Hope it helps
This is how it can look with functions. It worked for me.
alfabeth = 'abcdefghijklmnopqrstuvwxyz'
def clean_text(text_in, alfabeth):
for x in range(len(text_in)):
if text_in[x] in alfabeth:
continue
else:
text_in[x] = '?'
def main():
global UsrInput
UsrInput = list(input('type in text: '))
return UsrInput
if __name__ == "__main__":
main()
clean_text(UsrInput, alfabeth)
print("".join(UsrInput))
You have to return something to be able to assign that user_input to a variable to pass into clean_text(). Here is a working version of your project. This will handle multiple words separated by space as well.
def clean_text(word):
alphabeth = 'vshthstmpd'
for idx, item in enumerate(word):
if item == ' ':
pass
elif item not in alphabeth:
word[idx] = '?'
return ''.join(word)
def main():
user_input = input('Type in text: ')
text = list(user_input)
return text
if __name__ == '__main__':
text = main()
print(clean_text(text))
Type in text: vash the stampede
v?sh th? st?mp?d?

How do I get a python program to rerun itself [duplicate]

This question already has answers here:
How do I re-run code in Python?
(9 answers)
Closed 6 years ago.
I want the code below to automatically rerun itself any ideas hwo to do this? Btw I am new to stack overflow and python itself so If I am doing anything wrong on either please let me know, Thanks
import sys
import os
import random
answer_correct_message = random.choice(['Well done', 'Correct answer','Nice one','Thats correct!'])
answer_wrong_message = random.choice(['Unlucky','Thats wrong','Nope'])
random_num_1 = random.randint(1,10)
random_num_2 = random.randint(1,10)
def question_asker_and_answerer():
q2 = input("What is " + str(random_num_1) + " + " + str(random_num_2) + "?")
if q2 == random_num_1 + random_num_2:
the_questions = True
if the_questions == True:
return (answer_correct_message)
else:
return (answer_wrong_message)
else:
the_questions = False
if the_questions == True:
return (answer_correct_message)
else:
print(answer_wrong_message)
print question_asker_and_answerer()
This is not a situation where you are need a program to rerun itself. That sort of requirement is when you want a script to run as a daemon. This is simply a matter of creating a loop
while True:
print question_asker_and_answerer()
There are two problems here:
how to iterate;
how to make sure that the various randomly-chosen variables are different each pass through.
Just looping over the existing function, or getting it to recurse (as in a couple of other answers) solves the first of these problems (actually, recursing really doesn't, since Python doesn't have tail-call elimination, so it will run out of stack eventually).
To solve both of them you need to make the randomly-chosen variables local to the function, and then loop. I have also modified it so it returns the string to print rather than printing it, in the case of a wrong answer (last line of function).
import sys
import os
import random
def question_asker_and_answerer():
answer_correct_message = random.choice(['Well done', 'Correct answer',
'Nice one','Thats correct!'])
answer_wrong_message = random.choice(['Unlucky','Thats wrong','Nope'])
random_num_1 = random.randint(1,10)
random_num_2 = random.randint(1,10)
q2 = input("What is " + str(random_num_1) + " + " + str(random_num_2) + "?")
if q2 == random_num_1 + random_num_2:
the_questions = True
if the_questions == True:
return (answer_correct_message)
else:
return (answer_wrong_message)
else:
the_questions = False
if the_questions == True:
return (answer_correct_message)
else:
return (answer_wrong_message)
while True:
print question_asker_and_answerer()

How do I display the count in the Password: [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
for attempt in range(5):
password = input("Password: ")
if password == "changeme":
print("Thou Shall Pass Into Mordor")
break
else:
print("Thou Shall Not Pass Into Mordor")
I need help so it displays the tries into password like this:
Password(1 attempts):
Your attempt variable holds the number of tries. Concatenate that with a print statement in your for loop.
Edit: Deleted Add 1, it is not necessary.
password_attempt = 0
for attempt in range(5):
password = input("Password: ")
if password == "changeme":
print("Thou Shall Pass Into Mordor")
break
else:
password_attempt += 1
print("Thou Shall Not Pass Into Mordor")
print(Password(%s attempt(s)) %password_attempt
I just made a little change to the code you posted to match yours needs.
for attempt in range(1, 5): # Change range to be 1 - 5.
password = input("Password (%d attempts): " % attempt) # Change input message showing attempt number.
if password == "changeme":
print("Thou Shall Pass Into Mordor")
break
else:
print("Thou Shall Not Pass Into Mordor")

Categories