Function loop True or False - python

I am now learning functions in python. I came across an exercise that asks me to write a script that will tell the user that the student is in a class or not. Here is the result that the script should present:
Welcome to the student checker!
Please give me the name of a student (enter 'q' to quit): [student1]
No, that student is not in the class.
Please give me the name of a student (enter 'q' to quit): [student2]
Yes, that student is enrolled in the class!
Please give me the name of a student (enter 'q' to quit): q
Goodbye!
I have written a script that fulfills the requirements. Here is the script:
print "Welcome to the student checker!"
students = ['Andreas', 'Martina', 'Maria']
while True:
name_student = raw_input("Please give me the name of a student (enter 'q' to quit): ")
if name_student == 'q':
print "Goodbye!"
break
if name_student in students:
print "Yes, {} is enrolled in the class!".format(name_student)
elif name_student not in students:
print "No, {} is not in the class.".format(name_student)
But the exercise states that there should be a function that returns True if the student is present, and False if not.
Could anybody enlighten me on how can I change my script to fulfill the requirement of adding a function that returns True if the student is present, and False if not?
Thanks in advance!! Peace!!!

Try doing something like this:
print "Welcome to the student checker!"
students = ['Andreas', 'Martina', 'Maria']
def is_present(name_student):
if name_student in students:
print "Yes, {} is enrolled in the class!".format(name_student)
return True
elif name_student not in students:
print "No, {} is not in the class.".format(name_student)
return False
while True:
name_student = raw_input("Please give me the name of a student (enter 'q' to quit): ")
if name_student == 'q':
print "Goodbye!"
break
is_present(name_student)
Wrap the logic into a function, so it can return a value, and call it each time your infinite loop iterates.
#edit
#barak manos is right, I updated the code

The following is one way to convert the student test into a function:
def student_present(student):
return student in ['Andreas', 'Martina', 'Maria']
print "Welcome to the student checker!"
while True:
name_student = raw_input("Please give me the name of a student (enter 'q' to quit): ")
if name_student == 'q':
print "Goodbye!"
break
if student_present(name_student):
print "Yes, {} is enrolled in the class!".format(name_student)
else:
print "No, {} is not in the class.".format(name_student)
Note student in [xxxxxx] automatically gives you a boolean result which can be returned directly. There is no need to explicitly return True and False.
Another point to consider, what happens if martina is entered? Using the current code it would state not in class. If you changed the function as follows, it would also accept this:
def student_present(student):
return student.lower() in ['andreas', 'martina', 'maria']

Related

Python loop from begining without running again the code

I don't know how I'm supposed to loop this code from the beginning without running the code again. I know I should put while True():
list_of_students = ["Michele", "Sara", "Cassie", "Andrew"]
name = input("Type name to check: ")
if name in list_of_students:
print("This student is enrolled.")
elif name not in list_of_students:
print("This student is not enrolled.")
while True:
If I don't want to duplicate the code, what should I do?
While True should be sufficient to have that input test run repeatedly.
while True:
name = input("Enter a name to check: ")
if name in list_of_students:
print("This student is enrolled")
else:
print("This student is not enrolled")
Are you looking to create a program that infinitely accepts a search argument?
If so the code would look like so:
list_of_students = ["Michele", "Sara", "Cassie", "Andrew"]
while True:
name = input("Type name to check: ")
if name in list_of_students:
print("This student is enrolled.")
else:
print("This student is not enrolled.")
Otherwise please further explain the problem.
list_of_students = ["Michele", "Sara", "Cassie", "Andrew"]
def student_checker(name):
if name == list_of_students:
print("This student is enrolled.")
elif name not in list_of_students:
print("This student is not enrolled.")
# Test to make sure it is working, comment out when not wanted
student_checker("Michele")
student_checker("Anthony")
while True:
name = input("Type name to check: ")
NOTE: this will run continuously, please make sure to add a breaking condition when you want the code to finish.

How can I restart my python 3 script?

I am making a program on python 3. I have a place that I need the script to restart. How can I do this.
#where i want to restart it
name= input("What do you want the main character to be called?")
gender = input("Are they a boy or girl?")
if gender == "boy":
print("Lets get on with the story.")
elif gender == "girl":
print("lets get on with the story.")
else:
print("Sorry. You cant have that. Type boy or girl.")
#restart the code from start
print("Press any key to exit")
input()
It's a general question about programming an not specific to Python ... by the way you can shorten your code with the two conditions on boy and girl...
while True:
name= input("What do you want the main character to be called?")
gender = input("Are they a boy or girl?")
if gender == "boy" or gender == "girl":
print("Lets get on with the story.")
break
print("Sorry. You cant have that. Type boy or girl.")
print("Press any key to exit")
input()
Simple but bad solution but you get the idea. I am sure, you can do better.
while True:
name= input("What do you want the main character to be called?")
gender = input("Are they a boy or girl?")
if gender == "boy":
print("Lets get on with the story.")
elif gender == "girl":
print("lets get on with the story.")
else:
print("Sorry. You cant have that. Type boy or girl.")
#restart the code from start
restart = input("Would you like to restart the application?")
if restart != "Y":
print("Press any key to exit")
input()
break
Don't have the program exit after evaluating input from the user; instead, do this in a loop. For example, a simple example that doesn't even use a function:
phrase = "hello, world"
while (input("Guess the phrase: ") != phrase):
print("Incorrect.") //Evaluate the input here
print("Correct") // If the user is successful
This outputs the following, with my user input shown as well:
Guess the phrase: a guess
Incorrect.
Guess the phrase: another guess
Incorrect.
Guess the phrase: hello, world
Correct
or you can have two separate function written over, It's same as above(only it's written as two separate function ) :
def game(phrase_to_guess):
return input("Guess the phrase: ") == phrase_to_guess
def main():
phrase = "hello, world"
while (not(game(phrase))):
print("Incorrect.")
print("Correct")
main()
Hope this is what you are looking for .

Looping with a while statement while reading a string for an integer

I need help encasing the:
if any(c.isdigit() for c in name):
print("Not a valid name!")
inside of a while statement. This pretty much just reads the input for the "name" variable and sees if there's an integer in it. How could I use that in a while statement? I just want it to be if the user inputs a variable into the input, it will print out the string up above and loop back and ask the user for their name again until they successfully enter in a string with no integer, then I want it to break. Any help?
print("Hello there!")
yn = None
while yn != "y":
print("What is your name?")
name = raw_input()
if any(c.isdigit() for c in name):
print("Not a valid name!")
print("Oh, so your name is {0}? Cool!".format(name))
print("Now how old are you?")
age = raw_input()
print("So your name is {0} and you're {1} years old?".format(name, age))
print("y/n?")
yn = raw_input()
if yn == "y":
break
if yn == "n":
print("Then here, try again!")
print("Cool!")
Use while True and a break to end the loop when a valid name has been entered:
while True:
name = raw_input("What is your name? ")
if not any(c.isdigit() for c in name):
break
print("Not a valid name!")
This is much easier than first initializing name to something that is invalid then using the any() expression in the while test.
Something like this:
name = input("What is your name? : ")
while any(c.isdigit() for c in name):
print ("{0} is invalid, Try again".format(name))
name = input("What is your name? : ")
demo:
What is your name? : foo1
foo1 is invalid, Try again
What is your name? : 10bar
10bar is invalid, Try again
What is your name? : qwerty
Are you just saying you want a continue after your print("Not a valid name!")?
print("Hello there!")
yn = None
while yn != "y":
print("What is your name?")
name = raw_input()
if any(c.isdigit() for c in name):
print("Not a valid name!")
continue
print("Oh, so your name is {0}? Cool!".format(name))
...
The continue will just go back to the top of your loop.

Saving Raw_input to a list when used in a While Loop

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.

Python - Problems with my loop and print out format

I am trying to let a user keep entering module and grades and store it as a dictionary {module:grades} and store this dictionary in a list.
I have 3 issues in this.
I am unable to use F6 in the second raw_input which is F7.
Secondly, I am using 'done' to stop the loop. When I print the information it looks like this:
{done : 100}
{done : 80}
and so on.. So the module name keeps getting replaced by the word 'done'.
And lastly I am trying to make the print out appear as follows: (which is not hapening now..)
Grades: Computer Science: 100
Computer Graphics: 80
I have finished the rest of my work less this portion which I am stuck with. Any assistance is deeply appreciated. Thank you so much.
students = []
class Student:
grades = {}
def setGrades(self, grades):
self.grades = grades
def addStudent():
while F6 != 'done':
F6 = raw_input("Please enter module name. type 'done' to quit: ")
if F6 == 'done':
break
F7 = raw_input("Please enter the grades for " ,F6, ':')
student.setGrades({F6:F7})
For starters, your code (as is) should look something like this
students = []
class Student:
grades = {}
def setGrades(self, grades):
self.grades = grades
def addStudent():
while True:
F6 = raw_input("Please enter module name. type 'done' to quit: ")
if F6 == 'done':
break
F7 = raw_input("Please enter the grades for " ,F6, ':')
student.setGrades({F6:F7})
In my opinion you should also have a better api for setting Grades. Something like this would suffice imo:
def set_grades(self, lesson, grade):
self.grades[lesson] = grade
Finally in order to print the grades you should have a method like this:
def print_grades(self):
for lesson, grade in grades.items():
print lesson, grade
Last but not least in your raw input, in order to use F6 you have to do something like that:
F7 = raw_input("Please enter the grades for %s: " % F6)
To sum it all up, if I were you my code would look something like this:
class Student:
grades = {}
def set_grades(self, lesson, grade):
self.grades[lesson] = grade
def addStudent():
while True:
F6 = raw_input("Please enter module name. type 'done' to quit: ")
if F6 == 'done':
break
F7 = raw_input("Please enter the grades for %s: " % F6)
student.setGrades(F6, F7)
def print_grades(self):
for lesson, grade in grades.items():
print lesson, grade

Categories