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().
Related
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 am new to coding and I am learning python. I’m trying to write a simple program to test my skills, but I’m having some difficulties with it; I want to turn it into a function in order to make the program cleaner, but I get this error: http://prntscr.com/im5pt7
Here is what I want to put inside a function:
name = input(str("\nFull Name: "))
position = input(str("Position at the company: "))
print("\nConfirm Staff Data:\n")
name_confirm = "Name: %s"%(name)
position_confirm = "Position: %s"%(position)
print(name_confirm)
print(position_confirm)
confirmAns = input("Is the information right? (Y/N)")
if confirmAns == "y" or confirmAns == "Y":
message = "\nSearching for %s"%(name)
print(message)
hoursWorked = int(input("Insert hours worked: "))
if hoursWorked <= 0:
print("Please insert a valid number")
elif hoursWorked > 0:
print("\nCalculete Paycheck")
hourRate = int(input("Insert the rate of each hour worked: "))
bonus = input("If a bonus was given insert it here: ")
fine = input("If a fine was given insert it here: ")
print('\n')
payment = hoursWorked*hourRate-int(fine)+int(bonus)
paymentMsg = "Your Payment is: $%d"%(payment)
print(paymentMsg)
elif confirmAns == "n" or confirmAns == "N":
ctypes.windll.user32.MessageBoxW(0, "The software will close to avoid slowness.", "Warning", 1)
else:
print("Please answer with Y or N")
I've tried this but it did not work.
Here is all the code (working but with out the function so I need to copy and paste code): https://pastebin.com/PA9mxMkk
What is happening is that the function as other statements needs to hold it's code into a new indentation level
print('a')
def test(var):
print(var)
not this way
print('a')
def test(var):
print(var)
because this way it will give you the error that you are seeing.
All python code should be indented after the ':' character, in python the indentation should be 4 spaces, or people use the tab key, your code has an issue with indentation which I can't be bothered finding;
for example a 'class'
class this_is_a_class():
#indentation
#code goes here
pass
or a 'for loop' or 'while loop';
numbers = [0,1,2,3,4,5,6,7,8,9]
for number in numbers:
#indentation
print(number)
x = 0
while x < 10:
#indentation
x += 1
print('This is going to print 10 times')
or an 'if statement';
true_boolean = True
if true_boolean:
#indentation
print(True)
or a 'function';
def function():
#indentation
print('You have called a function')
What is actually happening, is python is reading through your code 'Token' by token and 'interpreting' what your code does. But considering you don't know what a function is; gloss over this paragraph.
Now for your question about how functions work. A function is used organize code. You can call a function multiple times, which makes your code more organized and easier to work with, this is why as your code got longer, you ran into this problem; Lets for example say i wanted to print 'hello world' 10 times.
I could write this code on 10 seperate lines;
print("hello world")
print("hello world")
#etc... More chance for error
or I could use a function and call it 10 times;
def say_hello_world():
#indentation
print("hello world")
for each_call in range(0,10):
say_hello_world() #This is the function call
You can also pass 'arguments into a function' for example;
def say_hello(person):
#indentation
print('hello', person)
say_hello('Alex')
Now any words that are in quotations in this answer can be google searched with the word 'python' and you can find out much more about how python works.
I hope this gets you started with python. Although all of these concepts can be used in other programming languages.
The first step which is often difficult in learning python in understanding indentation.
for example.
def hello_world(world):
print("hello ", world)
#your function code goes here.
#you need to indent back to be out of function block.
hello_world("there!")
out: hello there
so in your case it should be like this.
def AnsNo():
name = input(str("\nFull Name: "))
position = input(str("Position at the company: "))
print("\nConfirm Staff Data:\n")
name_confirm = "Name: %s"%(name)
position_confirm = "Position: %s"%(position)
print(name_confirm)
print(position_confirm)
confirmAns = input("Is the information right? (Y/N)")
if confirmAns == "y" or confirmAns == "Y":
message = "\nSearching for %s"%(name)
print(message)
hoursWorked = int(input("Insert hours worked: "))
if hoursWorked <= 0:
print("Please insert a valid number")
elif hoursWorked > 0:
print("\nCalculete Paycheck")
hourRate = int(input("Insert the rate of each hour worked: "))
bonus = input("If a bonus was given insert it here: ")
fine = input("If a fine was given insert it here: ")
print('\n')
payment = hoursWorked*hourRate-int(fine)+int(bonus)
paymentMsg = "Your Payment is: $%d"%(payment)
print(paymentMsg)
elif confirmAns == "n" or confirmAns == "N":
print("working")
else:
print("Please answer with Y or N")
return
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
when I try to run this module
from import random
def guessnum():
randomnum = random.randint(1,6)
awnser = input ("what do you think the number is? ")
if awnser==randomnum:
print ("good job. you are correct. ")
else:
print ("incorrect. better luck next time. ")
restart = input ("would you like to try again? ")
if restart = Yes or y:
guessnum()
else:
end()
I get invalid syntax highlighting the import.
what is the issue?
I have already tried import random but it doesn't seem to want to work
Your code is full of errors. I have fixed indentation and other syntax issues.
You don't need to use from, just use import random.
Here is the code
import random
def guessnum():
randomnum = random.randint(1,6)
awnser = input ("what do you think the number is? ")
if awnser==randomnum:
print ("good job. you are correct. ")
else:
print ("incorrect. better luck next time. ")
restart = input ("would you like to try again? ")
if restart == "Yes" or "y":
guessnum()
else:
end()
Fixed your indentation, spelling, capitalization, insertion of unnecessary spaces and comparing between a string and int which would always be false.
Also added str.title to allow for all types of capitalization for restart
import random
import sys
def guessnum():
random_num = random.randint(1,6)
answer = int(input("What do you think the number is? "))
if answer == random_num:
print("Good job. you are correct!")
else:
print("Incorrect. Better luck next time. The number was %d" % random_num)
restart = input("Would you like to try again? ")
if restart.title() in ["Yes", "Y"]:
guessnum()
else:
end()
def end():
print("Goodbye!")
sys.exit(0)
guessnum()
Just started to code, can't figure out why the start function will not ask me for any user input.
import random
number = random.randint(1,6)
def start():
print("Do you want to start?")
answer = raw_input("Type 'Yes' to start!") #Asks me for user input... Doesn't work
if answer == "yes":
print("Rolling the dice... The number is... " + number)
else:
print("Aww :( ")
You want to give consideration to your program as a module.
Try making the following changes:
import random
_NUMBER = random.randint(1,6)
def start():
print("Do you want to start?")
answer = raw_input("Type 'Yes' to start!")
if answer == "yes":
print("Rolling the dice... The number is... " + _NUMBER)
else:
print("Aww :( ")
if __name__ == "__main__":
start()
The "if name"... addition allows your program to be run from the interpreter as a module. You can also import this module into other programs easily.
I've also changed the syntax on your global variable (number) to reflect best practices. It's now private -- indicated by the underscore -- and uppercase.
If this program is imported as a module, the global variable won't impact those of the same name.
Now you can do python filename.py from the command line, or from filename import start and start() from the interpreter to run your program.
You have to call the function.
start()
Working script:
import random
number = random.randint(1,6)
def start():
print("Do you want to start?")
answer = raw_input("Type 'Yes' to start!")
if answer == "yes":
print "Rolling the dice... The number is... ", number
else:
print("Aww :( ")
start()
You never actually call the function:
number = random.randint(1,6)
def start():
print("Do you want to start?")
answer = raw_input("Type 'Yes' to start!")
if answer == "yes":
print("Rolling the dice... The number is... " + number)
else:
print("Aww :( ")
start()
Just like the other two said, you haven't called the function "start()". Also you asked to type "Yes" but you check if the user gave "yes".