why cant I get this if statement to show? [duplicate] - python

This question already has answers here:
Comparing numbers give the wrong result in Python
(4 answers)
Closed 3 years ago.
so I need to make sure the information I am inputting shows if its less than, greater than, or equal too.
not sure if the variable is messed up or not.
here is the code:
#the main function
def main():
print #prints a blank line
age = getAge ()
weight = getWeight()
birthMonth = getMonth()
print
correctAnswers(age, weight, birthMonth)
#this function will input the age
def getAge():
age = input('Enter your guess for age: ')
return age
#thisfunction will input the weight
def getWeight():
weight = input('Enter your guess for weight: ')
return weight
#thisfunction will input the age
def getMonth():
birthMonth = raw_input('Enter your guess for birth month: ')
return birthMonth
#this function will determine if the values entered are correct
def correctAnswers(age, weight, birthMonth):
if age <= 25:
print 'Congratulations, the age is 25 or less.'
if weight >= 128:
print 'Congatulations, the weight is 128 or more.'
if birthMonth == 'April':
print 'Congratulations, the birth month is April.'
#calls main
main()

input() function returns a string. Before performing the integer comparison you are trying to do, you have to convert string.
For example:
def getAge():
age = input('Enter your guess for age: ')
return int(age)

I have edited your code so that it will work correctly.
def main():
print #prints a blank line
age = getAge()
weight = getWeight()
birthMonth = getMonth()
print()
correctAnswers(age, weight, birthMonth)
#this function will input the age
def getAge():
age = input('Enter your guess for age: ')
return age
#thisfunction will input the weight
def getWeight():
weight = input('Enter your guess for weight: ')
return weight
#thisfunction will input the age
def getMonth():
birthMonth = raw_input('Enter your guess for birth month: ')
return birthMonth
#this function will determine if the values entered are correct
def correctAnswers(age, weight, birthMonth):
if int(age) <= 25:
print('Congratulations, the age is 25 or less.')
if int(weight) >= 128:
print('Congatulations, the weight is 128 or more.')
if birthMonth == 'April':
print('Congratulations, the birth month is April.')
#calls main
main()

Related

what is wrong with python my python code in while loop?

I don't know what is the error of my code can anyone help me to fix this code.
age = ""
while int(len(age)) == 0:
age = int(input("Enter your age: "))
print("Your age is " + age)
You wanted a string for age but you transformed this age into an integer inside your loop :)
You can write :
age = ""
while age == "":
age = input("Enter your age: ")
print("Your age is " + age)
In Python, "" and 0 (and values like None and empty containers) are considered "falsey". Not necessarily the same thing as False but logically treated like False.
So you can simplify your while loop:
age = ""
while not age:
age = input("Enter your age: ")
print("Your age is " + age)
You cast age to be an int inside of your while loop, while using the len(age) as the comparison.
int does not have a length.
You want to wait to cast age until you are outside of the loop, or in this situation, don't cast it at all.
age = ""
while len(age) == 0:
age = input("Enter your age: ")
print("Your age is " + age)

Finding the oldest and ending on specific user input

I have just started Python and I am attempting a simple exercise. It's to end a program on a user specified input and then finding the oldest age from a set of ages entered. I got the user input but having issues with the oldest age aspect. Where am I going wrong? I think I may not be 100% on the "None" aspect. Here is code below:
largest = None
while True:
name = str(input("What is your name? enter Yvonne to end program."))
if name.strip() != 'Yvonne':
age = int(input("Please enter your age"))
elif name.strip() == 'Yvonne':
if largest is None or largest < age:
largest = age
print("Oldest age is: ", largest)
break
The output I get is the wrong number being selected as the oldest:
You’ve got your test for largest in the wrong place:
largest = None
while True:
name = str(input("What is your name? enter Yvonne to end program."))
if name.strip() != 'Yvonne':
age = int(input("Please enter your age"))
if largest is None or largest < age:
largest = age
else:
print("Oldest age is: ", largest)
break

Python input ranges and types of input

How do i get it to not keep repeating after a sucessfull trial
while age == "": #make it only except numbers so it wont give an error
age = input("How old are you " + name + "? ")
if age.isdigit() == False:
print("Only digits are allowed!")
age = ""
if age not in range(0,99):
print ("Age must be between 0,90!")
age = ""
convert the input to int to check it's value:
while age == "": # make it only except numbers so it wont give an error
age = input("How old are you " + name + "? ")
if not age.isdigit():
print("Only digits are allowed!")
age = ""
elif int(age) not in range(0, 99):
print("Age must be between 0,99!")
age = ""
Your variable "age" is a string - that's what the "input" function returns. Later you check to see if it's in the range (0, 90), but the "range" function returns a sequence of integers. So "age" - a string - is NEVER in the sequence.
Here is one way to fix it:
while age == "": #make it only except numbers so it wont give an error
age = input("How old are you " + name + "? ")
if age.isdigit() == False:
print("Only digits are allowed!")
age = ""
if int(age) not in range(0,99):
print ("Age must be between 0,90!")
age = ""

Python: Returning array values from a function

I'm trying to understand how to use functions properly. In this code, I want to return 2 arrays for pupil names and percentage scores. However I am unable to return the array variables from the first function.
I've tried using different ways of defining the arrays (with and without brackets, both globally and locally)
This is the relevant section of code for the program
#function to ask user to input name and score
def GetInput():
for counter in range(0,10):
names[counter] = input("Please enter the student's name: ")
valid = False
while valid == False:
percentages[counter] = int(input("Please enter the student's score %: "))
if percentages[counter] < 0 or percentages[counter] > 100:
print("Please enter a valid % [0-100]")
else:
valid = True
return names, percentages
name, mark = GetInput()
I'm expecting to be asked to enter the values for both arrays.
I'm instead getting:
Traceback (most recent call last):
File "H:/py/H/marks.py", line 35, in <module>
name, mark = GetInput()
File "H:/py/H/marks.py", line 7, in GetInput
names[counter] = input("Please enter the student's name: ")
NameError: global name 'names' is not defined
You need to use dictionary instead of list if your want to use key-value pairs. furthermore you need to return the values outside of for loop. You can try the following code.
Code:
def GetInput():
names = {} # Needs to declare your dict
percentages = {} # Needs to declare your dict
for counter in range(0, 3):
names[counter] = input("Please enter the student's name: ")
valid = False
while valid == False:
percentages[counter] = int(input("Please enter the student's score %: "))
if percentages[counter] < 0 or percentages[counter] > 100:
print("Please enter a valid % [0-100]")
else:
valid = True
return names, percentages # Return outside of for loop.
name, mark = GetInput()
print(name)
print(mark)
Output:
>>> python3 test.py
Please enter the student's name: bob
Please enter the student's score %: 20
Please enter the student's name: ann
Please enter the student's score %: 30
Please enter the student's name: joe
Please enter the student's score %: 40
{0: 'bob', 1: 'ann', 2: 'joe'}
{0: 20, 1: 30, 2: 40}
If you want to create a common dictionary which contains the students' name and percentages, you can try the following implementation:
Code:
def GetInput():
students = {}
for _ in range(0, 3):
student_name = input("Please enter the student's name: ")
valid = False
while not valid:
student_percentages = int(input("Please enter the student's score %: "))
if student_percentages < 0 or student_percentages > 100:
print("Please enter a valid % [0-100]")
continue
valid = True
students[student_name] = student_percentages
return students
students = GetInput()
print(students)
Output:
>>> python3 test.py
Please enter the student's name: ann
Please enter the student's score %: 20
Please enter the student's name: bob
Please enter the student's score %: 30
Please enter the student's name: joe
Please enter the student's score %: 40
{'ann': 20, 'bob': 30, 'joe': 40}
You forgot to set the names and percentages as empty dictionaries so you can use them. Also the "return" should be outside of the for loop.:
def GetInput():
names={}
percentages={}
for counter in range(0,10):
names[counter] = input("Please enter the student's name: ")
valid = False
while valid == False:
percentages[counter] = int(input("Please enter the student's score %: "))
if percentages[counter] < 0 or percentages[counter] > 100:
print("Please enter a valid % [0-100]")
else:
valid = True
return names, percentages
name, mark = GetInput()
Probably this may help to you.
#function to ask user to input name and score
def GetInput():
names=[]
percentages=[]
for counter in range(0,3):
names.append(input("Please enter the student's name: "))
valid = False
while valid == False:
percentages.append(int(input("Please enter the student's score %: ")))
if percentages[counter] < 0 or percentages[counter] > 100:
print("Please enter a valid % [0-100]")
else:
valid = True
return names, percentages
name, mark = GetInput()
print(name,mark)
This is implemented by using two lists. (Not suggested for keeping records. Better use dictionary as done below.)
counter = 10
def GetInput():
names = []
percentage = []
for i in range(counter):
names.append(input("Please enter the student's name: "))
valid = False
while not(valid):
try:
percent = int(input("Please enter the student's score between 0 and 100%: "))
if percent >= 0 and percent <= 100:
percentage.append(percent)
valid = True
break
else:
continue
except ValueError:
print("\nEnter valid marks!!!")
continue
valid = True
return names, percentage
students, marks = GetInput()
The following is implemented by using dictionary, and for this, you do not need the variable counter.
def GetInput():
records = dict()
for i in range(counter):
name = input("Please enter the student's name: ")
valid = False
while not(valid):
try:
percent = int(input("Please enter the student's score between 0 and 100%: "))
if percent >= 0 and percent <= 100:
#percentage.append(percent)
valid = True
break
else:
continue
except ValueError:
print("\nEnter valid marks!!!")
continue
valid = True
records[name] = percent
return records
record = GetInput()
Change the value of counter to how many records you want. This takes care of marks to be between 0 and 100 (included) and to be integer. Its better if you implement it with dictionary.
Wouldn't it be better to have name and percentage in one dict?
#function to ask user to input name and score
def GetInput():
name_percentage = {}
for counter in range(0,10):
name = input("Please enter the student's name: ")
valid = False
while not valid:
percentage = int(input("Please enter the student's score %: "))
if percentage < 0 or percentage > 100:
print("Please enter a valid % [0-100]")
else:
valid = True
name_percentage[name] = percentage
return name_percentage
name_percentage = GetInput()
print(name_percentage)

Finding A Collective Average & Letter Grade For Tests & Assignments

I am using Python 3.4.1 and I am trying to write a code that does the following:
class Student(object):
def __init__(self, name):
self.name, self.grades = name, []
def append_grade(self, grade):
self.grades.append(grade)
def average(self):
return sum(self.grades) / len(self.grades)
def letter_grade(self):
average = self.average()
for value, grade in (90, "A"), (80, "B"), (70, "C"), (60, "D"):
if average >= value:
return grade
else:
return "F"
def main():
print()
a_class = [] # "class" by itself is a reserved word in Python, avoid using
while True:
print()
print('{} students in class so far'.format(len(a_class)))
another_student = input('Do you have another student to enter (y/n) ? ')
if another_student[0].lower() != 'y':
break
print()
student_name = input('What is the student\'s ID? ')
a_class.append(Student(student_name))
print()
print('student :', student_name)
print('------------------------------------------------')
number_of_tests = int(input('Please enter the number of tests : '))
for test_num in range(1, number_of_tests+1):
print('test grade {}'.format(test_num), end='')
score = float(input(' : '))
if score < 0: # stop early?
break
number_of_assignments = int(input('Please enter the number of assignments : '))
for assignment_num in range(1, number_of_assignments+1):
print('assignment grade {}'.format(assignment_num), end='')
score2 = float(input(' : '))
if score2 < 0: # stop early?
break
number_of_participation = int(input('Please enter 1 to add participation grade : '))
for participation_num in range(1, number_of_participation+1):
print('participation grade {}'.format(participation_num), end='')
score3 = float(input(' : '))
if score3 < 0: # stop early?
break
a_class[-1].append_grade(score + score2 + score3) # append to last student added
print_report(a_class)
def print_report(a_class):
print()
print('Student Grades')
print()
for student in sorted(a_class, key=lambda s: s.name):
print('student: {:20s} average test score: {:3.2f} grade: {}'.format(
student.name, student.average(), student.letter_grade()))
print()
print('The class average is {:.2f}'.format(class_average(a_class)))
def class_average(a_class):
return sum(student.average() for student in a_class) / len(a_class)
main()
The task here is to get the letter grade of a student by adding 3 different things and getting the average. I need to be able to input the test scores, assignment scores, and 1 participation grade. Those need to average out and give me a final letter grade. I was able to find out how to do just one set of scores to average but when I added the other scores, the average is wrong. What can I edit here?
I didn't look in great detail, but this:
a_class[-1].append_grade(score + score2 + score3)
...makes me suspect that you are adding a single value to the list of grades, that is above 100%. That might account for your averages being too high.
Instead, you likely should:
a_class[-1].append_grade(score)
a_class[-1].append_grade(score2)
a_class[-1].append_grade(score3)

Categories

Resources