Why won't my program work in python? - python-2.7

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!"

Related

Detecting if two variables have the same value

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))

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.

simple notepad data input program needs fixing

Hi I recently had this program running fine but after fiddling round with it now it doesn't work because when i run it in the shell when the program asks "do you want to enter a user" and I type "yes" it doesn't ask for the user to input he/shes name, DOB in form 00/00/0000, run time, postcode. It just prints "do you want to see your records?" If anyone could help quick it would be much appreciated p.s im really new so I dont 100% understand some things at the moment.
def openfile1(name,dob,time,postcode):
file=open('runnerdata.txt', 'a')
file.write(name+":")
file.write(dob+":")
file.write(time+":")
file.write(postcode+ ":\n")
file.close()
while True:
enter=input("Do you want to enter a user? ")
if enter=="no":
file=open('runnerdata.txt', 'r')
list=(file.readlines())
enter2=input("Do you want to see your records? ")
if enter2=="no":
break
elif enter2=="yes":
name2=input("Enter name to see your records ")
for line in list:
if line.split(":")[0]==name2:
print(line)
elif enter=="yes":
name=input("Enter name ")
dob=input("Enter your DOB in form 00/00/0000 ")
time=input("Enter your run time ")
postcode=input("Enter your postcode ")
openfile1(name,dob,time,postcode)
def openfile1(name,dob,time,postcode):
file=open('runnerdata.txt', 'a')
file.write(name+":")
file.write(dob+":")
file.write(time+":")
file.write(postcode+ ":\n")
file.close()
while True:
enter=input("Do you want to enter a user? ")
if enter=="no":
file=open('runnerdata.txt', 'r')
list=(file.readlines())
enter2=input("Do you want to see your records? ")
if enter2=="no":
break
elif enter2=="yes":
name2=input("Enter name to see your records ")
for line in list:
if line.split(":")[0]==name2:
print(line)
elif enter=="yes":
name=input("Enter name ")
dob=input("Enter your DOB in form 00/00/0000 ")
time=input("Enter your run time ")
postcode=input("Enter your postcode ")
openfile1(name,dob,time,postcode)
Try this

How would you create a option to retry in Python?

I'm a little confused on how to allow the user to retry entering something in Python. I created an example code bellow. I want it so if the user types a invalid answer other than 1 or 2 it allows them to try again.
import sys
def start():
print "Hello whats your name?"
username = raw_input("> ")
print "Okay, welcome to the game %s" % username
print "Do you want to hear the background of the game?"
print "1. Yes"
print "2. No"
background = raw_input("> ")
if background == "1":
print "Background goes here."
elif background == "2":
print "Background skipped"
start()
How would I incorporate a try again option into this example? Thanks!
Use a while loop:
def start():
print "Hello whats your name?"
username = raw_input("> ")
print "Okay, welcome to the game %s" % username
print "Do you want to hear the background of the game?"
print "1. Yes"
print "2. No"
while True: # Repeat the following block of code infinitely
background = raw_input("> ")
if background == "1":
print "Background goes here."
break # Break out of loop if we get valid input
elif background == "2":
print "Background skipped"
break # Break out of loop if we get valid input
else:
print "Invalid input. Please enter either '1' or '2'" # From here, program jumps back to the beginning of the loop
start()

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.