Detecting if two variables have the same value - if-statement

I am new to coding, so I've been creating simple programs. I'm currently trying to make a guess the number program. I'm currently having issues trying to make the program tell you whether you won or lost by detecting whether the number entered by the user is equal to the number that was generated. This is my code, and I am currently getting a syntax error on line 10, which I don't understand. Please help me!
import time
from time import sleep
import random
var1 = "Hello"
print(var1)
time.sleep(1)
print("I'm going to pick a number now!")
time.sleep(2)
value = (random.randint(1, 9)
print("Okay, now it's your turn!")
usernumber = input("""Pick a number, 1-9:
""")
time.sleep(1)
var2 = "I picked..."
print(var2)
time.sleep(1)
print(value)
if var3 == usernumber
print("You win!")
if var3 != usernumber
print("You lose. :(")

value = (random.randint(1, 9)
Note the missing parenthesis.
It should be
value = (random.randint(1, 9))

Related

name 'Start()' not defined

I have two files in a game I am currently making (not finished). They are the same directory. When I run either of the two files, the terminal in macos Serria is giving me this error (and yes, I did research, to no avail). BTW, thank you, StackOverFlow, for answering (and downvoting when needed) questions. It truly helped me.:
File "story.py", line 3, in <module>
from engine import *
File "SurvivalAdventureGame/Resources/engine.py", line 2, in <module>
from story import *
File "SurvivalAdventureGame/Resources/story.py", line 5, in <module>
class Start(Scene):
NameError: name 'Scene' is not defined
Here is story.py:
from sys import exit
from random import randint
from engine import *
class Start(Scene):
print """
You are flying to Brussels from Seattle. You *are* glad you received the bonus from work, you think to yourself.
\nUnfortunally, you were only able to put 100$ towards the vacation due to your bastard landlord.
\nYou muttered to yourself, "If this plane got League Pass, though. Warriors-Raptors would be lit."
\nYep, your 14-year old son says as he reads The New Jim Crow. Your 9-year old son is playing Minecraft.
\nThen the speakers boomed, as the crew said, "Hi. My name is Messlia and our pilot is temporarily incapacitated."
\nA strange mixture of curses, crying, yells of terror, and silence filled the cabin.
\n"We will land shortly on a grass clearing near trees."
\nMore panic.
\nYou cried as You told your panicking sons (and secretly myself) to do
"""
print "1. Bring only a blanket, some food and water, some clothing, and every medication needed."
print "2. Bring nothing"
print "3. Bring everything you possibly can."
action = raw_input("> ")
if action == "1":
print "You survived, crawling out the door with a painful leg injury."
print "\n Your older son, a safety-first guy, escaped without ANY injury AT ALL. Your other son, however, has a gaping hole in his wrists."
print "\n He sheds tears, clearly in pain, as you ponder your options."
print "1. Splash with water and cover it with a blanket"
print "2. Cover it with a towel."
print "3. Splash it with water only."
next = raw_input("> ")
if next == "1":
print "Your now have about 50 mL of water left. However, he has calmed down."
Day1()
elif next == "2":
print "You now have to tend to the boy at all times. However, at least he will not get sick, right?"
Day1()
elif next == "3":
print "You now only have 50 mL of water left. At least he calmed down a bit!"
Day1()
else:
Stupid()
elif actions =="2":
print "You survive with no injuries, however, you have nothing and your youngest son just suffered a major wrist injury."
Day1()
elif next == "3":
print "You, your sons, and 12 people die because of you delaying everyone else."
Death()
else:
Stupid()
class Death(Scene):
print "Either you, one or both of your sons or others died. You suck."
class Stupid(Scene):
print "ERROR: OVERWHELMING STUPIDITY."
print "You should enter the numbers without the period, without the words"
Here is engine.py:
from sys import exit
from story import *
class Scene(object):
def __init__(self):
start()
def start(self):
print "DOESNOTEXIST!"
exit(1)
class Engine(object):
def __init__(self, scene_map):
self.scene_map = scene_map
def play(self):
current_scene = self.scene_map.opening_scene()
while True:
print "\n--------"
next_scene_name = current_scene.start()
current_scene = self.scene_map.next_scene(next_scene_name)
class Map(object):
# Won't work now, Gotta finish writing the story!
scenes = {
"Start": Start(),
"Day1": Day1(),
"Day2": Day2(),
"Day3": Day3(),
"Day4": Day4(),
"Day5": Day5(),
"Day6": Day6(),
"Day7": Day7(),
"Day8": Day8(),
"Death": Death(),
"Stupid": Stupid(),
}
def __init__(self, start_scene):
self.start_scene = start_scene()
def next_scene(self, scene_name):
return Map.scenes.get(scene_name)
def opening_scene(self):
return self.next_scene(self.start_scene)
class play(object, Map):
def __init__(self, map):
the_map = Map('Start')
the_map = Engine(the_map)
a_game.play()
Looks like you have a circular dependency: in story you import * (everything) from engine and vice versa. This is not supported in Python.

Python input/strings

(Python 2.7.10) So i am a beginner in python, just started learning about a week ago. I need some help with writing the code commented on lines 3 and 5.If the user enters a word instead of a numerical value then I need the program to tell them error and to restart. I commented the program to make it easier to understand. The program works just fine otherwise. Thank you.
## Ask user for age
age = input("Please enter your age.(numerical value)")
## If input is not a numerical value then tell the user "Error. Enter a numerical value"
## Restart program to let the user try again.
## If age is less than 18 then tell them they are too young
if age < 18:
print (" Access denied. Sorry, you are not old enough.")
## If the user is 18 then grant them access
elif age == 18:
print ("Acess granted. You are just old enough to use this program!")
## If user is any age above 18 then grant them access
else:
print ("Access granted.")
his is a way to make sure you get something that can be interpreted as integer from the user:
while True:
try:
# in python 3:
# age = int(input('Please enter your age.(numerical value)'))
# in python 2.7
age = int(raw_input('Please enter your age.(numerical value)'))
break
except ValueError:
print('that was not an integer; try again...')
the idea is to try to cast the string entered by the user to an integer and ask again as long as that fails. if it checks out, break from the (infinite) loop.
Change your age input part to this:
#keep asking for age until you get a numerical value
while True:
try:
age=int(raw_input("Please enter your age.(numerical value)"))
break
except ValueError:
print "Error. Enter a numerical value"

Why won't my program work in python?

Hi I am 11 yrs old and I am teaching myself how to code. I set myself a task to make a times table quiz that asks 10 questions and inputs random numbers. However, my code is not working and I do not know why. I am using python 2.7.5. This is my code:
print("Here is a quiz to test your knowledge")
print("")
print("Question 1")
import random
print random.randint(1,10)
print ("times")
import random
print random.randint(1,10)
answer = raw_input ("Make your choice: ")
if answer == ran1*ran2:
print "That is correct"
correct=correct +1
else:
print "That is incorrect!"
I can not spot why it is not working but I have not put a for loop in yet so it only asks 1 question. When I run it else is highlighted in red but I do not know why.
Python works without brackets. It is replaced by "spaces or tabs". And we import ONCE, the beginning.
This should work
import random
print("Here is a quiz to test your knowledge")
print("")
print("Question 1")
print random.randint(1,10)
print ("times")
print random.randint(1,10)
answer = raw_input ("Make your choice: ")
if answer == ran1*ran2:
print "That is correct"
correct=correct +1
else:
print "That is incorrect!"

TypeError: expected a character buffer object (trying to write to a text file)

I am trying to code a simple program that writes the output of a function to a text file, and I had it working, but today I tried to run it and it gives me this error at line 54: TypeError: expected a character buffer object.
Here is that line:
f.write(spotify.getCurrentTrack())
Also, here is the rest of the code:
from pytify import Spotify
spotify = Spotify()
import time
var2exit = 1
print "This program was created by Drew Halverson. Do not claim as your own work."
time.sleep(2)
print "This program could not have been created without the help of pytify."
time.sleep(2)
print "Also, this program is not affiliated with Spotify at all and is not an official app."
time.sleep(2)
print "For information on how to use this program and what its use is, check readme.txt"
yes = set(["yes", "y", "YES"])
no = set(["no", "n", "NO"])
r = open("readme.txt", "r")
print "Would you like to read the readme now (type yes or no)?"
choice = raw_input()
if choice in yes: print r.read()
print " "
time.sleep(2)
if choice in no: print "Hi! I will now be checking what song is playing on spotify."
time.sleep(2)
print "Make sure spotify is playing (Only the downloaded application will work. The program is not compatible with the web player version of Spotify."
time.sleep(2)
print " "
time.sleep(1)
print "Have you downloaded Spotify on this computer already? Type yes or no..."
choice2 = raw_input()
if choice2 in yes: print "Alright! Let's go!"
if choice2 in no: var2exit = 2
if var2exit == 2:
print "Go install Spotify first, then try again."
time.sleep(5)
print "Goodbye!"
time.sleep(2)
sys.exit()
var = 1
while var == 1 :
spotify.getCurrentTrack()
spotify.getCurrentArtist()
f = open("current_track.txt", "w")
g = open("current_artist.txt", "w")
f.write(spotify.getCurrentTrack())
g.write(spotify.getCurrentArtist())
print "The current Track is:"
print spotify.getCurrentTrack()
print "The current Artist is:"
print spotify.getCurrentArtist()
time.sleep(10)
print" "
print "Checking again..."
I know there are similar questions to this but none that I found exactly answered my problem. Thanks.

How can i make it so the program progresses while a 'while loop' is running a timer (python)

I need to know how i can enter user input while this while loop counting time is running. I know my program is not efficient nor organized as I am new to python. A simple but longer fix is better than a short fix that I would not understand.
import time
print 'Welcome To the Speedy Type Game!'
time.sleep(1)
print "You're objective is to win the game by typing the specific word before the time runs out"
print "Don't forget to press 'enter' after typing the word!!!!"
print "For round 1 you will have 5 seconds"
null = raw_input('Press enter when you are ready to start')
print '3'
time.sleep(1)
print '2'
time.sleep(1)
print '1'
time.sleep(1)
print 'GO'
C = 'poop'
x = 5
while C in ['poop']:
x = x - 1
time.sleep(1) #This is where my program comes to a halt.
C = raw_input("Print the word 'Calfornia': ") #I dont know how to make the program progress to here without stopping the timer above.
if x < 0:
print 'You have failed, game over!'
else:
print 'Good Job! let us move to the next round!'
There is no easy way to do this in Python - a single process is running at a time, so without e.g. threading (see https://stackoverflow.com/a/2933423/3001761) you can't overlap user input with counting. An easier approach might be:
def test(word, limit=5):
started = time.time()
while True:
result = raw_input("Type {0!r}: ".format(word))
finished = time.time()
if result == word and finished <= started + limit:
print 'Good Job! let us move to the next round!'
return True
elif finished > started + limit:
break
print 'Wrong, try again.'
print 'You have failed, game over!'
return False
Then call e.g.:
>>> test("California")
Type 'California': California # typed quickly
Good Job! let us move to the next round!
True
>>> test("California")
Type 'California': foo # typed wrongly but quickly
Wrong, try again.
Type 'California': California # typed quickly
Good Job! let us move to the next round!
True
>>> test("California")
Type 'California': foo # typed wrongly and slowly
You have failed, game over!
False
>>> test("California")
Type 'California': California # typed slowly
You have failed, game over!
False