So let's say I have a function of
def question():
print("")
question_section = str("B" + str(quiz_nmbr + 1))
print("Question", str(quiz_nmbr) + ": " + str(sheet[question_section].value))
question_become = str(input("Type your question: "))
sheet[question_section].value = question_become
book.save('Quiz_Problems.xlsx')
Then let's say one time I wanted to call the question() function again.
However, I don't want print("Question", str(quiz_nmbr) + ": " + str(sheet[question_section].value)) to be printed.
Is there anyway to just remove that statement for certain condition? and by condition what I mean is let's say I wanted to call the function in if else statement (which condition matters to give different output)
Try this:
def question(prompt):
print("")
question_section = str("B" + str(quiz_nmbr + 1))
if prompt:
print("Question", str(quiz_nmbr) + ": " + str(sheet[question_section].value))
question_become = str(input("Type your question: "))
sheet[question_section].value = question_become
book.save('Quiz_Problems.xlsx')
Then, inside your if/else clause, you can call question(True) or question(False) as desired.
Related
I have this function that prints 25 lines of text and I need to input it in my tkinter page, but ever time it doesn't seem to work.
I've tried using text.input but it didn't seeem to work
This is the function I need to print:
def decode(secretmessage):
for key in range(len(alphabet)):
newAlp = alphabet[key:] + alphabet[:key]
attempt = ""
for i in range(len(message)):
index = alphabet.find(message[i])
if index < 0:
attempt += message[i]
else:
attempt += newAlp[index]
print("Key: " + str(key) + " - " + attempt)
print()
This is what I tried:
def finalprint (uncoded):
print("Key: " + str(key) + " - " + attempt)
print()
text = Text.insert(root, finalprint(message), width=450, height=450)
It doesn't work to show up for some reason.
The print command prints the given text to console. It does returns None
Your finalprint function also returns None while Text.insert expects a string as an input.
Instead of printing the output you can store the values into a string.
def finalprint(uncoded): ## may need different inputs as key and attempts are not in scope
string = ""
string = string + "Key: " + str(key) + " - " + attempts + "\n"
return string
However the input to the finalprint function is uncoded while the variables used in it are key and attempts. You may need to pass in more information to the function for it to work like you have it written.
So here is my function and some info on it:
This function is called by another function, so returning the result1 would print what I want.
So, in this function, I want to be able to print result1 then the for loop after; although, since I am unable to place the for loop inside the return, it would always print the for loop first, then the returned result1 would be printed next.
Note: Dish_str() is another function, I will include it at the bottom
def Restaurant_str(self: Restaurant) -> str:
result1 = ("Name: " + self.name + "\n" +
"Cuisine: " + self.cuisine + "\n" +
"Phone: " + self.phone + "\n" +
"Menu: ")
for i in self.menu:
print(Dish_str(i))
return result1 + "\n\n"
This is the result:
Fried Chicken ($10.00): 1300.0cal
Name: KFC
Cuisine: American
Phone: 1112223333
Menu:
I want to make it so that the dish would come after the menu.
One way that I attempted to make it work was putting the Dish_str() into the return so it would look like this:
return result1 + Dish_str(self.menu) + "\n\n"
To which, I'd receive an error that says an attribute error saying that the list does not contain attribute name, even though in the for loop, it was able to work. Then I tried doing simply just Dish_str(self) which gives me a type error that can't concatenate a list.
Another way I tried to make it work was also split the for loop into another function and have the Restaurant_str() call it, but alas, no avail because I realized it was the same exact thing as calling Dish_str() just with another extra function.
Here is the other functions that are calling it and being called on:
def Dish_str(self: Dishes) -> str:
'''Returns a string that represents the dish name, price, and calories'''
result = self.name + " ($" + str("%.2f" % self.price) + "): " +
str(self.calories) + "cal"
return result
def Collection_str(C: list) -> str:
''' Return a string representing the collection
'''
s = ""
for r in C:
s = s + Restaurant_str(r)
return s
I simply print the collection through:
print(Collection_str(C))
Please let me know if you need me to clarify anything as I wrote this late at night and didn't have time to check in the morning. Thank you for your patience and help in advance.
Just add the string dish to the end of result1, result1 = result1 + Dish_str(i)
def Restaurant_str(self: Restaurant) -> str:
result1 = ("Name: " + self.name + "\n" +
"Cuisine: " + self.cuisine + "\n" +
"Phone: " + self.phone + "\n" +
"Menu: ")
for i in self.menu:
result1 = result1 + Dish_str(i)
return result1 + "\n\n"
Would this help?
Making a math quiz in python with random equations. I'm not sure how to stop the program from asking the same thing twice?
The program asks ten questions from a list of add, subtract or multiply, each using random numbers. I've managed to make the ten questions random, but I'm not sure how to stop it from choosing the same two numbers twice? For example, it would choose 1+3 for one question, but it will ask the same question multiple times after. Here is the code:
import random
#Asks for name
name = input("What's your name?")
#Stops user from entering invalid input when entering their class
classchoices = ["A","B","C"]
classname = input("What class are you in?")
while classname not in classchoices:
classname = input("Not a valid class, try again:")
print(name, ",", classname)
print("Begin quiz!")
questions = 0
def add(a,b):
addQ = int(input(str(a) + "+" + str(b) + "="))
result = int(int(a) + int(b))
if addQ != result:
print ("Incorrect!", result)
else:
print("Correct")
a = random.randint(1,12)
b = random.randint(1,12)
def multiply(a,b):
multQ = int(input(str(c) + "X" + str(d) + "="))
results = int(int(c) * int(d))
if multQ != results:
print ("Incorrect! The answer is", results)
else:
print("Correct")
c = random.randint(1,12)
d = random.randint(1,12)
def subtract(a,b):
subQ = int(input(str(e) + "-" + str(f) + "="))
resultss = int(int(e) - int(f))
if subQ != resultss:
print ("Incorrect! The answer is", resultss)
else:
print("Correct")
e = random.randint(1,12)
f = random.randint(1,12)
while questions in range(10):
Qlist = [add, subtract, multiply]
random.choice(Qlist)(a,b)
questions += 1
if questions == 10:
print ("End of quiz")
Any help would be appreciated, thanks.
The issue here is that you are generating random numbers at the start of the program, but not regenerating them every time a question is asked: your add function will always use a and b, multiply will always use c and d, and subtract will always use e and f for all of their respective calculations, the values of which never change.
In addition, the parameters you are inputting are of no value for multiply and subtract as you are just disregarding them and using c, d and e, f respectively without note of the parameters inputted.
In order to remedy both these issues, I would place the random generation of the numbers inside the while loop and make the functions use the correct inputted parameters for calculations.
Moreover, the while iteration is a bit redundant a simple for questions in range(10) without the extra bits is much more straightforward. Hence the questions variable is useless.
With all that in mind, here is the rewritten code.
import random
#Asks for name
name = input("What's your name?")
#Stops user from entering invalid input when entering their class
classchoices = ["A","B","C"]
classname = input("What class are you in?")
while classname not in classchoices:
classname = input("Not a valid class, try again:")
print(name, ",", classname)
print("Begin quiz!")
def add(a,b):
addQ = int(input(str(a) + "+" + str(b) + "="))
result = int(int(a) + int(b))
if addQ != result:
print ("Incorrect!", result)
else:
print("Correct")
def multiply(a,b):
multQ = int(input(str(a) + "X" + str(b) + "="))
results = int(int(a) * int(b))
if multQ != results:
print ("Incorrect! The answer is", results)
else:
print("Correct")
def subtract(a,b):
subQ = int(input(str(a) + "-" + str(b) + "="))
resultss = int(int(a) - int(b))
if subQ != resultss:
print ("Incorrect! The answer is", resultss)
else:
print("Correct")
for i in range(10):
Qlist = [add, subtract, multiply]
random.choice(Qlist)(random.randint(1, 12),random.randint(1, 12))
print ("End of quiz")
The program could be refined further by creating a function that manages the printing and checking of the result dependent on a third parameter that dictates what operation it should perform.
for each problem you have asked, you can add it to a set of "asked_questions" and use "in" method to test if already asked, and if yes, generate a new question.
not sure if it's the most efficient method, but it definitely works, and more than enough for your little application.
Here is my code:
# This program makes the robot calculate the average amount of light in a simulated room
from myro import *
init("simulator")
from random import*
def pressC():
""" Wait for "c" to be entered from the keyboard in the Python shell """
entry = " "
while(entry != "c"):
entry = raw_input("Press c to continue. ")
print("Thank you. ")
print
def randomPosition():
""" This gets the robot to drive to a random position """
result = randint(1, 2)
if(result == 1):
forward(random(), random())
if(result == 2):
backward(random(), random())
def scan():
""" This allows the robot to rotate and print the numbers that each light sensors obtains """
leftLightSeries = [0,0,0,0,0,0]
centerLightSeries = [0,0,0,0,0,0]
rightLightSeries = [0,0,0,0,0,0]
for index in range(1,6):
leftLight = getLight("left")
leftLightSeries[index] = leftLightSeries[index] + leftLight
centerLight = getLight("center")
centerLightSeries[index] = centerLightSeries[index] + centerLight
rightLight = getLight("right")
rightLightSeries[index] = rightLightSeries[index] + rightLight
turnRight(.5,2.739)
return leftLightSeries
return centerLightSeries
return rightLightSeries
def printResults():
""" This function prints the results of the dice roll simulation."""
print " Average Light Levels "
print " L C R "
print "========================="
for index in range(1, 6):
print str(index) + " " + str(leftLightSeries[index]) + " " + str(centerLightSeries[index]) + " " + str(rightLightSeries[index])
def main():
senses()
pressC()
randomPosition()
scan()
printResults()
main()
So, I am getting this error when I run my program.
NameError: global name 'leftLightSeries' is not defined
I understand that I must be doing something wrong related to the return statement. I'm not sure if I can only return one variable at the end of a user-defined function. If that were to be true, then I should probably separate the scan(): function. Anyways, I would appreciate any help on how to fix this error. Also, this is the result that I am looking for when I successfully complete my program:
Click Here
I am looking to complete the average values like the picture shows, but I am not worried about them at this point, only the list of values from the light sensors. I do not need to reach those exact numbers, the numbers will vary in the simulator.
If you want to return multiple items from scan(), don't use three separate return statements. Instead, do this:
return leftLightSeries, centerLightSeries, rightLightSeries
Also, when you call the function, you have to assign variable(s) to the returned values; it won't automatically create new local variables with the same names. So in main, call scan() like this:
leftLightSeries, centerLightSeries, rightLightSeries = scan()
I am making a Recipe book, at the moment I have the ability to create a recipe, but now I am starting to build the module of searching and displaying stored recipes.
At the moment I have a .txt document with the contents along the lines of:
Williams Special Recipe
Ingredients:
bread: 120 grams
butter: 1234 grams
Recipe Serves: 12
I then ask the user how many they are serving and based on how many the recipe serves, I need to multiply all the ingredients quantity by that number. I then need to print that off with the full recipe again.
I was wondering how I would go about achieving this result, not asking specifically for a coded response as an answer, but I would greatly appreciate how I would approach this task and any specific functions required.
I have also included my code so far, I appreciate the fact it is incredibly un-organised at the moment, and probably hard to understand, but I included it for any reference.
(I have also created a .txt file of all the created recipes which will be implemented later on as a way of displaying to the user all recipes, but at the moment it is just set up for searching.)
#Recipe Task
import os.path
def file_(n):
if n == "listR" :
list_f = open("list_recipes.txt", "a+")
list_f.write(new_name + "\n")
if n == "oar": #open append read
f=open(new_name + ".txt","a+")
elif n == "c": #closes file
f.close()
def print_line(x): #ease of printing multiple lines to break up text
for c in range(x):
print ""
def new_ingredients(): #adding new ingredients
f.write("Ingredients:" + "\n" + "\n")
fin_ingredient = False
while fin_ingredient != True :
input_ingredient = raw_input("New ingredient:" + "\n").lower()
split_ingred = input_ingredient.split()
if input_ingredient == "stop": #stops asking questions when user types 'stop'
fin_ingredient = True
else :
f.write(split_ingred[0] + ":" + " " + split_ingred[1] + " " + split_ingred[2] + "\n")
def search_recipe(n): #searching for recipes
n = n + ".txt"
if os.path.isfile('/Users/wjpreston/Desktop/' + n) == True :
print "Recipe Found..."
found_recipe = open(n)
print found_recipe.read()
append_serving = raw_input("Would you like to change the number of people you are serving?" + "\n").lower()
if append_serving == "yes" :
appended_serving = input("How many would you like to serve?" + "\n")
with open(n) as f: #here is my issue - not sure where to go with this!!
list_recipe = f.readlines()
found_recipe.close()
else :
print "fail"
else:
print "No existing recipes under that name have been found."
print "Welcome to your Recipe Book"
print_line(3)
recipe_phase = raw_input("Are you 'creating' a recipe or 'viewing' an existing one?" + "\n").lower()
if recipe_phase == "creating":
new_name = raw_input("Name of Recipe: " + "\n")
file_("listR")
file_("oar")
f.write("------------" + "\n" + new_name + "\n" + "\n")
print "Ingrediants required in the format 'ingredient quantity unit' - type 'stop' to end process"
new_ingredients()
new_num = input("Number serving: ")
f.write("\n" + "Recipe Serves: " + str(new_num) + "\n" "\n" + "\n")
file_("c")
elif recipe_phase == "viewing":
search = raw_input("Search for recipe: ")
search_recipe(search)
I'm not the specialist in processing strings, but I'd approach your problem following way:
Save each ingredient on a new line.
Split the loaded string by "\n".
Then process the list with some for-loops while creating two dicts, one for the actual data
e.g. {"bread": 4, "butter": 7}
and one for the types of each ingredient:
e.g. {"bread": grams, "butter": grams}
The you should also save how many serves the recipe is written for, and maybe the order of the ingredients (dicts get stored in a random order):
e.g. ["bread", "butter"]
After that, you can ask your costumer how many serves he has and then finally calculate and print the final results.
for ing in ing_order:
print ing+":", ing_amount[ing]*requested_serves/default_seves, ing_types[ing]
...hopyfully you still have enough challange, and hopefully I understood your question correctly.