Passing a value to end message of game - python

I have this hang man code but i want to add parameter passing to it
import time
import random
#Procedure
def Username():
name = raw_input("What is your name?")
print "Hello, "+ name, "Time to play hangman!"
print "\n"
def loading():
#Makes the user wait for 1 second
time.sleep(1)
print "Start guessing..."
time.sleep(0.5)
return
def randwords():
global words
words = ["keyboard", "motherboard", "python", "powersupply"]
words = random.choice(words)
#Main Program
Username()
loading()
randwords()
guesses =""
turns = 12
#while loop
while turns > 0:
failed = 0
for char in words:
if char in guesses:
print char,
else:
print"_",
failed += 1
if failed == 0:
print "\nyou won Well Done"
break
print
guess = raw_input("guess a character:")
guesses += guess
if guess not in words:
turns -= 1
print "wrong\n"
print "you have", + turns, "more guesses"
if turns == 0:
print "you lose GAME OVER\n"
input()
Username()
waiting()
Random
I want it to take the name value, user types in at the start and then pass that value into the end messages.
Example
print "you have won (NAME) Well Done"
or
print "you lose (NAME) GAME OVER"
Please help me somebody because I can solve the problem every time I try I get a error message.

You should declare 'name' as global variable.
name = '' # before def Username
And before you assign a value to this variable, do following:
global name
name = raw_input("What is your name?")
You may then use this variable anywhere in the script to print its value.
print name, "you lose GAME OVER\n"
P.S : To write to a gllobal variable, you must precede with:
global <variable-name>
whereas, you may read its value in normal way

You can simply return the name from the function 'Username()'.
def Username():
...
return name
def main():
...
name = Username()
...

Related

How do I use in input from one function in another?

So I'm writing a higher or lower game and I am experimenting with functions. I have a couple functions in my code but I need 2 in particular to kind of work with each other in order for my code to run properly (my code isn't finished yet so there are still a lot of mechanics I need to add).
def winner(opponent1, opponent2):
opponent1_flwrs = opponent1['follower_count']
opponent2_flwrs = opponent2['follower_count']
score = 0
if opponent1_flwrs > opponent2_flwrs:
if higher_or_lower == "A" or higher_or_lower == "a":
score += 1
return "You're right! Current score: " + score
else:
clear()
print(art.logo)
return "Sorry, that's wrong. Final score: " + score
elif opponent2_flwrs > opponent1_flwrs:
if higher_or_lower == "B" or higher_or_lower == "b":
score += 1
return "You're right! Current score: " + score
else:
clear()
print(art.logo)
return "Sorry, that's wrong. Final score: " + score
def game(opponent1, opponent2:
"""
Contains the code necessary for the game to begin and will continue to execute
as long as the user is the winner
"""
print(art.logo)
print(f"Compare A: {opponent1['name']}, a {opponent1['description']}, "
f"from {opponent1['country']}")
print(art.vs)
print(f"Against B: {opponent2['name']}, a {opponent2['description']}, "
f"from {opponent2['country']}")
higher_or_lower = input("Who has more followers A or B? ")
I have a file that contains the data so the values for opponent1, opponent2, and opponent1_flwrs, opponent2_flwrs are taken from that data.
I want the higher_or_lower input from the game function to be able to do the same thing in the winner function and have the same value if that makes sense. Also later on I'm going to add a while loop that's going to call on these functions continuously until the user has lost.
firstable, sorry for the bad English, but I think that you can just pass the higher_or_lower variable to the winner function like this:
def winner(opponent1, opponent2, chosen_option, current_score):
chosen_option= chosen_option== 'a'
correct_option= opponent1['follower_count']> opponent2['follower_count']
if chosen_option== correct_option:
score += 1
return "You're right! Current score: " + score
else:
clear()
print(art.logo)
return "Sorry, that's wrong. Final score: " + score
def game(opponent1, opponent2, score):
"""
Contains the code necessary for the game to begin and will continue to execute as long as the user is the winner
"""
print(art.logo)
print(f"Compare A: {opponent1['name']}, a {opponent1['description']}, from {opponent1['country']}")
print(art.vs)
print(f"Against B: {opponent2['name']}, a {opponent2['description']}, from {opponent2['country']}")
higher_or_lower = input("Who has more followers, A or B? ").lower()
winner(opponent1, opponent2, higher_or_lower)
in the main loop you have to declare the score variable so you don't reset it every time you call the function

How do I fix a Stubborn syntax error in my python project?

I'm working on a school project and I've almost got it done. Doing a hangman game. for the "else:" command below print (char) on line 32 I keep getting a syntax error and nothing I've tried so far fixes it and the compiler wont tell me what the problem is besides it being a syntax error
import time
Name =input("What is your name?")
print ("Hello,"+Name,"Time to play hangman")
print( "")
#wait for 1 second
time.sleep(1)
print("Start guessing...")
time.sleep(0.5)
#here we set the secret
word = "ball"
#creates an variable with an empty value
guesses = ""
#determine the number of turns
turns =10
#create a while loop
#check if the turns are more than zero
while turns > 0:
#make a counter that starts with zero
Failed =0
#for every character in secret_word
for char in word:
if char in guesses:
print (char,)
else:
print ( "_", )
failed += 1
print ("You won")
break
print()
guess = input ("guess a character:")
guesses +=guess
if guess not in word
turns -=1
print ("Wrong")
print ("You have", turns, "more guesses")
if turns ==0:
print ("You Lose the Word was",word)

Python Hangman game and replacing multiple occurrences of letters

This is my first year programming with Python.
I am trying to create a hangman game.
So my questions: how do I check for
If the person is guessing a letter that has already been guessed and where to include it.
Check they are inputting a valid letter not multiple letters or a number.
What happens if it's a word such as 'Good' and they guess an 'o' at the moment my code breaks if this is the case. Also where on Earth would this be included in the code?
Here is my code
import random
import math
import time
import sys
def hangman():
if guess == 5:
print " ----------|\n /\n|\n|\n|\n|\n|\n|\n______________"
print
print "Strike one, the tigers are getting lonely!"
time.sleep(.5)
print "You have guessed the letters- ", guessedLetters
print " ".join(blanks)
print
elif guess == 4:
print " ----------|\n / O\n|\n|\n|\n|\n|\n|\n______________"
print
print "Strike two, pressure getting to you?"
time.sleep(.5)
print "You have guessed the letters- ", guessedLetters
print " ".join(blanks)
print
elif guess == 3:
print " ----------|\n / O\n| \_|_/ \n|\n|\n|\n|\n|\n______________"
print
print "Strike three, are you even trying?"
time.sleep(.5)
print "You have guessed the letters- ", guessedLetters
print " ".join(blanks)
print
elif guess == 2:
print " ----------|\n / O\n| \_|_/ \n| |\n|\n|\n|\n|\n______________"
print
print "Strike four, might aswell giveup, your already half way to your doom. Oh wait, you can't give up."
time.sleep(.5)
print "You have guessed the letters- ", guessedLetters
print " ".join(blanks)
print
elif guess == 1:
print " ----------|\n / O\n| \_|_/ \n| |\n| / \\ \n|\n|\n|\n______________"
print
print "One more shot and your done for, though I knew this would happen from the start"
time.sleep(.5)
print "You have guessed the letters- ", guessedLetters
print " ".join(blanks)
print
elif guess == 0:
print " ----------|\n / O\n| \_|_/ \n| |\n| / \\ \n| GAME OVER!\n|\n|\n______________"
print "haha, its funny cause you lost."
print "p.s the word was", choice
print
words = ["BAD","RUGBY","JUXTAPOSED","TOUGH","HYDROPNEUMATICS"]
choice = random.choice(words)
lenWord = len(choice)
guess = 6
guessedLetters = []
blanks = []
loading = ".........."
print "Loading",
for char in loading:
time.sleep(.5)
sys.stdout.write(char)
sys.stdout.flush()
time.sleep(.5)
print "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
print "Great I'm glad to see you have finally woken."
time.sleep(1)
raw_input("Did you have a nice journey? ")
time.sleep(2)
print """
Oh wait, I don't care.
I have brought you to this island simply for my amusment. I also get paid to do this.
"""
time.sleep(2)
print"""
Don't worry this isn't all for nothing.
I'm sure the tigers will enjoy your company.
"""
time.sleep(2)
print"""
Hold on, let us make things interesting.
"""
time.sleep(2)
print "I will let you live if you complete an impossible game!"
time.sleep(2)
print "A game know as hangman!"
time.sleep(2)
print "HAHAHAHAHAH, I am so evil, you will never escape!"
time.sleep(2)
print "Enjoy your stay :)"
time.sleep(1)
print
print "Alright lets begin! If you wish to guess the word type an '!' and you will be prompted"
time.sleep(.5)
print
for s in choice:
missing = choice.replace(choice, "_")
blanks.append("_")
print missing,
print
time.sleep(.5)
while guess > 0:
letterGuess = raw_input("Please enter a letter: ")
letterGuess = letterGuess.upper()
if letterGuess == "!":
print "If you guess the FULL word correcly then you win, if incorrect you die. Simple."
fullWordGuess = raw_input("What is the FULL Word? ")
fullWordGuess = fullWordGuess.upper()
if fullWordGuess == choice:
print "You must have hacked this game"
time.sleep(.5)
print "Looks like you beat an impossible game! \nGood Job \nI'll show myself out."
break
else:
print "You lost, I won, you're dead :) Have a nice day!"
print "P.S The word was ", choice
break
else:
print
if letterGuess in choice:
location = choice.find(letterGuess)
blanks.insert(location, letterGuess)
del blanks[location+1]
print " ".join(blanks)
guessedLetters.append(letterGuess)
print
print "You have guessed the letters- ", guessedLetters
if "_" not in blanks:
print "Looks like you beat an impossible game! \nGood Job \nI'll show myself out."
break
else:
continue
else:
guessedLetters.append(letterGuess)
guess -= 1
hangman()
I did not really follow your code since there seems to be something wrong with your indentation, and the many print's confused me a little, but here is how I would suggest soving your Questions:
1.1. Create a list of guessed characters:
guessed_chars = []
if(guess in guessed_chars):
guessed_chars.append(guess)
#do whatever you want to do with the guess.
else:
print("You already guessed that.")
#do what ever you want to do if you already guessed that.
1.2 Lets say the word the player has to ges is word = "snake". To get the indices (since a string is just a list of charcters in python, only that it is immutable) where the guessed letter is in the word you could then use something like:
reveal = "_"*len(word)
temp = ""
for i, j in enumerate(word):
if j == guess:
temp += guess
else:
temp += reveal[i]
reveal = temp
print(reveal)
Maybe not fancy but it should work:
if (guess not in [a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z]):
with my suggestion for 1.2 you would just have to check if(word==reveal): no problem with duplicate charcters.
Since I am just a hobbyist there would probably be a more professional way though.
Next time maybe splitting up your question and first looking them up individually would be better, since I am pretty sure that at least parts of your questions have been asked before.

Appending variable to text file not working in Python

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.

Inputting scoring (python 2.7.5)

I'm having trouble inputting scoring in my python quiz code. Here is the script:
#This is the Test script for )TUKT(, Developed by BOT.
print ""
print "Welcome to the Ultimate Kirby Test."
print ""
begin = (raw_input("Would you like to begin?:"))
if begin == "yes":
print ""
print "Alright then! Let's start, shall we?"
print "Q1. What color is Kirby?"
print "1) Black."
print "2) Blue."
print "3) Pink."
print "4) Technically, his color changes based on the opponent he swallows."
choice = input("Answer=")
if choice ==1:
print "Incorrect."
print ""
elif choice ==2:
print "Incorrect."
print ""
elif choice ==3:
print "Tee hee.... I fooled you!"
print ""
elif choice ==4:
score = score+1
print "Well done! You saw through my trick!"
print ""
elif choice > 3 or choice < 1:
print "That is not a valid answer."
print ""
print "Well done! You have finished my test quiz."
print("Score:")
print ""
#End of Script
The error always says
score = score+1 is not defined.
I did not get anywhere researching.
Thanks! Help is very much appreciated!
You forgot to define a variable called score. You can't reference a value that doesn't exist!
Just declare it at the start:
score = 0
In the line score = score + 1, Python goes: 'so I need to create a variable called score. It contains the value of score, plus 1.' But score doesn't exist yet, so an error is thrown.
The varibale score has never been defined. Insert score = 0 as first line of your scirpt.

Categories