Multiple raw_inputs - python

#Print out the menu
print """
###############################################
# 1 - Introduction. #
# 2 - Base. #
# 3 - Contact. #
###############################################"""
#Get the user's choice
choice = raw_input("")
#Work with choice
print choice
if choice == 1:
print "# Welcome to xbrEra's first application! #"
elif choice == 2:
print "# This application was built in Python 7.2.1. #"
elif choice == 3:
print "# Contact me at Blackriver.era#hotmail.com #"
else:
print "# Invalid choice! #"
That is my code. My problem is that after the first input has been completed, they next inputs will have ">>> " as a prefix. How do I change this, and also I keep getting "Invalid choice!" in the current code. Please help, thank you!

I keep getting "Invalid choice!" in the current code
raw_input() returns string in python 2.7, so you need to compare as
choice == "1"
or you may try with input() instead of raw_input(), which evaluate input as numbers.
or you could parse to integer with int(raw_input()) as J.F. Sebastian pointed out. non-integer input could cause errors, so wrap it with try: except: block like
try:
choice = int(raw_input(), 10)
except ValueError:
choice = None
ps: ", 10" is for base 10, input could be zero padded like 010, which could take input as octal numbers

#Print out the menu
ch = """###############################################
# 1 - Introduction. #
# 2 - Base. #
# 3 - Contact. #
###############################################
Enter your choice : """
choice = raw_input(ch)
warn = "\n You must enter 1 or 2 or 3.\n"+\
" Enter your choice : "
while choice not in ('1','2','3'):
choice = raw_input(warn)
print ("# Welcome to xbrEra's first application! #",
"# This application was built in Python 7.2.1. #",
"# Contact me at Blackriver.era#hotmail.com #")[int(choice)-1]

I think you need to code your new lines like this '\n''You must enter 1, 2, or 3.''\n'

Related

invalid literal for int with base 10 - when user dont choose any option

I have this code below and it is working correctly when I choose the option 1, when I choose the option 2 and when I choose other option.
But if user dont choose any option and press enter, I want to show a message "empty" and ask again user to choose an option.
But in this case, when the field is empty I get this error:
invalid literal for int with base 10
Code:
def nav(number):
while True:
option = int(raw_input(number))
if filename == 1:
createjob()
elif option == "2":
print filename
elif option == "":
print "empty"
else:
print "Option not available"
def main():
print " 1 - option 1"
print " 2 - option 2"
nav("Choose an option:")
main()
I'm not sure why you have so many while loops...
Anyway the reason that you are having this issue is because when the user just presses enter "" is trying to be converted to an int. Perhaps you should use strings instead. Ie:
def nav(option_number):
option = raw_input(option_number)
if option == "1":
test()
elif option == "2":
print option
elif option == "":
print "empty"
else:
print "option unavailable"
print " 1 - Option 1"
print " 2 - Option 2"
nav("Select option:")
raw_input gets data as a string. If you are sure you are always going to get integers. Then typecast. Else check the type using the type(data_var) to be sure

How to save the users name and last 3 scores to a text file?

I need to write the last three scores of students and their names into a text file for the teacher's program to read and sort later.
I still don't know how to save the last 3 scores
I have tried this so far:
#Task 2
import random
name_score = []
myclass1= open("class1.txt","a")#Opens the text files
myclass2= open("class2.txt","a")#Opens the text files
myclass3= open ("class3.txt","a")#Opens the text files
def main():
name=input("Please enter your name:")#asks the user for their name and then stores it in the variable name
if name==(""):#checks if the name entered is blank
print ("please enter a valid name")#prints an error mesage if the user did not enter their name
main()#branches back to the main fuction (the beggining of the program), so the user will be asked to enter their name again
class_name(name)#branches to the class name function where the rest of the program will run
def class_name(yourName):
try:#This function will try to run the following but will ignore any errors
class_no=int(input("Please enter your class - 1,2 or 3:"))#Asks the user for an input
if class_no not in range(1, 3):
print("Please enter the correct class - either 1,2 or 3!")
class_name(yourName)
except:
print("Please enter the correct class - either 1,2 or 3!")#asks the user to enter the right class
class_name(yourName)#Branches back to the class choice
score=0#sets the score to zero
#add in class no. checking
for count in range (1,11):#Starts the loop
numbers=[random.randint (1,11),
random.randint (1,11)]#generates the random numbers for the program
operator=random.choice(["x","-","+"])#generates the random operator
if operator=="x":#checks if the generated is an "x"
solution =numbers[0]*numbers[1]#the program works out the answer
question="{0} * {1}=".format(numbers[0], numbers [1])#outputs the question to the user
elif operator=="+":#checks if the generated operator is an "+"
solution=numbers[0]+numbers[1]#the program works out the answer
question="{0} + {1}=".format(numbers[0], numbers [1])#outputs the question to the user
elif operator=="-":
solution=numbers[0]-numbers[1]#the program works out the answer
question="{0} - {1}=".format(numbers[0], numbers [1])#outputs the question to the user
try:
answer = int(input(question))
if answer == solution:#checks if the users answer equals the correct answer
score += 1 #if the answer is correct the program adds one to the score
print("Correct! Your score is, {0}".format(score))#the program outputs correct to the user and then outputs the users score
else:
print("Your answer is not correct")# fail safe - if try / else statment fails program will display error message
except:
print("Your answer is not correct")#if anything else is inputted output the following
if score >=5:
print("Congratulations {0} you have finished your ten questions your total score is {1} which is over half.".format(yourName,score))#when the user has finished there ten quetions the program outputs their final score
else:
print("Better luck next time {0}, your score is {1} which is lower than half".format(yourName,score))
name_score.append(yourName)
name_score.append(score)
if class_no ==1:
myclass1.write("{0}\n".format(name_score))
if class_no ==2:
myclass2.write("{0}\n".format(name_score))
if class_no ==3:
myclass3.write("{0}\n".format(name_score))
myclass1.close()
myclass2.close()
myclass3.close()
Your program seems to be working just fine now.
I've re-factored your code to follow the PEP8 guidelines, you should really try to make it more clear to read.
Removed the try/except blocks, not needed here. Don't use try/except without a exception(ValueError, KeyError...). Also, use with open(...) as ... instead of open/close, it will close the file for you.
# Task 2
import random
def main():
your_name = ""
while your_name == "":
your_name = input("Please enter your name:") # asks the user for their name and then stores it in the variable name
class_no = ""
while class_no not in ["1", "2", "3"]:
class_no = input("Please enter your class - 1, 2 or 3:") # Asks the user for an input
score = 0
for _ in range(10):
number1 = random.randint(1, 11)
number2 = random.randint(1, 11)
operator = random.choice("*-+")
question = ("{0} {1} {2}".format(number1,operator,number2))
solution = eval(question)
answer = input(question+" = ")
if answer == str(solution):
score += 1
print("Correct! Your score is, ", score)
else:
print("Your answer is not correct")
print("Congratulations {0}, you have finished your ten questions!".format(your_name))
if score >= 5:
print("Your total score is {0} which is over half.".format(score))
else:
print("Better luck next time {0}, your score is {1} which is lower than half".format(your_name, score))
with open("class%s.txt" % class_no, "a") as my_class:
my_class.write("{0}\n".format([your_name, score]))
main()

While/if loop giving me trouble (beginner)

I have been trying to make my first "solo" python program, its a calculator where you pick what kind of formula you want it to calculate and then input the variables needed. I got issues with my while/for loop, when i run the program i get the correct menu: menu(), and then when I choose my next menu by inputting 1 i correctly get the "v_menu" however if I input 2, which should get me the "m_menu", I instead just get the v_menu like I would if I typed in a 1.
I hope my explanation made sense, im still very new to all of this. Appreciate any help I can get, been breaking my head over this for atleast one hour or so..
Cheers, and heres my code:
# coding=utf-8
#Menues
def menu():
print "Choose which topic you want in the list below by typing the corresponding number\n"
print "\t1) virksomhedsøkonomi\n \t2) matematik\n"
return raw_input("type the topic you want to pick\n >>")
def v_menu():
print "Choose which topic you want in the list below by typing the corresponding number"
print "\t1) afkastningsgrad\n \t2) overskudsgrad\n \t3) aktivernes omsætningshastighed\n \t4) Egenkapitalens forrentning\n \t5) return to main menu\n"
return raw_input("Type the topic you want to pick\n >>")
def m_menu():
print "Choose which topic you want in the list below by typing the corresponding number"
print "\t1) omregn Celsius til Fahrenheit\n \t2) omregn Fahrenheit til Celsius\n"
return raw_input("Type the topic you want to pick\n >>")
# - Mat -
#Celsius to Fahrenheit
def c_to_f():
c_temp = float(raw_input("Enter a temperatur in Celsius"))
#Calculates what the temperatur is in Fahrenheit
f_temp = c_temp * 9 / 5 + 32
#Prints the temperatur in Fahrenheit
print (str(c_temp) + " Celsius is equal to " + str(f_temp) + " Fahrenheit")
#Fahrenheit to Celsius
def f_to_c():
f_temp = float(raw_input("Enter a temperatur in Fahrenheit"))
#Calculates what the temperatur is in celsius
c_temp = (f_temp - 32) * (float(100) / 180)
#Prints the temperatur in celsius
print (str(f_temp) + " Fahrenheit is equal to " + str(c_temp) + " Celsius")
#Program
loop = 1
choice = 0
while loop == 1:
choice = menu()
if choice == "1" or "1)":
v_menu()
elif choice == "2" or "2)":
m_menu()
if choice == "1":
c_to_f()
elif choice == "2":
f_to_c()
loop = 0
Your problem is in your if statements: if choice == "1" or "1)":
What you really need is: if choice == "1" or choice == "1)":
Everything after the or gets evaluated as another expression. You're saying "if choice is equal to one or if one exists."
"1)" evaluates to "true" in this instance, so you'll always hit that branch.
The problem is here;
if choice == "1" or "1)":
v_menu()
elif choice == "2" or "2)":
You have to write them like;
if choice == "1" or choice == "1)":
v_menu()
elif choice == "2" or choice == "2)":
Otherwise, all the time your if statement is True. And if first if statement is True, then your elif statement is not going to work. That's why you can't call v_menu()

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.

Integer and string conflicts

Currently I'm working on an assignment that requires that I create a program in which the user enters a number between 0-4. The program then checks which number the user inputs and outputs a specific string. For example if the user enters 4, the program will output "80 or above: Level 4"
The problem is that the user should also be able to quit the program. I decided to create the program so if the user inputs something that is not blank (while input != "":) the program will run, but if they decide to hit enter the program will end.
This is the code I've come up with so far:
def get_level():
level = raw_input("Enter a number from 0-4 (Press <Enter> to quit): ")
return level
def check_mark(level):
if int(level) == 4:
print "80 or above: Level 4"
elif int(level) == 3:
print "70 - 79: Level 3"
elif int(level) == 2:
print "60 - 69: Level 2"
elif int(level) == 1:
print "50 - 59: Level 1"
elif int(level) == 0:
print "Below 50: Level 0"
else:
print "ERROR: out of range"
def output(level):
while level != "":
level = raw_input("Enter a number from 0-4 (Press <Enter> to quit): ")
check_mark(level)
print
def main():
user_level = get_level()
user_mark = check_mark(user_level)
print
program_output = output(user_level)
main()
I'm pretty aware that the problem has to do with the fact that raw_input only accepts strings which is what activates the "while level != "":" statement. I tried working around this by placing int() operators before each level. The problem is that it conflicts with the input if the user enters blank since it checks whether the input is an integer. Something like that anyways.
So I was hoping someone could guide me to finding a way around this. It would be much appreciated!
You probably want the next looping code:
def output(level):
level = raw_input("Enter a number from 0-4 (Press <Enter> to quit): ")
while level != "":
check_mark(level)
level = raw_input("\nEnter a number from 0-4 (Press <Enter> to quit): ")
I don't htink there is any shortcut around validating input. So the user can either type "" or an integer. What happens if the user types in letters?
I would verify all input to handle accordingly so the program doesn't break
# check for blank
if level == '':
# exit for user
# validate input if not exit
try:
level_int = int(level)
except ValueErrror:
# integer not inputed
if not (0 <= level_int <= 4):
# check that input is between 0 4
# out of range
or you could just check for expection in check_mark when you call it in main

Categories