Python Forum
Else Statement Not Working
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Else Statement Not Working
#1
This is homework, but I'm not asking anyone to do my homework for me. My professor isn't helping me with anything and I've been stuck on this one question for the past 6 hours. Here's what the questions is:
3. Write a program that lets the user type in the name of a file. Attempt to open the supplied file for read access. If the file exists, you can print out a confirmation message. If the file doesn't exist, you should tell the user that the file cannot be found.

Hint: use a try/except block to do this (don't just use a series of "if" statements - we want this program to be as "generic" as possible).

You will not get credit for this part of the program if you write something like the following to identify valid data files:

filename = input("Enter a filename: ")

if filename == "class1":
# open class1.txt
elif filename == "class2":
# open class2.txt
else:
print ("Sorry, I can't find this filename")

Here's the sample of the program you will use to test this problem:

Enter a class file to grade (i.e. class1 for class1.txt): foobar
File cannot be found.

Enter a class file to grade (i.e. class1 for class1.txt): class1
Successfully opened class1.txt


And here's what I've written as my code:

def inputfilename():
    filename = input("Filename (with extension): ")
    if filename == "class1.txt" or "class2.txt":
        openfile = open(filename, "r")
        contents = openfile.read()
        print(contents)
        contents = openfile.close()

    else:
        print("File cannot be found")

inputfilename()
inputfilename()


Whenever I type in "class1.txt" or "class2.txt", it works perfectly fine, returning the contents of both files. Whenever I type in "foobar", or anything besides "class1.txt" or "class2.txt", it returns this:
Traceback (most recent call last):
File "C:\Users\Gary\Desktop\School\Assignment Leftovers\A5\trash.py", line 12, in <module>
inputfilename()
File "C:\Users\Gary\Desktop\School\Assignment Leftovers\A5\trash.py", line 4, in inputfilename
openfile = open(filename, "r")
FileNotFoundError: [Errno 2] No such file or directory: 'foobar'


It should be returning "File cannot be found.", but it appears the "else" statement isn't properly working.

Does anyone know what I'm doing wrong? Please help soon, my assignment is due 7/21 at midnight (EST).
My code is properly spaced, but I don't know how to properly use this site, so it won't let me add spacing, sorry.
Reply
#2
(Jul-20-2019, 11:24 PM)SenkouSimmer Wrote: if filename == "class1.txt" or "class2.txt":
This is your problem. Read this tutorial as it will explain why.

In simple terms:
Your if condition is always true regardless of what you put because this string "class2.txt" returns True always.
Recommended Tutorials:
Reply
#3
if filename == "class1.txt" or filename == "class2.txt":
But your professor has written, that you don't get credits for this.
Is only class1.txt and class2.txt allowed? Why? If only this two files are
allowed to access, why to write them out instead of using a kind of menu or
command line arguments.

You can use a list or tuple with filenames. Then you can check, if filename is in the iterable.
filename = 'something'
allowed_filenames = ('class1.txt', 'class2.txt')
if filename in allowed_filenames:
    #code

# filename in allowed_filenames returns True, because 'something' is not in the tuple.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#4
(Jul-20-2019, 11:24 PM)SenkouSimmer Wrote: Hint: use a try/except block to do this (don't just use a series of "if" statements - we want this program to be as "generic" as possible).

The task is to use a try/except block, catch the FileNotFoundError exception.
Reply
#5
Pseudocode:
1. get filename
2. start try/except block
3. open the supplied filename for read
4. if no error, display success message
5. in the exception script (the part that executes if there is an exception), display message "not found"
6. end try/except block
7. drink coffee.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  if statement not working g0g0g1g 2 1,631 Sep-08-2020, 05:40 PM
Last Post: nilamo
  Simple IF statement not working as intended gortexxx 2 2,772 May-17-2018, 07:54 PM
Last Post: gortexxx
  help! if statement not working molliemae 2 2,576 Apr-26-2018, 11:13 PM
Last Post: woooee

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020