name1 = input("What is your first name: ")
name2 = input("What is your last name: ")
grades = []
prompt = "Enter your grade or enter '1234' to get your letter grade and average: "
print('Please enter your grades:')
grade1 = input(prompt).strip()
while (prompt != 1234):
grades.append(grade1)
grade1 = input(prompt).strip()
else:
print (name1.title().strip(), name2.title().strip())
average = (sum(grades) / len(grades))
print (average)
I need this to print out the name and average. When I input '1234' it just goes on normally. Can you help me so it makes it output the else statement? Thanks.
This is one problem:
while (prompt != "1234"):
You're comparing the prompt (which is "Enter your grade...") to the number 1234, and the prompt never changes. Which means it will never be equal to 1234, so it will go on forever! I believe you want to compare to grade1, rather than prompt.
Another issue, is the else statement:
else:
print (name1.title().strip(), name2.title().strip())
average = (sum(grades) / len(grades))
print (average)
You don't need the else statement, because you want those statements to be executed after the while loops ends, right? Then just put them after the while loop. No need for an if or if-else statement!
With those corrections, the code will look similar to this:
name1 = input("What is your first name: ")
name2 = input("What is your last name: ")
grades = []
prompt = "Enter your grade or enter '1234' to get your letter grade and average: "
print('Please enter your grades:')
grade1 = input(prompt).strip()
while (grade1 != "1234"):
grades.append(grade1)
grade1 = input(prompt).strip()
print (name1.title().strip(), name2.title().strip())
average = (sum(grades) / len(grades))
print (average)
Only a few syntax errors were holding you back, so keep up the good work!
Related
I'm making a simple game that shows up "What number do you like" and if u write a number(for example "77") it should show up an EXCEPT but it doesn't
why?
your_name = input("What's your name: ")
this_year = 2019
your_age = int(input("How old are you: "))
year_born = this_year - your_age
print("Hello",your_name,".You are",your_age,"years old","\n\n")
year_when_you_were_born = print("That means that you were
born",year_born)
hundred_year = year_born + 100
print("And that means that you are gonna be 100 years old at the year
of",hundred_year)
number = int(input("What number do you like: "))
try:
question = str(input("Do you wanna print your name that many times:
"))
except ValueError:
print("I don't get it,type words not numbers")
else:
if question == "yes":
word = your_name * question
print(word)
number = int(input("What number do you like: ")) takes the input and converts it to an int. So 77 is fine. However, letters can not be converted to a int, so that will throw a ValueError. For that the line needs to be inside the try block:
try:
number = int(input("What number do you like: "))
except ValueError:
print("I don't get it,type numbers not words")
Note that question = str(input("Do you wanna print your name that many times: ")) will not throw a ValueError, because both letters and numbers can be converted to a string. So you don't have to put it in the 'try'-block, it is better placed in the 'else' block:
try:
number = int(input("What number do you like: "))
except ValueError:
print("I don't get it,type numbers not words")
else:
question = str(input("Do you wanna print your name that many times: "))
if question == "yes":
word = your_name * question
print(word)
strFName = ""
while strFName != strFName.isalpha():
if strFName != strFName.isalpha():
strFName = input("What is your first name? ")
else:
print("Your name cannot contain numbers")
break
I want the user to enter their name, but if they enter any letters the program will throw up an error. So far I am trying to do this with a try and except but whenever I enter a number it just goes straight on to the next part of the program.
You mean the first name cannot contain digits?
If so, you can do something like this:
import string
has_digits = lambda x: any([i.isdigit() for i in x])
first_name = "0"
while has_digits(first_name):
first_name = input("Enter first name (cannot contain digits): ")
print('Your name is {}'.format(first_name))
The problem statement, all variables and given/known data
I need a program, which would break and show results once a 0 is entered in input name and input grade.
I figured how to do that in name, but how do I add another break? Like grade !="0"?
The program I have so far:
students = []
grades = []
while True:
name = input ("Enter a name: ")
if name.isalpha() == True and name != "0":
while True:
grade = input("Enter a grade: ")
if grade.isdigit()== True:
grade = int(grade)
if grade >= 1 and grade <= 10:
if name in students:
index = students.index(name)
grades[index].append(grade)
break
else:
students.append(name)
grades.append([grade])
break
else:
print("Grade is not valid. Try to enter it again!")
elif name == "0":
print("A zero is entered!")
break
else:
print ("Grade is not valid. Try to enter it again!")
for i in range(0,len(students)):
print("NAME: ", students[i])
print("GRADES: ", grades[i])
print("AVERAGE: ", round(sum(grades[i])/len(grades[i]),1), "\n")
Also is there any way that I can make Python ignore spaces in input function?
Example: I enter a grade that has "________8" in it (_ are spaces) and the program does not want to ignore it, how do I make it ignore the spaces and just accept the number as it is?
strip() method
Use strip() method of string to strip the white spaces.
Demo:
>>> a = " Go "
>>> a.strip()
'Go'
>>> a.rstrip()
' Go'
>>> a.lstrip()
'Go '
>>>
Your code will work fine. Produce correct output.
Use dictionary to save Student records.
Demo:
import collections
student_record = collections.defaultdict(list)
while True:
name = raw_input("Enter a name: ").strip()
if name=="0":
print "A zero is entered!"
break
if not name.isalpha():
print "Name is no valid. Try again. Enter alpha value only."
continue
while True:
grade = raw_input("Enter a grade: ").strip()
if grade.isdigit():
grade = int(grade)
if 1<=grade <= 10:
student_record[name].append(grade)
break
else:
print "Grade is not valid. Try again. Enter digit values between 1 and 10."
else:
print "Grade is not valid. Try again. Enter digit values."
for i, j in student_record.items():
print "\nNAME: ", i
print "GRADES: ", j
print "AVERAGE: ", round(sum(j)/len(j),1)
Output:
$ python test1.py
Enter a name: ABC
Enter a grade: 2
Enter a name: XYZ
Enter a grade: 5
Enter a name: ABC
Enter a grade: 6
Enter a name: 0
A zero is entered!
NAME: XYZ
GRADES: [5]
AVERAGE: 5.0
NAME: ABC
GRADES: [2, 6]
AVERAGE: 4.0
Note:
Use raw_input() for Python 2.x
Use input() for Python 3.x
Im new to python and I am currently working on a python script and want to add a loop at the end of it, currently the code is as follows:
#FinalGrade
print ("\n")
Institution = str(input("Please Enter the Name of Your insitution: "))
print ("\n")
Year = str(input("Please Enter the Year of the Student (For Example, 'Year 2'): "))
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 ("Total Grade Average: %G" % (average))
passed_or_failed = "PASSED"
if average < 40:
passed_or_failed = 'FAILED'
print ("\n")
print ("%s has: %s" % (Student, passed_or_failed))
Id like to find out if it would be possible to set a loop so another student can be entered, would this be possible?
Thank you
Why not put it in an infinite loop?
cont = 'y'
while cont=='y':
print ("\n")
Institution = str(input("Please Enter the Name of Your insitution: "))
print ("\n")
Year = str(input("Please Enter the Year of the Student (For Example, 'Year 2'): "))
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
...
cont = input('Do you want to keep entering students? y/n: ')
Or if you want to keep all of the results:
results = []
cont = 'y'
while cont=='y':
print ("\n")
Institution = str(input("Please Enter the Name of Your insitution: "))
...
passed_or_failed = "PASSED"
if average < 40:
passed_or_failed = 'FAILED'
results.append(passed_or_failed)
...
cont = input('Do you want to keep entering students? y/n: ')
And you can just loop through the results to see them.
You mean just one more student to be entered?
You can probably do that with a while or for loop. Something along these lines:
counter = 0
while (counter < 2):
your existing code
....
counter += 1
I have already posted a question today and it had 2 problems on it. One of which was solved perfectly, then it got a little complicated. So forgive me but I am posting the other question separately as it confused some peeps:
I am new to python so apologies in advance. Any help is much appreciated. I have been stuck on this code for 2weeks now and I have tunnel vision and cannot work it out:
Basically our assignment was to get to grips with Object-Oriented Programming. We unfortunately have to use "get" and "set" which I've learnt a lot of people dislike, however, as per our tutor we have to do it like that. We were told tp create a program whereby the user is presented with a screen with 3 options. 1. adding a student. 2. viewing a student and 3. removing a student.. within my AddStudent function I have to ask the user to enter fname Lname age degree studying id number (these are the easy bits) and also module name and grade for each module, I have managed to create a loop whereby it will ask the user over and over to enter modules and corresponding grades and will break from said loop when the user enters -1 into the modulname field. However, when trying saving it to a list named students[] ... (which is at the very top of my code above all functions, to apparently make it global) it saves all input from the user re: age name etc but when it comes to saving module names and grades it only saves the last input and not the multiple inputs I need it to. I am unsure if it is within my AddStudent function where it isn't saving or within my ViewStudent function: Both are below (remember I HAVE to use the GET and SET malarky) ;)
students[] # Global List
def addStudent():
print
print "Adding student..."
student = Student()
firstName = raw_input("Please enter the student's first name: ")
lastName = raw_input("Please enter the student's last name: ")
degree = raw_input("Please enter the name of the degree the student is studying: ")
studentid = raw_input("Please enter the students ID number: ")
age = raw_input("Please enter the students Age: ")
while True:
moduleName = raw_input("Please enter module name: ")
if moduleName == "-1":
break
grade = raw_input ("Please enter students grade for " + moduleName+": ")
student.setFirstName(firstName) # Set this student's first name
student.setLastName(lastName)
student.setDegree(degree)# Set this student's last name
student.setGrade(grade)
student.setModuleName(moduleName)
student.setStudentID(studentid)
student.setAge(age)
students.append(student)
print "The student",firstName+' '+lastName,"ID number",studentid,"has been added to the system."
........................
def viewStudent():
print "Printing all students in database : "
for person in students:
print "Printing details for: " + person.getFirstName()+" "+ person.getLastName()
print "Age: " + person.getAge()
print "Student ID: " + person.getStudentID()
print "Degree: " + person.getDegree()
print "Module: " + person.getModuleName()
print "Grades: " + person.getGrade()
your problem is that the module is a single variable you keep changing. instead, make it a list.
while True:
moduleName = raw_input("Please enter module name: ")
if moduleName == "-1":
break
grade = raw_input ("Please enter students grade for " + moduleName+": ")
should be something like
modules = []
while True:
moduleName = raw_input("Please enter module name: ")
if moduleName == "-1":
break
grade = raw_input ("Please enter students grade for " + moduleName+": ")
modules.append((moduleName, grade))
add a new variable to student which is "Modules" and is a list.
and then modules will be a list of tuples which are (moduleName, grade) and to display them, change the line in viewstudent from:
print "Module: " + person.getModuleName()
print "Grades: " + person.getGrade()
to:
for module, grade in person.getModules():
print "Module: " + module
print "Grades: " + grade
It seems you need something like this:
modules = {}
while True:
module_name = raw_input("Please enter module name: ")
if module_name:
grade = raw_input ("Please enter students grade for " + module_name +": ")
modules[module_name] = grade
Modules is a dictionary ("hash map" in other languages), each mod name is key and grades are values, or you could also do it with tuples, wherever floats your boat.
Instead of checking for -1 as a stop condition you check if is true, in python anything empty is evaluated to false.