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
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I've been wonder how to clean up code to make my code easier and more readable for others reviewing my code. I'm fairly new to python, so I write everything into functions instead of using classes. Should I use more classes to better understand python more? I know that if the code works then it doesn't matter the way you did it but I just want to learn how to decrease my lines of code.
def paymentData():
calculateTotal = {}
remainingAmount = []
balance = int(raw_input('What is the balance of your bank account? \n'))
amount = int(raw_input('What is the amount you would like to subtract? \n'))
calculateTotal[balance]=amount
total = balance - amount
print('your total is: ' + str(total))
remainingAmount.append(total)
while True:
choice = raw_input('To continue press "Enter" or type "q" to exit (For options type "o"). \n')
if choice == '':
clearScreen()
paymentData()
break
elif choice.lower() == 'q':
clearScreen()
menuBudget()
break
elif choice.lower() == 'o':
return calculateTotal, remainingAmount
clearScreen()
options_menu()
break
else:
print('Invalid value.')
continue
This is a function from one of my programs that is a budget program that takes the value balance that the user puts in and subtracts it from the amount value.
This function calls three different functions, one of them being clearScreen() that clears the terminal:
def clearScreen(numlines=100):
if os.name == "posix":
os.system('clear')
elif os.name in ("nt", "dos", "ce"):
os.system('CLS')
else:
print('\n' * numlines)
The options_menu() function that tells you the results of all the amount you put in (This is not completed nor do I plan to complete this project).
def options_menu():
print('Do you want to see all of you total amounts?\n(Enter 1 for Yes, 2 for no.)')
choice = int(raw_input())
if choice == 1:
time.sleep(3)
elif choice == 2:
menuBudget()
else:
print('Invalid Response.')
and the `menuBudget()` function that is the main menu for this script:
def menuBudget(): # this is a menu for budget fast.
menuRunning = True
while menuRunning:
print("""
1. payment calculator.
2. Comming Soon.
3. Comming Soon.
4. Exit/Quit.
""")
ans = input('Pick on the options above.\n')
if ans == 1:
clearScreen()
paymentData()
break
elif ans == 2:
print('Comming soon!')
continue
elif ans == 3:
print('Comming soon!')
continue
elif ans == 4:
break
else:
print('Unknown Option Seleted!')
continue
The use of classes means the use of OOP (Oriented Object Programmation). Sometimes your code will be very simple and doesn't need the use of classes. This paradigm depends of the type of project you want to build.
If you use imperative programmation, the best practice is to use functions as you're doing. If you want to improve your code, here are some tips :
Use meanful variable names
Use meanful function names
Sort your code into many files, feel free to have as much as you need. Try to call them once more with meanful names.
Simplify your code as much as needed, and use python libraries functions (this comes with experience). For example, use the max() function instead for re-write other functions.
Add comments to your code to make it re-usable even after month
Feel free to update this answer with other good-programmation pattern !
I'm creating a quiz for my GCSE where a person is given the musical and the first letters of the song, they then must guess the entire song. The part I'm having trouble with is that even though I get the question right, it is telling me I am wrong. I'm also using a CSV file to store the questions and answers.
I have tried changing the variable many, many times and I'm really not sure what else to do. Currently the loop is still open, but the code is not finished yet and I cannot move on until I've done this.
while fail!= True:
randomN = random.randint(0, totalQu - 1)
musical = questions[randomN][0]
title = questions[randomN][1]
title_split = title.split()
new = []
for title in title_split:
letter=title[0].upper()
new.append(letter)
ans=" ".join(new)
print(musical+",",ans)
answer = input()
if answer == title:
print("That is CORRECT")
score = score + 3
elif answer != title:
print("That is INCORRECT. Try again")
If the question is "Dear Evan Hansen, F F" then the answer is "For Forever" but if I input this it tells me I am wrong. The variable 'title' is for some reason, only the first word? For example, in this case it would be "Forever".
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Assuming I have a list of options:
options = ["Option 1", "Option 2", "Option 3"]
And I would like the user to choose an option on the command line, e.g. something like this:
Please choose:
1) Option 1
2) Option 2
3) Option 3
Enter number: <user input>
So I am looking for the implementation of the following:
choice = let_user_pick(options) # returns integer
How would one go about this in python?
def let_user_pick(options):
print("Please choose:")
for idx, element in enumerate(options):
print("{}) {}".format(idx+1,element))
i = input("Enter number: ")
try:
if 0 < int(i) <= len(options):
return int(i)
except:
pass
return None
You might want to instead return int(i)-1 in order to use the result as an index of your options list, or return the option directly. It might also be good to instead of returning None loop over the whole thing until the user enters a correct choice.
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 7 years ago.
Improve this question
I'm trying to get my python code so it happens like this
Imports Register.txt [Done]
Now loops it and asks the user which variable it wants to go to
following code is:
print("Registration System")
print("Make sure their is atleast one name in register!")
input("Enter any key to continue ")
with open ("register.txt", "r") as register:
registers = [line.rstrip("\n") for line in register]
for pop in registers:
print(pop)
Thanks!
If I understand you right you can try this:
print("Registration System")
print("Make sure their is atleast one name in register!")
input("Enter any key to continue ")
set1 = set()
set2 = set()
with open("register.txt", "r") as register:
registers = [line.rstrip("\n") for line in register]
for pop in registers:
print(pop)
choice = input(
'Where would you like it to go? (Enter 1 - set1, enter 2 - set2)')
if choice == '1':
set1.add(pop)
elif choice == '2':
set2.add(pop)
print(set1)
print(set2)
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.