I'm trying to write the basic code for a random name generator in Python. This will soon become a fully working web application with an easy-to-use GUI but for some reason the program doesn't work.
When I run the program, it asks the user to specify either "console" or "game". When I enter "game" it still carries on with the if route instead of the else route.
import string
#This is a Name Generato
print("Welcome To the first version of my name generator at the moment there is only 20 names but in the final version there will be 200 names with over 25 different tags")
print("First of all what do you need a Console or a game Name?")
console = input()
if (console):
print("is it a,PS4,PS3,XBOX 360,XBOX ONE or PC")
print("NOTE:Wii,PSP and DS are not supported")
consolename = input()
print("The,",consolename)
print("Is good")
print ("now give me one or two key words that you would like in your name out of...")
print("happy,sad,depressed,fox,cow,cat,dog,wolf,lion,lil,lazy,forgetful,gaming,xxx,orthodox,apex,toXic")
firstname1=input()
secondname=input()
print(firstname1)
print(secondname)
print("Good Choice")
else:
print("What game is it?")
print("Minecraft,Black ops 1//2/3,COD,Halo1/2/3/4/5/CE/Reach,Terraria,World of warcraft,League Of Legends")
print("NOTE:Type the Game As you see it!")
game1 = input()
print("Ah good choice eh")
You are getting a string input and you are checking if its True which is always true if its not empty. You need to compare your console variable to a string. Something like this will do the job.
import string
#This is a Name Generato
print("Welcome To the first version of my name generator at the moment there is only 20 names but in the final version there will be 200 names with over 25 different tags")
print("First of all what do you need a Console or a game Name?")
console = input()
if (console=="console" or console=="Console"):
print("is it a,PS4,PS3,XBOX 360,XBOX ONE or PC")
print("NOTE:Wii,PSP and DS are not supported")
consolename = input()
print("The,",consolename)
print("Is good")
print ("now give me one or two key words that you would like in your name out of...")
print("happy,sad,depressed,fox,cow,cat,dog,wolf,lion,lil,lazy,forgetful,gaming,xxx,orthodox,apex,toXic")
firstname1=input()
secondname=input()
print(firstname1)
print(secondname)
print("Good Choice")
else:
print("What game is it?")
print("Minecraft,Black ops 1//2/3,COD,Halo1/2/3/4/5/CE/Reach,Terraria,World of warcraft,League Of Legends")
print("NOTE:Type the Game As you see it!")
game1 = input()
print("Ah good choice eh")
Related
I am making trying to make a text base game and I want to make a level selection
print ("You and your crew are pinned in the remains of a church on the top floor, with two wounded. Being fired at by German machine guns, matters will soon only get worse as you see German reinforcements on their way. Find a way to escape with your 9 man crew with minimal casualties.")
#Start up Menu
print ("Before you start the game ensure that you are playing in fullscreen to enhance your gaming experience")
print("")
print ("")
time.sleep(1)
print ("Menu")
print ('Instructions: In this game you will be given a series of paths. Using your best judgment you will choose the best path by using the "1" or "2" number keys, followed by pressing the "enter" button')
print ('If the wrong path is selected, there will be consequences of either death, or a lower final score.')
print ('Death will end the game, and you will be forced to start from the beginning of the level.')
time.sleep(1)
print ('If you will like to restart, press "r"')
print ('If you will like to quit, press "q"')
print ('If you want to play level 1, press "a"')
print ('If you want to play level 2, press "s"')
print ('you cannot restart or quit at this time')
print ('')
print ('')
def levelselection():
level=""
while level != "1" and level != "2":
level = input("Please select a level to play: ")
return level
over here, why does it say "level is not defined? and how can I fix it so the program works?
levelselection()
if level == "1":
print ("good job!")
First of all , level is a local variable to your function levelselection .
After that you are returning level variable but not saving it to some other variable.
Do like this -
levelselected = levelselection()
if levelselected == "1":
print ("good job!")
I would suggest you to read about python variables scope, this is a good source.
Explanation:
As level is initialized within the function levelselection you won't have access to the variable outside the function.
Solution:
1.You can fix this with defining level in a global scope.
2.Also, you can return level from the function as you did, but you will need to catch this return value, for example:
level = levelselection()
if level == "1":
print ("good job!")
you forgot to indent the return level. So in your current code, the return doesn't belong to the levelselection()function.
Try this:
def levelselection():
level=""
while level != "1" and level != "2":
level = input("Please select a level to play: ")
return level
level = levelselection()
if level == "1":
print("good job!")
How can I link the second info() call to a text file ?
print("Hi,welcome to the multiple choice quiz")
def info ():
print("Firstly we would like to collect some personal details:-?")
name = input("Please enter your first name?")
surname =input ("please enter your surname?")
email_address = input ("please enter your email addres #.co.uk")
username = input (" Chose a username?")
password = input ("Enter a Password?")
validation()
def validation():
correct = 0
while correct == 0:
correct=input(" is the following data is correct ?")
if correct in ["Y,y"]:
print("Well done you have registered for the quiz")
elif correct in ["N,n"]:
info()
else:
info()
You might want to drop your while loop.
info() calls your validation. "if" the data is correct, you finish, "else" you just call info() again.
That is pretty much what you did already. maybe you wanted it to look more like this:
print("Hi, welcome to the multiple choice quiz")
def info ():
print("Firstly we would like to collect some personal details:-?")
name = input("Please enter your first name?")
surname = input("please enter your surname?")
email_address = input("please enter your email address #.co.uk")
username = input(" Chose a username?")
password = input("Enter a Password?")
validation()
def validation():
correct = 0
correct = input(" is the data is correct ?")
if correct in ["Y,y"]:
print("Well done you have registered for the quiz")
elif correct in ["Y,y"]:
info()
else:
print "please type y or n"
validation()
info()
You wrote:
if correct in ["Y,y"]:
print("Well done you have registered for the quiz")
elif correct in ["N,n"]:
info()
else:
info()
Firstly, correct in ["Y,y"] will not do what you expect. ["Y,y"] is a list containing one element: "Y,y". That means correct in ["Y,y"] if and only if correct == "Y,y", and the user is not likely to enter that! You probably want a list with two elements: ["Y", "y"]. in can also test containment within strings, so you could use "Yy". You don't want a comma in there because then if the user enters just a comma that will pass the test as well, which is silly.
Putting that issue aside, if the user enters y or Y, it prints well done. If they enter n or N, info() is called. If they enter something else, info() is still called. That last part is surely not what you want: entering "N" and entering "A" should have different results! You want the user to be told that it's not valid. That part is easy, print a message. Then you want them to be asked again. Since they'll be asked for every iteration of your while loop, you just have to ensure that the loop continues. The loop will run as long as the condition correct == 0 is true, so just set correct to 0 and that will happen. So something like this:
else:
print("That's not valid")
correct = 0
OK, now to your question. You want to save those personal details to a file. You can't do that properly with the way your program is organised. The variables in info are local, so validation can't access them to save them. info has to do the saving (perhaps indirectly by passing the data along to another function). What we could do is have validation report the result of asking the user and let info decide what to do based on that:
def info ():
# collect data
if validation():
# save data
def validation():
correct = 0
while correct == 0:
correct=input(" is the following data is correct ?")
if correct in ["Y", "y"]:
print("Well done you have registered for the quiz")
return True
elif correct in ["N", "n"]:
return False
else:
print("That's not valid")
correct = 0
return will exit the validation function (thus ending the loop) and give the value returned to info to decide if the data should be saved.
Since the return statements end the loop, the only way the loop can continue is the else is reached, in which case explicitly making it continue with correct = 0 is silly. We can just make the loop go on forever until the function returns:
def validation():
while True:
correct=input(" is the following data is correct ?")
if correct in ["Y", "y"]:
print("Well done you have registered for the quiz")
return True
elif correct in ["N", "n"]:
info()
return False
else:
print("That's not valid")
I am trying to get my program to output two variables to a text file after it finishes running something but all I get is the folder and no text files inside of it. Here is the code in question:
I have edited to include the entire program.
import random #needed for the random question creation
import os #needed for when the scores will be appended to a text file
#import csv #work in progress
answer = 0 #just to ensure a strage error isn't created by the input validation (since converting to a global variable isn't really needed)
global questionnumber #sets the question number to be a global variable so that
questionnumber = 0
global score
score = 0
global name
name = "a"
def check_input(user_input): #used to verify that input by user is a valid number
try: #the condition that does the checking
answer = int (user_input)
except ValueError: #what to do if the number isn't actually a number
return fail() #calls the failure message
return answer #sends the answer back to the rest of the program
def fail(): #the failure message procedure defined
print("That isn't a whole number! Try again with a different question") #tells the user what's going on
global questionnumber #calls the global variable for this procedure
questionnumber = questionnumber - 1 #allows the user, who made a mistake, a second chance to get it right
def questions(): #the question procedure defined
global name
name=input("Enter your name: ") #gets the user's name for logging and also outputting messages to them
print("Hello there",name,"! Please answer 10 random maths questions for this test!") #outputs welcome message to the user
ClassOfStudent=input("Which class are you in?") #gets the user's class for logging
finish = False
while finish == False: #only occurs if "finish" isn't set to true so that the questions asked don't exceed ten
global questionnumber #calls the global variable
global score
choice = random.choice("+-x") #uses the random function to choose the operator
if questionnumber < 10 | questionnumber >= 0: #validation to ensure the question number is within ten
number1 = random.randrange(1,12) #uses random numbers from the random function, above 1 and below 12
number2 = random.randrange(1,12) #same as the abovem for the second number
print((number1),(choice),(number2)) #outputs the sum for the student to answer
answer=check_input((input("What is the answer?"))) #asks for the student's answer
questionnumber = questionnumber + 1 #adds one to the numebvr of questions asked
if choice==("+"): #if the ramdomly generated operator was plus
correctanswer = number1+number2 #operator is used with the numbers to work out the right answer
if answer==correctanswer: #checks the studen't answer is right
print("That's the correct answer") #if it is, it tells the student
score = score + 1 #adds one to the score that the user has
else:
print("Wrong answer, the answer was",correctanswer,"!") #if the answer is wrong, it tells the student and doesn't add one to the score
if choice==("x"): #essentially the same as the addition, but with a multiplicatin operator instead
correctanswer = number1*number2
if answer==correctanswer:
print("That's the correct answer")
score = score + 1
else:
print("Wrong answer, the answer was",correctanswer,"!")
elif choice==("-"): #essentially the same as the addition, but with a subtraction operator instead
correctanswer = number1-number2
if answer==correctanswer:
print("That's the correct answer")
score = score + 1
else:
print("Wrong answer, the answer was",correctanswer,"!")
else: #if the number of questions asked is ten, it goes on to end the program
finish = True
else:
print("Good job",name,"! You have finished the quiz") #outputs a message to the user to tell them that they've finished the quiz
print("You scored " + str(score) + "/10 questions.") #ouputs the user's score to let them know how well they've done
#all below here is a work in progress
#Create a new directory for the scores to go in, if it is not there already.
if os.path.exists("Scores") == False:
os.mkdir("Scores")
os.chdir("Scores")
if ClassOfStudent==1: #write scores to class 1 text
file_var = open("Class 1.txt",'w+')
file_var.write("name, score")
file_var.close()
if ClassOfStudent==2: #write score to class 2 text
file_var = open("Class 2.txt",'w+')
file_var.write(name, score)
file_var.close()
if ClassOfStudent==3: #write score to class 3 text
file_var = open("Class 3.txt",'w+')
file_var.write(name, score)
file_var.close()
questions()
ClassOfStudent is a string rather than a number, so none of the code that writes to the file will get executed. You can easily verify that by adding a print statement under each if so you can see if that code is being executed.
The solution is to compare to strings, or convert ClassOfStudent to an i teger.
Use print(repr(ClassOfStudent)) to show the value and type:
>>> ClassOfStudent = input("Which class are you in?")
Which class are you in?2
>>> print(repr(ClassOfStudent))
'2'
Using input() in Python 3 will read the value in as a string. You need to either convert it to an int or do the comparison against a string.
ClassOfStudent = int(input("Which class are you in?")
should fix your problem.
first you have a problem with the "". you have to correct the following:
if ClassOfStudent==2: #write scores to class 1 text
file_var = open("Class 2.txt",'w+')
file_var.write("name, score")
file_var.close()
if ClassOfStudent==3: #write scores to class 1 text
file_var = open("Class 3.txt",'w+')
file_var.write("name, score")
file_var.close()
notice that I added the "" inside the write.
In any case, I think what you want is something like:
file_var.write("name %s, score %s"%(name,score)). This should be more appropriate.
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 .
I need to write the last three scores of students and their names into a text file for the teacher's program to read and sort later.
I still don't know how to save the last 3 scores
I have tried this so far:
#Task 2
import random
name_score = []
myclass1= open("class1.txt","a")#Opens the text files
myclass2= open("class2.txt","a")#Opens the text files
myclass3= open ("class3.txt","a")#Opens the text files
def main():
name=input("Please enter your name:")#asks the user for their name and then stores it in the variable name
if name==(""):#checks if the name entered is blank
print ("please enter a valid name")#prints an error mesage if the user did not enter their name
main()#branches back to the main fuction (the beggining of the program), so the user will be asked to enter their name again
class_name(name)#branches to the class name function where the rest of the program will run
def class_name(yourName):
try:#This function will try to run the following but will ignore any errors
class_no=int(input("Please enter your class - 1,2 or 3:"))#Asks the user for an input
if class_no not in range(1, 3):
print("Please enter the correct class - either 1,2 or 3!")
class_name(yourName)
except:
print("Please enter the correct class - either 1,2 or 3!")#asks the user to enter the right class
class_name(yourName)#Branches back to the class choice
score=0#sets the score to zero
#add in class no. checking
for count in range (1,11):#Starts the loop
numbers=[random.randint (1,11),
random.randint (1,11)]#generates the random numbers for the program
operator=random.choice(["x","-","+"])#generates the random operator
if operator=="x":#checks if the generated is an "x"
solution =numbers[0]*numbers[1]#the program works out the answer
question="{0} * {1}=".format(numbers[0], numbers [1])#outputs the question to the user
elif operator=="+":#checks if the generated operator is an "+"
solution=numbers[0]+numbers[1]#the program works out the answer
question="{0} + {1}=".format(numbers[0], numbers [1])#outputs the question to the user
elif operator=="-":
solution=numbers[0]-numbers[1]#the program works out the answer
question="{0} - {1}=".format(numbers[0], numbers [1])#outputs the question to the user
try:
answer = int(input(question))
if answer == solution:#checks if the users answer equals the correct answer
score += 1 #if the answer is correct the program adds one to the score
print("Correct! Your score is, {0}".format(score))#the program outputs correct to the user and then outputs the users score
else:
print("Your answer is not correct")# fail safe - if try / else statment fails program will display error message
except:
print("Your answer is not correct")#if anything else is inputted output the following
if score >=5:
print("Congratulations {0} you have finished your ten questions your total score is {1} which is over half.".format(yourName,score))#when the user has finished there ten quetions the program outputs their final score
else:
print("Better luck next time {0}, your score is {1} which is lower than half".format(yourName,score))
name_score.append(yourName)
name_score.append(score)
if class_no ==1:
myclass1.write("{0}\n".format(name_score))
if class_no ==2:
myclass2.write("{0}\n".format(name_score))
if class_no ==3:
myclass3.write("{0}\n".format(name_score))
myclass1.close()
myclass2.close()
myclass3.close()
Your program seems to be working just fine now.
I've re-factored your code to follow the PEP8 guidelines, you should really try to make it more clear to read.
Removed the try/except blocks, not needed here. Don't use try/except without a exception(ValueError, KeyError...). Also, use with open(...) as ... instead of open/close, it will close the file for you.
# Task 2
import random
def main():
your_name = ""
while your_name == "":
your_name = input("Please enter your name:") # asks the user for their name and then stores it in the variable name
class_no = ""
while class_no not in ["1", "2", "3"]:
class_no = input("Please enter your class - 1, 2 or 3:") # Asks the user for an input
score = 0
for _ in range(10):
number1 = random.randint(1, 11)
number2 = random.randint(1, 11)
operator = random.choice("*-+")
question = ("{0} {1} {2}".format(number1,operator,number2))
solution = eval(question)
answer = input(question+" = ")
if answer == str(solution):
score += 1
print("Correct! Your score is, ", score)
else:
print("Your answer is not correct")
print("Congratulations {0}, you have finished your ten questions!".format(your_name))
if score >= 5:
print("Your total score is {0} which is over half.".format(score))
else:
print("Better luck next time {0}, your score is {1} which is lower than half".format(your_name, score))
with open("class%s.txt" % class_no, "a") as my_class:
my_class.write("{0}\n".format([your_name, score]))
main()