Python IF Statement not being displayed [duplicate] - python

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 8 years ago.
currently I am getting to grips with Python and I am trying to produce a small script, however I am having issues with an IF statement, ideally I would like it so if the user inputs an "N" or 'n' for "No" then I like this sentence to be displayed "Thank you for using FinalGrade. Goodbye." However, it only loops back and reacts as if I had entered "Y", allowing another student to be inputted.
Heres my code:
results = []
cont = 'y' or 'Y'
print ("\n")
print ("-----------------------------------------------------------------------------")
print ("\n")
Institution = str(input("Please Enter the Name of Your Insitution: "))
while cont=='y' or 'Y':
print ("\n")
print ("---------------------------------NEW STUDENT---------------------------------")
print ("\n")
Year = str(input("Please Enter the Year of the Student (For Example, 'Year 1 / 2 / 3 / 4'): "))
print ("\n")
print ("-----------------------------------------------------------------------------")
print ("\n")
Student = str(input("Student Full Name: "))
print ("\n")
Grade1 = int(input("Enter Student's First Term Grade: "))
Grade2 = int(input("Enter Student's Second Term Grade: "))
Grade3 = int(input("Enter Student's Third Term Grade: "))
Grade4 = int(input("Enter Student's Fourth Term Grade: "))
average = (Grade1+Grade2+Grade3+Grade4)/4
print ("\n")
print ("-----------------------------------------------------------------------------")
print ("\n")
print ("Total Grade Average: %G" % (average))
passed_or_failed = "PASSED"
if average < 40:
passed_or_failed = 'FAILED'
results.append(passed_or_failed)
print ("\n")
print ("%s has: %s" % (Student, passed_or_failed))
print ("\n")
The main issues I am having in my code are shown below:
cont = input('Do you want to keep entering students? Y/N: ')
if cont=='N' or 'n':
print ("\n")
print ("-----------------------------------------------------------------------------")
print ("\n")
print ("Thank you for using FinalGrade. Goodbye.")
Is there any solution to this problem? Thank you.

if cont=='N' or 'n':
You need to do either:
if cont in "nN":
or:
if cont in ["n", "N"]:
or even:
if cont.lower() == "n":
Writing what you had if cont=='N' or 'n': would not evaluate correctly as you expect.
This is essentially saying:
if cont is ("N" or "n") then do something
Note: the brackets around ("N" or "n"); this will evaluate to True and then your
if statement becomes: if cont == True: which always evaluates to True.
See:
>>> cont = "Y"
>>> if cont == "N" or "n":
... print "cont is N or n"
...
cont is N or n
Update::
You will also want to change your code structure a bit as well to something like this:
while True:
... most of your code ...
cont = raw_input("Do you want to continue? (Y/N)")
if cont.lower() == "n":
break
Update II: From your comments Here is a complete corrected version of your program:
#!/usr/bin/env python
#FinalGrade
results = []
print ("\n")
print ("-----------------------------------------------------------------------------")
print ("\n")
Institution = str(input("Please Enter the Name of Your Insitution: "))
while True:
print ("\n")
print ("---------------------------------NEW STUDENT---------------------------------")
print ("\n")
Year = str(input("Please Enter the Year of the Student (For Example, 'Year 1 / 2 / 3 / 4'): "))
print ("\n")
print ("-----------------------------------------------------------------------------")
print ("\n")
Student = str(input("Student Full Name: "))
print ("\n")
Grade1 = int(input("Enter Student's First Term Grade: "))
Grade2 = int(input("Enter Student's Second Term Grade: "))
Grade3 = int(input("Enter Student's Third Term Grade: "))
Grade4 = int(input("Enter Student's Fourth Term Grade: "))
average = (Grade1+Grade2+Grade3+Grade4)/4
print ("\n")
print ("-----------------------------------------------------------------------------")
print ("\n")
print ("Total Grade Average: %G" % (average))
passed_or_failed = "PASSED"
if average < 40:
passed_or_failed = 'FAILED'
results.append(passed_or_failed)
print ("\n")
print ("%s has: %s" % (Student, passed_or_failed))
print ("\n")
cont = input('Do you want to keep entering students? Y/N: ')
if cont.lower() == "n":
print ("\n")
print ("-----------------------------------------------------------------------------")
print ("\n")
print ("Thank you for using FinalGrade. Goodbye.")
break
Sample run: http://codepad.org/hvoYCXWL
Note that the condition to check for entering more data is properly indented inside the while loop's block. This is important.

if cont=='N' or 'n':
Should be
if cont=='N' or cont == 'n':
Or better
if cont in [ 'N', 'n' ]:

Related

How to select just 1 element in a list for a if statement

This program prints 'Select a Valid function!' even if the input is correct, why is that? And how can I tell the program that I'm talking about individual elements in a list and not the entire list?
sign = input ("Enter the sign: ")
if sign != ["+","-","*","/"]:
print ("Select a Valid function!")
else:
print ("Let's Begin")
if sign =="+":
no1 = input("Enter the first number: ")
no2 = input("Enter the second number: ")
print (int(no1)+int(no2))
elif sign =="-":
no1 = input("Enter the first number: ")
no2 = input("Enter the second number: ")
print (int(no1)-int(no2))
elif sign =="*":
no1 = input("Enter the first number: ")
no2 = input("Enter the second number: ")
print (int(no1)*int(no2))
elif sign =="/":
no1 = input("Enter the first number: ")
no2 = input("Enter the second number: ")
print (int(no1)/int(no2))
if sign != ["+","-","*","/"]:
That will always be true, because sign is not a list, so it will never be equal to a list.
You want to use the in operator instead:
if sign not in ["+","-","*","/"]:
As others have pointed out, you're not using the correct operator to check if something is in a list.
But you don't even need that check. Just add an else: statement after all the if/elif.
sign = input ("Enter the sign: ")
if sign =="+":
no1 = input("Enter the first number: ")
no2 = input("Enter the second number: ")
print (int(no1)+int(no2))
elif sign =="-":
no1 = input("Enter the first number: ")
no2 = input("Enter the second number: ")
print (int(no1)-int(no2))
elif sign =="*":
no1 = input("Enter the first number: ")
no2 = input("Enter the second number: ")
print (int(no1)*int(no2))
elif sign =="/":
no1 = input("Enter the first number: ")
no2 = input("Enter the second number: ")
print (int(no1)/int(no2))
else:
print ("Select a Valid function!")
This way you don't need to keep the list consistent with the list of signs that you implement.
As others have said change:
if sign != ["+","-","*","/"]:
to
if sign not in ["+","-","*","/"]:
to test for non-membership of a list.
You can also cut down on a lot of duplication in your code and avoid the if...elif statements by using a dictionary of operators like this:
import operator
ops = {'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': operator.truediv
}
sign = input ("Enter the sign: ")
if sign not in ops:
print ("Select a Valid function!")
else:
print ("Let's Begin")
no1 = int(input("Enter the first number: "))
no2 = int(input("Enter the second number: "))
ans = ops[sign](no1, no2)
print(ans)

I'm trying to make a quiz on Python but my code keeps repeating

So, I'm trying to make a basic quiz in Python and when I get to a certain point when I'm testing the program my code will repeat for reasons I can't seem to work out...
My code:
`if choice == "2": #If the user enters 2 they will be taken here.
print (" ") #Makes a break between lines.
username=input ("Please enter your username:")
print (" ") #Makes a break between lines.
password=input ("Please enter your password:")
file=open ("userinformation.txt","r")
for line in file:
if username and password in line:
print (" ") #Makes a break between lines.
print ("Thank you for logging in " + username+".")
time.sleep (3)
#file.close()
print (" ") #Makes a break between lines.
print ("Please choose a topic and a difficulty for your quiz.")
time.sleep (4)
print (" ") #Makes a break between lines.
print("a.History - Easy.")
print (" ") #Makes a break between lines.
print("b.History - Medium.")
print (" ") #Makes a break between lines.
print("c.History - Hard.")
print (" ") #Makes a break between lines.
print("d.Music - Easy.")
print (" ") #Makes a break between lines.
print("e.Music - Medium.")
print (" ") #Makes a break between lines.
print("f.Music - Hard.")
print (" ") #Makes a break between lines.
print("g.Computer Science - Easy.")
print (" ") #Makes a break between lines.
print("h.Computer Science - Medium.")
print (" ") #Makes a break between lines.
print("i.Computer Science - Hard.")
print (" ") #Makes a break between lines.
topic = input("To choose a topic please enter the corrosponding letter:")
if topic == "a":
print (" ") #Makes a break between lines.
time.sleep(2)
print ("You have selected option a, History - Easy.") #Tells the user what subject they picked (Same result but with a different topic and difficulty displayed for each one
print (" ")
print ("Rules: You have an unlimited amount of time to anwser each question. You will be anwsering 2 questions and each question anwsered correctly")
print ("will reward you with 10 points.")
time.sleep(9)
print (" ")
print ("The maximum amount of points you can get is 20.")
time.sleep(3)
print (" ")
print ("Good luck!")
print (" ")
time.sleep(2)
print ("Question 1 -")
print ("When did World War 1 begin and end?")
print ("a. 1913 - 1917") #Incorrect anwser
print (" ")
print ("b. 1914 - 1919") #Incorrect anwser
print (" ")
print ("c. 1914 - 1918") #Correct anwser
anwserq1he = input ("Please pick an anwser:")
if anwserq1he == "b":
print(" ")
print("Sorry, that's the wrong anwser...")
time.sleep(3)
print(" ")
hisready = input ("Type ok when you are ready to proceed to the next question.")
elif anwserq1he == "a":
print(" ")
print("Sorry, that's the wrong anwser...")
time.sleep(3)
print(" ")
hisready = input ("Type ok when you are ready to proceed to the next question.")
elif anwserq1he == "c":
print(" ")
print ("That's the right anwser!")
print(" ")
time.sleep(2)
print ("Adding 10 points to your score...")
score = score +10
print(" ")
time.sleep(3)
hisready = input ("Type ok when you are ready to proceed to the next question.")
if hisready == "ok":
print(" ")
time.sleep(2)
print ("Question 2-")
print ("Which historical figure is commonly known as 'The lady with the lamp'?")
print ("a. Margaret Fuller")
print (" ")
print ("b. Florence Nightingale")
print (" ")
print ("c. Rosa Luxemburg")
anwserq2he = input ("Please pick an anwser:")
if anwserq2he == "a":
print ("Sorry, that's the wrong anwser...")
results = input("Please type results to get your results")
elif anwserq2he == "c":
print ("Sorry, that's the wrong anwser...")
results = input("Please type results to get your results")
elif anwserq2he == "b":
print (" ")
time.sleep(2)
print ("That's the right anwser!")
print(" ")
time.sleep(2)
print ("Adding 10 points to your score...")
score = score + 10
results = input("Please type results to get your results.")
if results == "results":
print(" ")
time.sleep(3)
print ("Getting your results...")
if score == 20:
print ("Congratulations, you scored 20 points. That's the best score you can get!")
elif score == 10:
print ("Well done, you scored 10 points. Almost there!")
elif score == 0:
print ("You scored 0 points. Try again and you might do better!")`
When I complete the quiz everything beyond print ("Thank you for logging in " + username+".")repeats...I'd appreciate it if anyone could help me. Thank you.
Sidenote: The #file.close is intentional.
Alright, so first of all we need to improve the program layout , maybe call in some functions would be useful. Here is some tips to fix the program.
First of all use : if username.strip() and password.strip() in line: [Use the .strip() function so it will match a word.
Your program is inefficient because if you press another value as in 2 it will break the program. You want to loop it and loop it over and over again therefore use the while True statement and create a function.
Add a function called exampleFunction() (I.E) and then on the bottom of the code ad this line but obviously indent it.
while True:
exampleFunction()
You don't need to use a or r just do file=open("your file.txt")
For example,
genre=input("What is the film you would like to search?: ")
f=open("Films.txt")
for line in f:
if genre in line.strip():
print(line)
I would personally fix this myself and post a copy of the code however this is too minor to fix therefore i'm leaving it to you.
Goodluck,
Matin

Average of marks for three topics

I am trying to create a program that will ask the user for a username and password. If the login details are correct, the program should ask for the students name and then ask for three scores, one for each topic. The program should ask the user if they wish to enter another students details. The program should output the average score for each topic. I cannot work out how to enter the student marks for each topic per student and also how to work out the average for each topic for the class.
Can you please help?
login="teacher"
password="school"
usrnm=input("Please enter your username: ")
pw=input("Please enter your password: ")
if (usrnm==login) and (pw==password):
print("==Welcome to the Mathematics Score Entry Program==")
print("Do you want to enter the students score? Yes/No: ")
option = input()
option = option.title()
student_info = {}
student_data = ['Topic 1 : ', 'Topic 2 : ', 'Topic 3 : ']
while (option != "No"):
student_name = input("Name: ")
student_info[student_name] = {}
score1 = int(input("Please enter the score for topic 1: "))
student_info[student_name][Topic_1] = score1
score2 = int(input("Please enter the score for topic 2: "))
student_info[student_name][Topic_2] = score2
score3 = int(input("Please enter the score for topic 3: "))
student_info[student_name][Topic_3] = score3
print("Do you want to enter the students score? Yes/No: ")
option = input()
option = option.title()
average = sum(student_info.values())/len(student_info)
average = round(average,2)
print ("The average score is ", average)
else:
print("Access denied!")
just keep the marks seperate from the student names
students = []
marks = []
option = ""
while (option != "No"):
students.append(input("Name"))
marks.append([float(input("Mark_Category1:")),
float(input("Mark_Category2:")),
float(input("Mark_Category3:"))])
option = input("Add Another?")
import numpy
print(numpy.average(marks,0))
if you really want to do it without numpy
averages = [sum(a)/float(len(a)) for a in zip(*marks)] # transpose our marks and average each column

need help writing if else statement atm in python 2.7 for a pin protection

Im trying to create a pin protection thing for my ATM and you can enter a code etc. It then asks you for it however I want it so if you enter the wrong passcode it says incorrect try again and you cant continue into the main program. Maybe there could be a certain amount of tries? and also don't I have to write to a file if I want to save stuff? but nevermind that unless you know how I could use it in my code....
balance = float(0)
userInput = None
print("Hello, Welcome to the ATM")
print("")
print("Please begin with creating an account")
name = raw_input("Enter your name: ")
code = raw_input("Please enter a 4 digit pin to use as your passcode: ")
code = int(input('Please enter the 4 digit pin on your card:'))
if code == (code): print("correct pin!")
print "Hello , welcome to the ATM"
while userInput != "4":
userInput = raw_input("\n what would you like to do?\n\n (1)Check balance\n (2)Insert funds\n" +
" (3)Withdraw funds\n (4)Exit the ATM\n" )
if userInput == "1":
print "your balance is", "£" , balance
elif userInput == "2":
funds = float(raw_input("Enter how much money you want to add"))
balance = balance + funds
elif userInput == "3":
withdraw = float(raw_input("Enter how much money you want to withdraw..."))
balance = balance - withdraw
elif userInput == "4":
print "Thanks for using the ATM!"
balance = float(0)
userInput = None
print("Hello, Welcome to the ATM")
print("")
print("Please begin with creating an account")
name = raw_input("Enter your name: ")
# take the code as a string
saved_code = str(raw_input("Please enter a 4 digit pin to use as your passcode: "))
#validate that the code is a number and is 4 digit
try:
int(saved_code)
if len(saved_code)!=4:
raise
except Exception, e:
print("Error: Pin is not a valid 4 digit code")
exit()
# set trails and trail counter
totalTrails = 3;
currentTrail = 0;
status = 1;
# take input from user and compare codes
while currentTrail < totalTrails:
user_code =str(raw_input('Please enter the 4 digit pin on your card:'))
if user_code==saved_code:
status=0
break;
else:
currentTrail+=1
if status==0:
print("correct pin!")
else:
print("You tried to enter a wrong code more than three times.")
exit();
print "Hello , welcome to the ATM"
while userInput != "4":
userInput = raw_input("\n what would you like to do?\n\n (1)Check balance\n (2)Insert funds\n" +
" (3)Withdraw funds\n (4)Exit the ATM\n" )
if userInput == "1":
print "your balance is", "$" , balance
elif userInput == "2":
funds = float(raw_input("Enter how much money you want to add"))
balance = balance + funds
elif userInput == "3":
withdraw = float(raw_input("Enter how much money you want to withdraw..."))
balance = balance - withdraw
elif userInput == "4":
print "Thanks for using the ATM!"

Python not recognizing variables in while loops

I'm new to programming with python/in general. The goal is to produce a random number and have the user guess the number, telling the user if their guess is correct, too high, or too low. For some reason, it says "too low" no matter what I do. Here's what I have so far:
import random
numberGenerated = random.randint (1, 5)
userInput = raw_input("Enter a number between one and five: ")
numberEntered = int(userInput)
while numberEntered > numberGenerated:
print "Your guess was too high"
userInput = raw_input("Enter a number between one and five: ")
while numberEntered < numberGenerated:
print "Your guess was too low"
userInput = raw_input("Enter a number between one and five: ")
else:
print "You're Correct!"
an other way to do this is by keeping a boolean value. This makes your code better structured and readable.
import random
numberGenerated = random.randint (1, 5)
numberEntered = int(raw_input("Enter a number between one and five: "))
match=False
while not match:
if numberEntered > numberGenerated:
print "Your guess was too high"
numberEntered =int(raw_input("Enter a number between one and five: "))
elif numberEntered < numberGenerated:
print "Your guess was too low"
numberEntered =int(raw_input("Enter a number between one and five: "))
elif numberEntered == numberGenerated:
print "You're Correct!"
match = True
if you wrap everything in a function you could use the boolean value to start a new game recursively.
import random
def playGame():
match=False
numberGenerated = random.randint (1, 5)
numberEntered =int(raw_input("Enter a number between one and five: "))
while not match:
if numberEntered>numberGenerated:
print "Your guess was too high"
numberEntered =int(raw_input("Enter a number between one and five: "))
elif numberEntered<numberGenerated:
print "Your guess was too low"
numberEntered =int(raw_input("Enter a number between one and five: "))
elif numberEntered==numberGenerated:
print "You're Correct!"
match = True
if match:
again =raw_input("type 'Y' to play again")
if again.upper() == "Y":
playGame()
playGame()
You should use proper logic...
try this and ask if you have any doubts
import random
numberGenerated = random.randint (1, 5)
userInput = raw_input("Enter a number between one and five: ")
numberEntered = int(userInput)
while numberEntered!=numberGenerated:
while numberEntered>numberGenerated:
print "Your guess was too high"
#print numberGenerated
userInput = raw_input("Enter a number between one and five: ")
numberEntered = int(userInput)
while numberEntered<numberGenerated:
print "Your guess was too low"
#print numberGenerated
userInput = raw_input("Enter a number between one and five: ")
numberEntered = int(userInput)
print "You're Correct!"

Categories

Resources