Python input, ifstatement, return - if-statement

I have to create a function that takes an input, and returns a corresponding Grade.
So for example if the user inputs A+ output is 90%
or
if the input is A output is 80%
or
if the input is B output is 70%
I have some sort of Idea on how to do this... but I am having trouble on wrapping my head around on how I can return the statement??
def percent (percentage):
if ( percentage )== A+
return ("90%")
elif (percentage)== A
return ("80%")
Is this the correct way of going about it?

OK, so first, welcome to Python. Second, this is Pythonic way of doing this - define a dict:
grades = {'A+': "90%", 'A': "80%", ...}
then
return grades[precentage]
will do the job.
You need to protect against the case where the grade is not in the dict, for example, if the user entered some mistake, like G. There are a few ways to go about that:
A simple if:
if precentage in grades:
return grades[precentage]
else:
return "bad precentage"
After you get used to Python you will be more aesthetic about your code and will want to do better than state twice bote grades and precentage, so you can do simply:
return grades.get(precentage, "bad precentage")
Or using a special dict with default values:
import collections
grades = collections.defaultdict(lambda: "bad precentage", [("A+", "90%"), ("A", "80%")])
then
grades[precentage]
will automatically return "bad precentage" upon bad input.

#user2829744 You don't want to have to repeatedly call if statements based on what the percentage is, that would make the code unnecessarily long.
Instead, you want to have a list or tuple (a variable which stores multiple elements) that the program can compare the user's inputted value to, and then calculate the percentage mark.
Take this for example:
def percentage(per):
grades=["A+","A","B","C","D","E","F"]
percentage=("90%","80%","70%","60%","50%","40%","30%")
for i in range(7):
if per.upper()==grades[i]:
return percentage[i]
d="a"
print(percentage(d))
What happens is that i counts up to the number seven, and if the value of i in grades (let's say i is 5, then that would be grades[5] which would be an "E") then the function returns the value of i in the percentage tuple. In my case, the interpreter outputs 80%
Logically, your way of going about it (by actually dealing with every grade possible in separate if statements) would work too, however like I said your code would be longer and chances are you'd make a few typos along the way that you'd have to edit. Of course, my code has a few problems too, like what if the user enters a grade which I don't have in the tuple. This is easily fixable though as you would just need to tell the interpreter what to do if that happens.
A bit brief I know, but I hope this helps

You could do something like this
user_input = int(input("percentage: ")
if user_input < 0 and user_input > 10:
print('F")
And then you can just duplicate the code and change the numbers and the return grade
Hope it helps :)

Related

how to use a conditional statement to stop a code with several inputs?

I wrote a code and want to end it after the first input is equal to "done".
If I write the condition after all of the inputs, the user should answer all the useless questions.
On the other hand, I don't want to write the condition in the middle of the inputs as you see in the following part.
I would appreciate it if anyone could help me with this.
Here is the code:
while True:
ind1=input('please enter your personal number:')
if ind1=='done':
break
ind2=input('please enter your name:')
ind3=input('please enter your family name:')
ind4=int(input('please enter your working hours:'))
ind5=int(input('please enter your payment:'))
Instead of using multiple variables, use an array.
pseudo code:
inputs = []
count = 0
while true:
if inputs[count] == 'done': break
inputs[count] = input('...')
count++

Assign nested function to variable with parameter

disclaimer: My title may not be accurate as far as what I would like to accomplish, but I can update if someone can correct my terminology
I have 2 functions, each with a separate purpose and usable on its own, but occasionally I would like to combine the two to perform both actions at once and return a single result, and to do this I would like to assign to a variable name
I know I can create a 3rd function that does basically what I want as it is really simple.. though it's become a bit of a challenge to myself to find a way of doing this
def str2bool(string):
return string.lower() in ("yes", "true", "t", "1")
def get_setting(string):
if string == 'cat':
return 'yes'
else:
return 'no'
VALID_BOOL = str2bool(get_setting)
print VALID_BOOL('cat')
So basically I would like to assign the combination of the 2 functions to a variable that I can call and pass in the string parameter to evaluate
In my real world code, get_setting() would retrieve a user setting and return the value, I would then like to test that value and return it as a boolean
Again I know I can just create a 3rd function that would get the value and do the quick test.. but this is more for learning to see if it can be done as I'm trying to do.. and so far my different variations of assigning and calling aren't working, is it even possible or would it turn too complex?
Using lambda is easy, but i don't know if it is exactly what you are looking for.
Example:
f = lambda astring : str2bool(get_setting(astring))
Outputs:
>>> f('cat')
True

Using for loop within if statements in Python

I am really having a hard time with loop statements for python, please see below:
I want it to check the users age, so if they are over 18, it will say "old enough, if they are over 16, it will say "almost there" and if they are younger than this, it will say "sorry you're too young"
I got the following code below:
age = int(raw_input("Enter your age:"))
if age >= 18:
print "You are old enough!"
elif age >= 16:
print "Almost there"
else:
print "You're just too young"
my problem is, how do I write code the includes an if statement and a for loop that will print out all the numbers from 0 that are less than the user's inputted age?
do I say:
for age in range (0,num)
if num <= age
print ....
else:
print...
Please kindly help. I'm new at this and still learning :(
So you could construct a variable that contains a list of numbers that is smaller than the user's age. You can construct this using python's range function; something like range(age) would do this nicely.
Then you need to use a for loop to loop through all these numbers and print them to the command line. Something like for x in range(age) would be a good place to start.
Then, in the loop, you'd just need to turn x from an integer into a string using the str() function, and print it to the command line.
So as pseudo-code:
if the age is greater than 18:
print that they're old enough
else if the age is greater than 16:
print that they're nearly old enough
otherwise:
print that they're not old enough.
for each number between 0 and age:
print the number
Come back when you have some code and we can help you with any trouble you have.

How to create multiple loops in python

I'm trying to create a basic maths program which will randomly generate a numerical question and then allows 3 attempts to complete it before it moves onto the next question however cant figure out how to make it do both together.
My code currently looks like this
print "What is your name?"
score = 0
Attempt = 0
loop = True
Name = raw_input()
import random
for i in range (1,6):
question_1_part_1 = random.randint(1,30)
question_1_part_2 = random.randint(1,30)
print "What is", question_1_part_1, "+", question_1_part_2, "?"
while Attempt <3: # inputing this while loop here means it will retry the same question.
Guess = raw_input()
Guess = int(Guess)
answer = question_1_part_1 + question_1_part_2
if Guess == answer:
print "Well done"
score = score + 1
else: print "try again"
Attempt = Attempt + 1
if Attempt == 3: print "You failed"
print Name, "your score is", score
A simple break statement will take you out of the loop when the answer is correct.
if Guess == answer:
print "Well done"
score += 1
break
else: print "try again"
Note the change to your assignment; this is considered a cleaner increment.
To answer your comment ... you don't use this when the person gets the question wrong. Your program logic freezes out the user after three wrong guesses total, on all questions. If you want them to have up to three guesses on every problem, then you have to reset the Attempt counter for every question. Pull that line into the outer loop:
for i in range (1,6):
Attempt = 0
loop = True
question_1_part_1 = random.randint(1,30)
question_1_part_2 = random.randint(1,30)
In the future, I strongly recommend that you program incrementally: get a few lines working before you add more. Insert tracing print statements to check that the values and program flow are correct. Don't remove them until that part of the code is solid -- and even then only comment them out until the entire program is working. Some of your problems stem from trying to write more than you can comfortably hold in your mind at once -- which is common at most levels of programming. :-)
Add another argument to your while loop.
while Attempt <3 and Guess != ... :
rest of loop code
Then you are exiting your loop when they get the correct answer. Or you could break from the statement when they get the answer right.

Python number averages using lists and keys

I'm working on a Python assignment and I'm totally stuck. Any assistance would be greatly appreciated. I know it's probably not as convoluted as it seems in my head... The details are below. Thanks very much.
Implement the following three functions (you should use an appropriate looping construct to compute the averages):
allNumAvg(numList) : takes a list of numbers and returns the average of all the numbers in the list.
posNumAvg(numList) : takes a list of numbers and returns the average of all the numbers in the list that are greater than zero.
nonPosAvg(numList) : takes a list of numbers and returns the average of all the numbers in the list that are less than or equal to zero.
Write a program that asks the user to enter some numbers (positives, negatives and zeros). Your program should NOT ask the user to enter a fixed number of numbers. Also it should NOT ask for the number of numbers the user wants to enter. But rather it should ask the user to enter a few numbers and end with -9999 (a sentinel value). The user can enter the numbers in any order. Your program should NOT ask the user to enter the positive and the negative numbers separately.
Your program then should create a list with the numbers entered (make sure NOT to include the sentinel value (-9999) in this list) and output the list and a dictionary with the following Key-Value pairs (using the input list and the above functions):
Key = 'AvgPositive' : Value = the average of all the positive numbers
Key = 'AvgNonPos' : Value = the average of all the non-positive numbers
Key = 'AvgAllNum' : Value = the average of all the numbers
Sample run:
Enter a number (-9999 to end): 4
Enter a number (-9999 to end): -3
Enter a number (-9999 to end): -15
Enter a number (-9999 to end): 0
Enter a number (-9999 to end): 10
Enter a number (-9999 to end): 22
Enter a number (-9999 to end): -9999
The list of all numbers entered is:
[4, -3, -15, 0, 10, 22]
The dictionary with averages is:
{'AvgPositive': 12.0, 'AvgNonPos': -6.0, 'AvgAllNum': 3.0}
EDIT: This is what I have so far, which I did pretty quick just to have a something to work with but I can't figure out how to implement the keys/dictionary like the assignment asks. Thanks again for any help.
print("This program takes user-given numbers and calculates the average")
counter = 0
sum_of_numbers = 0
first_question = int(input('Please enter a number. (Enter -9999 to end):'))
while first_question != -9999 :
ent_num = int(input('Please enter a number. (Enter -9999 to end):'))
sum_of_numbers = sum_of_numbers + ent_num
counter = counter + 1
first_question = int(input('Please enter a number (Enter -9999 to end):'))
print("Your average is " + str(sum_of_numbers/counter))
Welcome to Python programming, and programming in general!
From your code, I assume you are not entirely familiar with Python lists, dictionaries, and functions and how to use them. I'd suggest you look up tutorials for these; knowing how to use them will make your assignment much easier.
Here are some tutorials I found with some quick searches that might help:
Dictionary Tutorial,
List Tutorial,
Function Tutorial
When your assignment says to make three functions, you should probably make actual functions rather than trying to fit the functionality into your loop. For example, here is a simple function that takes in a number and adds 5 to it, then returns it:
def addFive(number):
return number + 5
To use it in your code, you would have something like this:
num = 6 # num is now 6
num = addFive(num) # num is now 11
So what you should do is create a list object containing all the numbers the user entered, and then pass that object into three separate functions - posNumAvg, nonPosAvg, allNumAvg.
Creating a dictionary of key-value pairs is pretty easy - first create the dictionary, then fill it with the appropriate values. For example, here is how I would create a dictionary like {'Hello': 'World'}
values = {}
values['Hello'] = 'World'
print(values) # Will print out {'Hello': 'World'}
So all you need to do is for each of the three values you need, assign the result of the function call to the appropriate key.
If this doesn't feel like quite enough for you to figure out this assignment, read the tutorials again and play with lists, dictionarys, and functions to try and get a feel for them. Good luck!
P.S. The append method of lists will be helpful to you. Try to figure out how to use it!