How to include 1st, 2nd, 3rd instead of writing it out - python

# extension
modify = input("Would you like to modify your recordings? Yes or No? ")
if modify == ("Yes","yes","Y","y"):
print ("OK")
if modify == ("No","no","n","N"):
print ("You may now exit the program")
print("")
name = input ("Whose score would you like to modify? Type it in with this format - Name, Age Category: ")
if name == ("Jane, Under 11"):
answer = input ("Would you like to add or delete data? ")
if name == ("Grant, Under 11"):
answer = input ("Would you like to add or delete data? ")
if name == ("Lilly, Under 11"):
answer = input ("Would you like to add or delete data? ")
if name == ("Henry, Over 11"):
answer = input ("Would you like to add or delete data? ")
if name == ("Jane, Over 11"):
answer = input ("Would you like to add or delete data? ")
if name == ("Naomi, Over 11"):
answer = input ("Would you like to add or delete data? ")
if answer == ("add" ,"Add"):
pos = input ("Type in the position(s) you would like to add: ")
elif answer == ("delete" ,"Delete", "del", "Del"):
delete = input ("Would you like to delete position or name?")
if delete == ("pos","Pos","Position","position"):
print ("Position deleted. Here is the final outcome: ",name)
elif delete == ("Name", "name"):
print ("Name deleted. There is no data now")
if pos == ('1st', '2nd', '3rd', '4th', '5th', '6th', '7th', '8th', '9th', '10th','11th', '12th', '13th', '14th', '15th', '16th', '17th', '18th', '19th', '20th', '21st', '22nd', '23rd', '24th', '25th', '26th', '27th', '28th', '29th', '30th', '31st'):
print ("Posititon added. Here is their final score: ", name, " ", pos)
Hello. I am new to SO so I'm not sure if this is the correct way to do this however I am trying to answer a question where I am told to use pickle and store data inside a file. I am also told that the code should be able to let the user select a list to delete, be able to change a player position(its about a tennis competition) and be able to store the position of players in their last three tournaments. I need to do it in certain age categories
Everything works well so far however I need to do the positions as 1st 2nd 3rd and so on up to 1000. I have started writing it out(see penultimate line) but it would take extremely long to write it out so does anyone know a way to save time and solve this problem??

This is an odd little program, which will break if you don't enter answers with exactly what you're expected to enter.
I was able to get your error when I typed "No" (accidentally) after the prompt "Whose score would you like to modify?"
Since you haven't instantiated the variable answer before your if statements (as #Enes pointed out) and since none of your if statements are true, I didn't have anything stored in the answer variable, when you called
if answer == ("add" ,"Add"):...
this threw an error.
So if you fix the error that #Schlator mentioned
(Change
if modify == ("Yes","yes","Y","y"):
to
if modify in ("Yes","yes","Y","y"):
everywhere)
and if you instantiate your variable answer as Enes mentioned
(Add
answer = ""
before
name = input ("Whose score would you like to modify? Type it in with this format - Name, Age Category: ")
)
then at least your fragile little program will exit gracefully.

It appears that you are mistaken with the syntax
It shouldn't be
if modify == ("Yes","yes","Y","y"):
rather it should be
if modify in ("Yes","yes","Y","y"):
Similarly for other if conditions that you have used in other parts of the program.

The way you've written your program, you will always drop through to if answer == with answer being undefined. Your input and test sequence:
name = input ("Whose score would you like to modify? Type it in with this format - Name, Age Category: ")
if name == ("Jane, Under 11"):
cannot possibly match the choices you've given, because every input will contain a newline. You need to either include that in your test, or strip it from the input before checking.

Related

How to fix IF/ELSE statments?

I'm trying to create an authorization process and it always says name unauthorized, despite the name not being assigned to the unauthorized variable.
I've tried different organization of the code, ie different order, but the problem hasn't improved.
Tessa=str
un = Tessa
n1=str
n2=str
input(n1("What is the name of player one?"))
if n1 == un:
print("Name unauthorised, try again")
else:
print ("Name authorised")
input(n2("What is the name of player two?"))
if n2 == un:
print("Name unauthorised, try again")
else:
print("Name authorised")
print("Welcome")
I expect any inputted name other than Tessa to result in the phrase "Name authorized" but instead it prints the unauthorized message."
I don't understand the statements n1 = str. Please check my code.
un = 'Tessa'
n1 = input("What is the name of player one?")
if n1 == un:
print("Name unauthorised, try again")
else:
print ("Name authorised")
n2 = input("What is the name of player two?")
if n2 == un:
print("Name unauthorised, try again")
else:
print("Name authorised")
print("Welcome")
and the result will be as below.
What is the name of player one? lam
Name authorised
What is the name of player two? rio
Name authorised
Welcome
you're clearly new to Python, so here are some things that you should fix:
Python doesn't need variables to have certain type. There is no need for what you were intending with n1 = str.
If you want to assign an actual string value, you can do so using quotes: "my string value".
If you want to do repeated checks, do it as part of a loop
If you want to store multiple values, use a list. (like for player names)
If you might have multiple values to check against (you might have multiple unauthorised names), use a list.
In light of these, consider the following code snippet:
unauthorised_names = ["Tessa"]
player_names = []
while len(player_names) < 2:
name = input("Please enter a name for player {}:".format(len(player_names) + 1))
if name in unauthorised_names:
print("Unauthorised name, please try again")
else:
player_names.append(name)
print(player_names)
Here unauthorised_names holds every name that cannot be entered. It can be one, it can be many.
player_names contain the names of the players.
You run it, until you got a sufficient number of valid player names, with the while loop
You take the input, with the number of the player as a parameter
Check it if it's on the list of invalid names, and store it, if it isn't.
Once you have the right number of names, you proceed with your program.
Try it for yourself!
To take an input and keep the value in n1, you need to do this:
n1 = str(input("What is the name of player one?"))
Also, I have no idea where you're going with the n1 = str, etc., so I suggest you scrap it.

Why am I receiving "incorrect" output in this ifelse statement?

I am new to python and trying to learn by doing small projects.
I am trying to write a program that displays the names of the four properties and
asks the user to identify the property that is not a railroad. The user should be informed if the selection is correct or not.
properties = "Reading,","Pennsylvania","B & O","Short Line"
question = str(input("Which is not a railroad?")) **Short Line**
if properties == "Short Line":
print("correct")
else:
print("incorrect")
However, my final output shows as "incorrect", what am i doing wrong?
The four railroad properties
are Reading, Pennsylvania,
B & O, and Short Line.
Which is not a railroad? Short Line
Correct.
Short Line is a bus company.
Couple things I see with this code you have posted.
First, not sure if you actually have **Short Line** in your actual code but if you are trying to comment use # That way it won't be interpreted at run time.
Second as mentioned in other answers you are checking against properties which is pulling in your array. You should be checking against your input which is stored at question.
properties = "Reading,","Pennsylvania","B & O","Short Line"
question = str(input("Which is not a railroad?")) # **Short Line**
if question == "Short Line": # replaced properties with question
print("correct")
else:
print("incorrect")
print(properties)
print(question)
I find that when I am having troubles understanding why something is not working I throw some print statements in to see what the variables are doing.
You may want to catch the user in a loop, otherwise you would have to constantly have to run the code to find the correct answer(unless that is the desired behavior, then you can leave it as you have it). Also, be aware that you may want to uppercase or lowercase because a user may provide the answer as "Short line" (lower case "L"), and the code will return as incorrect. Of course, that depends on what you will accept as an answer.
Sample
print ("Reading,Pennsylvania,B & O, or Short Line. Which is not a railroad?")
user_input = input("Please provide an answer: ")
# != the loop will close once the user inputs short line in any form
# The upper.() will convert a user_input string to all caps
while user_input.upper() != "SHORT LINE":
print ("Incorrect, Please try again.")
user_input = input("Which one is not a railroad? ")
print ("Correct")
Prettied it up for you
print( "Reading, Pennsylvania, B & O, and Short Line. Which is not a railroad?" )
print("Which is not a railroad?")
answer = input()
if answer == "Short Line":
print("correct")
else:
print("incorrect")

Python 3.6.2 loop not working like I wanted it too

I am currently writing a code for my GCSE coursework and I am kind of stuck with my for loop which also contains an if-else statement.
I have done a code similar to this earlier in the program and it works perfectly fine but for some reason this part doesn't and I was wondering if someone could help me.
What I am trying to do is make a quiz type program and the part that I need help with is choosing the subject that the user wants to do.
The user has to type in their preferred subject but if they type the subject in wrong, or type in something invalid, then the program should allow the user to type it in again.
So far, if you type in a subject correctly the first time, the program will proceed to the next stage.
However, if you type it incorrectly the first time, it will ask the user to try again. But if you type it in correctly the second time, it will again ask the user to try again. Instead of having the program make the user type the subject again, even though it should've been valid the when they typed it in correctly, I want the program to proceed to the next stage.
Available subjects:
subjects = []
algebra = ("algebra")
computing = ("computing")
subjects.append(algebra)
subjects.append(computing)
Part that I need help with:
with open("student_file.csv", "a+") as studentfile:
studentfileReader = csv.reader(studentfile, delimiter = ',')
studentfileWriter = csv.writer(studentfile, delimiter = ',')
print("Available subjects:\n-Algebra\n-Computing\n")
ChosenSubject = input("What subject would you like to do? ")
ChosenSubject.lower()
for i in range(2):
if ChosenSubject in subjects:
print("\n")
break
else:
print("\nPlease try again.")
ChosenSubject == input("What subject would you like to do?")
ChosenSubject.lower()
if ChosenSubject in subjects:
print("working")
else:
print("You keep typing in something incorrect.\nPlease restart the program.")
In the else block, perhaps you'd want to replace the '==' with '='.
Also do you want to give the user just two tries or keep asking them until they answer correctly? (The latter is what I inferred from your question, for that I'd recommend using continue)
The for loop just iterates over a collection of objects. Consider a list my_list = ['a', 'b', 'c']. On each iteration over my_list using for loop, it fetches one of the elements in order without repetition. range(2) is equivalent to [0, 1].
Try this:
print("Available subjects:\n-Algebra\n-Computing\n")
for i in range(2):
# `i` is 0 on first iteration and 1 on second. We are not using `i` anywhere since all we want is to loop :)
chosen_subject = input("What subject would you like to do? ")
if chosen_subject.lower() in subjects:
print("\n")
break
if chosen_subject.lower() in subjects:
print("working")
else:
print("You keep typing in something incorrect.\nPlease restart the program.")
This is not an optimal solution, but since your learning I will try to keep it as close as your solution. Your problem is that calling ChosenSubject.lower() does not change the actual value in ChosenSubject.
Here is a working example:
print("Available subjects:\n-Algebra\n-Computing\n")
ChosenSubject = input("What subject would you like to do? ")
subjects = ["algebra", "computing"]
for i in range(2):
if ChosenSubject.lower() in subjects:
print("\n")
break
else:
print("\nPlease try again.")
ChosenSubject = input("What subject would you like to do?") #not '=='
if ChosenSubject.lower() in subjects:
print("working")
else:
print("You keep typing in something incorrect.\nPlease restart the program.")
This from the doc:
This method returns a copy of the string in which all case-based
characters have been lowercased.

Issues with lists? Error checking not working

I am relatively new to python, and I just started learning how to use classes. This is the first program I've made where I've tried to integrate them, but I'm coming up with a small issue I can't seem to fix, and I think it has to do with lists. The code is as follows:
(The topic is getting the user to choose what type of seat to purchase).
class SeatBooking:
def __init__(self, seat):
self.seat = seat
possible_types = []
possible_types.extend(["Low_Economy", "Standard_Economy", "High_Economy",
"Business", "First", "Residence"])
possible_types = " ".join(possible_types)
while True:
if self.seat not in possible_types:
print("Sorry, but this is not a valid answer. Please try again!")
self.seat = str(input("What type of ticket would you like? The possible types are: {} "
.format(possible_types)))
else:
print("You have chosen to book a {} ticket.".format(self.seat))
confirmation = str(input("Please confirm with 'Yes' or 'No': ")).lower()
if confirmation == "yes":
print("Excellent decision! Ready to continue")
print("=" * 170)
break
elif confirmation == "no":
self.seat = str(input("What type of ticket would you like? The possible types are: {} "
.format(possible_types)))
else:
print("That doesn't seem to be a valid answer.")
Here is the main file (to execute the different classes I'll make):
import type_seat
# Choose the seat to book
print("=" * 170)
print("Welcome to Etihad! This program can help you organize your flight, payments and usage of miles!")
possible_types = []
possible_types.extend(["Low_Economy", "Standard_Economy", "High_Economy",
"Business", "First", "Residence"])
possible_types = " ".join(possible_types)
seat_type = str(input("What type of ticket would you like? The possible types are: {}. "
.format(possible_types)))
type_seat.SeatBooking(seat_type)
The problem I have is that I seem to be able to enter certain letters and it doesn't count them as an error even though they're not one of the available seats. For example, when I enter the letters "h" or "s", my error checking part of the code doesn't respond to it, but when I enter the letter "b" or random words like "try" it does. It doesn't seem to be completely random though, and it seems to only happen with letters or parts of the first 3 'items' in the possible_types[] list. However, I haven't tested this fully. This is why I thought it had something to do with lists, so if anyone knows what's causing this, I'd really appreciate it if they could help me resolve this and perhaps help me from repeating this mistake in the future!
Note, for the lists I am using .join, but I also tried str().
You don't have a list, you are testing characters against one long string:
possible_types = " ".join(possible_types)
The letters h and s are in that string (in the words High_Economy and Business, respectively), but the sequence try doesn't appear anywhere in the string.
If you only wanted to allow whole words to match, you'd need to leave possbile_types a list, or ideally convert it to a set (as sets allow for fast membership testing). You can define the list, no need for list.extend() here:
possible_types = ["Low_Economy", "Standard_Economy", "High_Economy",
"Business", "First", "Residence"]
or make it a set by using {...}:
possible_types = {"Low_Economy", "Standard_Economy", "High_Economy",
"Business", "First", "Residence"}
Do not join this into a string, just test directly against the object:
if self.seat not in possible_types:
If you still need to show the values to a user in an error message, join the values then, or store the str.join() result in a different variable for that purpose.
Note that you shouldn't deal with user input validation in the class __init__ method. Leave user interaction to a separate piece of code, and create instances of your class after you validated. That way you can easily swap out user interfaces without having to adjust all your data objects too.
possible_types = " ".join(possible_types)
Above statement will create one string as "Low_Economy Standard_Economy High_Economy Business First Residence".
Now you are doing
if self.seat not in possible_types:
This will check for a particular character in the string present or not. In your case you are finding 'h' which is present and 'try' which isn't.
Your program will work if you remove this statement
possible_types = " ".join(possible_types)

Why doesn't the second part of this loop work? [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
The user should insert a name as an input and then confirm with a yes or no (or any of its derivatives) if the 3 worded name includes a middle name or not. So far, I've gotten the loop to work if the answer is yes; however it keeps looping the question if the answer is no.
The purpose: if the answer is yes, the program will understand its a 3 worded name with a middle name and therefore execute naming combinations with the middle name; if its no, the program will understand its a 3 worded name with a second last name instead of a middle name and therefore execute naming combinations accordingly.
Please note I have exluded a lot of the code for sharing purposes.
What I'm I doing wrong? My question is in regards to the elif part of the loop.
print ('enter name')
providedname = input ()
while providedname != 'quit':
if len(providedname.split())==4:
pass
elif len(providedname.split())==3:
print ('Does the name include a middle name or middle initial? Please type yes or no:')
userinput = input()
if userinput.startswith ('ye' or 'Ye' or 'YE' or 'ya' or 'Ya' or 'YA'):
firstname, middlename, lastname = providedname.split()
elif userinput.startswith ('no' or 'No' or 'NO' or 'na' or 'Na' or 'NA'):
firstname, lastname, secondlastname = providedname.split()
else:
pass
print ('enter name or type quit or q to exit')
providedname=input()
continue
You can't use or like that. It makes sense in English, but it doesn't work in Python. One way to express what you're doing is with a mini for loop along with the any function, like so:
if any(userinput.startswith(string) for string in ['ye', 'Ye', 'YE', 'ya', 'Ya', 'YA']):
It reads almost like English if you shuffle the word order around a bit:
If the user input starts with any of the strings in this list...
Even better is to lowercase the input string first. Then you don't have to check so many combinations.
userinput = input().casefold() # Python 3.3+
userinput = input().lower() # Earlier
if any(userinput.startswith(string) for string in ['ye', 'ya']):
As it happens, startswith can also accept a list of strings. You can actually ditch the all the any() machinery and have simply:
if userinput.startswith(('ye', 'ya')):
(Thanks to #kindall for that tip.)
So, just run this in the interpreter
>>> 'ye' or 'Ye' or 'YE' or 'ya' or 'Ya' or 'YA'
'ye'
Your startswith isn't working the way you think it does.
Other than that, you can shorten that statement up if you lowercase your strings.
Runnable example
while True:
providedname = input ('enter name or type quit or q to exit: ')
if providedname in {'quit', 'q'}:
break
names = providedname.split()
if len(names) == 4:
pass
elif len(names) == 3:
userinput = input('Does the name include a middle name or middle initial? Please type yes or no:')
if userinput[:2].lower() in {'ye', 'ya'}:
firstname, middlename, lastname = names
elif userinput[:2].lower() in {'no' , 'na'}:
firstname, lastname, secondlastname = names
else:
pass
print(firstname, lastname)
It LOOKS as though you're missing the ending ' on the print command inside your elif ('Does the name include....), causing the rest of it to be taken as more text input. Try adding that ' and see if that helps!
First, you could have more complex names, for example, "Oscar De La Hoya", which would skip because the name would have length = 4. Ignoring 'difficult names', the next thing would be to work on cleaning the user's input. I would clean the user's input like so:
userinput = input().lower().strip()
This way you can make is simpler for yourself and also more readable.
Now you can do:
if userinput == 'yes':
firstname, middlename, lastname = providedname.split()
else:
firstname, lastname, secondlastname = providedname.split()
Finally (as the other answer states), if a 'valid' input is given, you'll want to break out of the while loop with a break.
You have 2 main problems (ignoring all the syntax errors assuming that they are just here on your question but your actual code is OK)
First you are never breaking out of the while loop, you must use the break statement anywhere you want to exit the loop.
Second you are overwriting the providedname at the end of the loop, that will leave you without the actual name, the variable will be quit even after the correct name was provided.

Categories