How solve error in this python program? [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
i m a beginner in python and i have lots and lots of questions about it.I tried to create a program and i m not getting the result exactly.Only little calculation is there,rest is printed matter.
it goes like this:
def travelmanagement():
trate=[]
totrate=[]
finrate=[]
frate=[]
print"WELCOME TO..........MESSAGE"
print"ARE YOU A VISITOR OR MEMBER"
ch1=raw_input("Enter your choice")
V="VISITOR"
v="visitor"
if(ch1==V)|(ch1==v):
print"To proceed further,you need to a create account/use guest session"
print"A.Create Account"
print"B.Guest Session"
ch2=raw_input("Enter your choice")
if(ch2=="A")|(ch2=="a"):
Name=raw_input("Enter your name:")
Username=raw_input("ENter your username")
Password=raw_input("ENter your password")
Confirm=raw_input("Confirm your password")
DOB=raw_input("DD: MM: YY: ")
Gender=raw_input("I am....")
Mobile=input("Enter your mobile number")
Location=raw_input("Enter your current location")
print"Prove you are not a robot,Type the text shown below"
print"trufle"
text="trufle"
type=raw_input("Type your text")
if(Password==Confirm)&(type==text):#proceed works only after if is satisfied
def proceed():
print"You have created account"
print"You can now proceed!!"
print"Welcome",Username
print"TMS specializes in touristplaces"
print"P1.DELHI"
print"P2.GOA"
ch3=raw_input("What's your destination?")
pl=['delhi','goa']
t=['t','c','b','p']
gp=[200,400]#general #rate for choosing place
gt=[200,300,400,500]#general rate for choosing transportation
print"""TMS specializez
t.Railways
c.Car
b.Bus
p.Plane"""
ch4=raw_input("ENter your choice")
if(ch4=="t"):#displays timmings of transportation
print"HYPERSONIC HAIRTRIGGER"
print "Timmings:"
print "DELHI"
print ".............."
print "GOA"
print ".............."
print "VELOCIOUS PALACE"
print "Timming"
if(ch4=="c"):
print"CArs available:"
print"BMW"
print"SWIFT"
print"......."
print"........"
if(ch4=="b"):
print"Buses available"
print"................"
print"""delhi
timiings
.........
goa
.................."""
if(ch4=="p"):
print"""Planes available
........just like abv"""
for i in range(0,2,1):
for j in range(0,4,1):
if(pl[i]==ch3)&(t[j]==ch4):
trate=gp[i]*gt[j]
return ch3,ch4
def accomodation():
print"""specialises
1.place 1
a.hotel 1
b.hotel 2
Hotel1:ac/non ac rooms
Ac.for ac...
Noac.for non ac....
b.Hotel2
Ac.ac..
Noac.non ac...
2.place 2
a.Hotel1:ac/non ac rooms
A.for ac...
N.for non ac...
b.Hotel2
A.ac..
N.non ac..."""
genh1=[5000]#general rate for choosing hotel1
genh2=[4000]#general rate for choosing hotel2
ch5=input("Enter ypur choice")
fav=raw_input("ENter hotel choice")
mode=raw_input("Enter ac/no ac")
TAc=[1000]#rate for ac room
Nac=[400]#rate for non ac room
if(ch5==1):
if(fav=="a"):
if(mode=="Ac"):
frate=genh1+TAc
else:
frate=genh1+Nac
elif(fav=="b"):
if(mode=="Ac"):
frate=genh2+TAc
else:
frate=genh2+Nac
elif(ch5==2):
if(fav=="a"):
if(mode=="Ac"):
frate=genh1+TAc
else:
frate=genh1+Nac
if(fav=="b"):
if(mode=="Ac"):
frate=genh2+TAc
else:
frate=genh2+Nac
else:
totrate=totrate+frate+trate
print"Due to prefer a guide??"
print"a guide inperson...rate=1000"
print"maps,3g....rate=2000"
ch6=raw_input("ENter your choice")
if(ch6=="person")|(ch6=="PERSON"):
totrate=totrate+[1000]
elif(ch6=="gadget"|ch6=="GADGET"):
totrate=totrate+[2000]
else:
return totrate
x=proceed()
y=accomodation()
print x
print y
else:
print"invalid"
#if(ch1==b) is present after this.Same lines as above is repeated
travelmanagement()
indentation is proper.The error is"totrate is referenced before assignment"I gave it in all places where global variables are allowed but still it doesnt come.And when i get the result the amount finrate is not getting printed.instead None or 0 comes.please let me know of the mistakes.Is there something i should import??Sorry for the trouble.Its for a class presentation.
Thanks for your effort.

totrate=totrate+frate+trate
you have initialized totrate to be a list. You cannot interact with the list object in this way. I believe you want to be using int types instead of lists. e.g totrate = 1000
Also note, these are not globals but local variables as they are in the scope of the function.

Related

python quiz with subject options [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
print("plese choose a topic of your liking")
History = ('History')
Music = ('Music')
Computer_science = ('Computer science')
print (History, Music, Computer_science)
History = print("when did the Reichstag fires begin?")
one = ("1) 1937")
two = ("2) 1933")
three = ("3) 1935")
print (one, two, three)
guess = int(input())
if guess == 2: #this makes it so any option appart from 2 is outputed as 'wrong'
print ("well done")
else:
print("wrong")
I have created the first part of my python quiz, It took me a while to figure out, I have also created a list that contains 3 different subjects, Do any of you know how to assign a button to each element within my subject list? If this does not make any sense, please let me know (I'm new to this site)
to get this sort of behaviour you can make an input before everything else which determines what subject you choose based on user input. so something REAL simple like:
subject = int(input("Please choose what subject you would like
(number):\n[1]History\n[2]Maths\n[3]Geography\n"))
if subject == 1:
print("You have chosen History")
elif subject == 2:
print("You have chosen Maths")
elif subject == 3:
print("You have chosen Geography")
else:
print("that is not an available option")
This is probably the simplest it can get with menus... If you type 1 and press enter you get history and so on. i dont know how your program works but do what fits in.
There are probably better ways too this is just what I remember doing back in the day. Very simple stuff

How can I return with a local variable in definition in Python? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am trying to create a simple AI program which plays stick game. The problem is that I would like to subtract chosen stick from the total stick number. This simple code shows some error such as nonexisting value. I could not assign returning value for my values. Is there another way to subtracts value with functions?
import random
msg = input('Determine stick numbers:')
print('Stick number is determined as:', msg)
# First player move
def robot(stick):
y = stick % 4
if y==0:
y=randint(1,3)
mov=int(y)
print('machine chose:', mov)
total = stick-mov
return total
def human(stick2):
mov2= int(input('your turn:'))
print('human chose:', mov2)
total = stick2-mov2
return total
players= {
'1': robot,
'2': human
}
number1= input('Determine first player machine(1) or human(2):')
number2= input('Determine second player (1) or (2):')
player1=players[number1]
player2=players[number2]
print(player1, player2)
print('the game begins')
while True:
player1(int(msg))
if msg == 0: break
print('remained sticks:', msg)
player2(int(msg))
print('remained sticks:', msg)
if msg == 0: break
Your players are references functions:
players= {
'1': robot,
'2': human
}
Later you call them player1 and player2:
player1=players[number1]
player2=players[number2]
But when you use these functions you don't do anything with the return value:
player1(int(msg))
...
player2(int(msg))
So those functions return something, but you ignore the value. You need to either print that return value or assign it to a variable so you can do something with the value later.
Since your return values are called total perhaps you want:
total = player1(int(msg))
print('new total:', total)
return does work, of course; it returns a value. However in your code you are not capturing that value and it is immediately thrown away.
It's really not clear what you want, but perhaps you want something like this:
msg = player1(int(msg))

Achievement system in and IDLE python game using pycharm [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am trying to use an achievement system in my game. The game is like cookie clicker except you type and enter the letter "L" over and over and can upgrade the effect done by each type. I am trying to make it so when you get a certain amount of coins, like 1000, it will display that you have achieved the 1000 coins achievement, however it doesn't seem to work. Here is the code:
if coins == 1000:
print("")
print("You have a new achievement!")
print("[✔] - Earn 1,000 points")
print("You have 1/6 coin achievements")
print("")
if coins == 10000:
print("")
print("You have a new achievement!")
print("[✔] - Earn 10,000 points")
print("You have 2/6 coin achievements")
print("")
Your specific problem is that you're using the wrong comparator. If you use ==. you're checking if the value exactly equals. You're interested in when a player "achieves" the value, so switch your comparators out for >=. That way, when a player goes from 980 to 1001 points, 1001 >= 1000 evaluates to True.
Note this will print the text every time you check, even if they've already got the achievement, so perhaps something like the following would be useful:
has_1000_achievement = False
has_10000_achievement = False
if coins >= 1000 and not has_1000_achievement:
has_1000_achievement = True
print("")
...
The solution provided by P i would undoubtedly work, but I believe it's not something you're ready to fluently understand at your current level.
Edit: After the OP added a comment the question got a little more clear to me. Maybe you could try the following (which is of course just an example as the OP did not provide a minimal running peace of code):
# -*- coding: utf-8 -*-
numCoinAchievements = 0
nextCoinLevel = 1000
for coins in range(0, 100000, 33):
if coins >= nextCoinLevel:
numCoinAchievements += 1
if numCoinAchievements == 1:
nextCoinLevel = 10000
elif numCoinAchievements == 2:
nextCoinLevel = 15000
else:
break
print("")
print("You have a new achievement!")
print("[✔] - Earn %d points" % nextCoinLevel)
print("You have %d/6 coin achievements" % numCoinAchievements)
print("")
Of course you have to adept the code to your needs, but it should make the problem clear!

I've created a recipe program for GCSE Computing, but I am missing one step [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
This is my first post here and I am quite unsure on how to implement a vital piece of code in my coursework. I have created a very crude and basic recipe program on Python 3.4. Below is the piece I am missing.
• The program should ask the user to input the number of people.
• The program should output:
• the recipe name
• the new number of people
• the revised quantities with units for this number of people.
I am a complete beginner to programming and our teacher hasn't been very helpful and only explained the basics of file handling which I have attempted to implement into this program.
I will attach the code I have so far, but I would really appreciate some tips or an explanation on how I could implement this into my code and finally finish this task off as it is becoming very irksome.
Thank you!
Code:
I apologise if the code is cluttered or doesn't make sense. I am a complete novice.
#!/usr/bin/env python
import time
def start():
while True:
User_input = input("\nWhat would you like to do? " "\n 1) - Enter N to enter a new recipe. \n 2 - Enter V to view an exisiting recipe, \n 3 - Enter E - to edit a recipe to your liking. \n 4 - Or enter quit to halt the program " "\n ")
if User_input == "N":
print("\nOkay, it looks like you want to create a new recipe. Give me a moment..." "\n")
time.sleep(1.5)
new_recipe()
elif User_input == "V":
print("\nOkay, Let's proceed to let you view an existing recipe stored on the computer")
time.sleep(1.5)
exist_recipe()
elif User_input == "E":
print("\nOkay, it looks like you want to edit a recipe's servings. Let's proceed ")
time.sleep(1.5)
modify_recipe()
elif User_input == "quit":
return
else:
print("\nThat is not a valid command, please try again with the commands allowed ")
def new_recipe():
New_Recipe = input("Please enter the name of the new recipe you wish to add! ")
Recipe_data = open(New_Recipe, 'w')
Ingredients = input("Enter the number of ingredients ")
Servings = input("Enter the servings required for this recipe ")
for n in range (1,int(Ingredients)+1):
Ingredient = input("Enter the name of the ingredient ")
Recipe_data.write("\nIngrendient # " +str(n)+": \n")
print("\n")
Recipe_data.write(Ingredient)
Recipe_data.write("\n")
Quantities = input("Enter the quantity needed for this ingredient ")
print("\n")
Recipe_data.write(Quantities)
Recipe_data.write("\n")
for n in range (1,int(Ingredients)+1):
Steps = input("\nEnter step " + str(n)+ ": ")
print("\n")
Recipe_data.write("\nStep " +str(n) + " is to: \n")
Recipe_data.write("\n")
Recipe_data.write(Steps)
Recipe_data.close()
def exist_recipe():
Choice_Exist= input("\nOkay, it looks like you want to view an existing recipe. Please enter the name of the recipe required. ")
Exist_Recipe = open(Choice_Exist, "r+")
print("\nThis recipe makes " + Choice_Exist)
print(Exist_Recipe.read())
time.sleep(1)
def modify_recipe():
Choice_Exist = input("\nOkaym it looks like you want to modify a recipe. Please enter the name of this recipe ")
Exist_Recipe = open(Choice_Exist, "r+")
time.sleep(2)
ServRequire = int(input("Please enter how many servings you would like "))
start()
EDIT: This is the new code, however I can still not figure out how to allow a user to multiply the original servings by entering how many servings are required, as the default servings are in a text file. Does anyone know how this can be done? I am new to file-handling and have been researching constantly but to no avail.
For the number of people, you can get that from user input similar to how you got any other input in your code, with num_people = input("How many people?").
Something a little more concerning you should look at. Your start() function calls its self. Unless you are using recursion, functions should not call themselves, it will build up on the stack. Use a while loop with something like
while ( 1 ):
userinput = input("what would you like to do?")
if( userinput == "n"):
#new recipe
....
if (user input == "quit"):
sys.exit(1) #this will halt the program
else:
print "not valid input"
You stored the whole data in a text file. This makes storage and retrieval easy, but makes changing values real hard. In these cases, you usually use ... well nevermind: you asked the same question again and got a useful answer.

i am stuck at one of the part T.T can anyone help me out? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I am creating a quiz... and i want to make sure that people can choose how many question they want to answer..
Write a program for an application that let the user host a quiz game. The application will have a collection of questions with short answers. The program should ask the user how many question they want for their game. It will then ask that many questions in random order. When the user types in an answer, it will check the answer against the correct answer and keep track of the number of questions they got right. It will never ask the same question twice. When all the questions have been asked, or the user has quit (by typing "quit" as an answer), the program will print the score and the total number of questions asked
from random import * #random is a library. we need the randint function from it
def Main() :
Questions = [] # list of all the questions
Answers = [] # list of all the answers
setup(Questions, Answers)
while True :
target = int(input("How many questions do you want to answer? more than 1 and less than 11 "))
if target <= len(Questions) :
break
print("Sorry, I only have ", len(Questions), " in my databank")
# alternate version:
# target = int(input("How many questions do you want to answer? "))
# while target > len(Questions) :
# print("Sorry, I only have ", len(Questions), " in my databank")
# target = int(input("How many questions do you want to answer? "))
#
score = 0
numberAsked = 0
while len(Questions) > 0 :
qnNum = randint(0, len(Questions)-1)
correct = askQuestion(Questions[qnNum], Answers[qnNum])
numberAsked = numberAsked + 1
if correct == "quit" :
break
elif correct :
score=score+1
del Questions[qnNum]
del Answers[qnNum]
reportScore(score, numberAsked)
def reportScore(sc, numAsked) :
print("Thanks for trying my quiz, Goodbye", sc, " questions right out of ", numAsked)
#asks the user a question, and returns True or False depending on whether they answered correctly.
# If the user answered with 'q', then it should return "quit"
def askQuestion (question, correctAnswer):
print(question)
answer = input("your answer: ").lower()
if answer == "quit" :
return "quit"
elif answer == correctAnswer.lower() :
print("Well done, you got it right!")
return True
else :
print("You got it wrong this time!. The correct answer is ", correctAnswer)
return False
# Sets up the lists of questions
def setup(Questions, Answers) :
Questions.append("The treaty of Waitangi was signed in 1901")
Answers.append("FALSE")
Questions.append("Aotearoa commonly means Land of the Long White Cloud")
Answers.append("TRUE")
Questions.append("The Treaty of Waitangi was signed at Parliament")
Answers.append("FALSE")
Questions.append("The All Blacks are New Zealands top rugby team")
Answers.append("TRUE")
Questions.append("Queen Victoria was the reigning monarch of England at the time of the Treaty")
Answers.append("TRUE")
Questions.append("Phar Lap was a New Zealand born horse who won the Melbourne Cup")
Answers.append("TRUE")
Questions.append("God Save the King was New Zealand’s national anthem up to and including during WWII")
Answers.append("TRUE")
Questions.append("Denis Glover wrote the poem The Magpies")
Answers.append("TRUE")
Questions.append("Te Rauparaha is credited with intellectual property rights of Kamate!")
Answers.append("FALSE")
Questions.append("Kiri Te Kanawa is a Wellington-born opera singer")
Answers.append("FALSE")
Main()
The main issue is in your while loop - you aren't doing anything with target, which is what is supposed to be governing the number of questions asked. Without going too crazy on suggested modifications, try replacing the code around your while loop with this:
score = 0
numberAsked = 0
while numberAsked < target:
qnNum = randint(0, len(Questions))
correct = askQuestion(Questions[qnNum], Answers[qnNum])
numberAsked = numberAsked + 1
if correct == "quit" :
break
elif correct :
score=score+1
del Questions[qnNum]
del Answers[qnNum]
This will loop while numberAsked is less than target. Your current issue is that your loop is governed by the length of the Questions list, which starts at 10 and decreases by 1 on each iteration. Therefore no matter what your target is, the loop will cycle through all of the questions.

Categories

Resources