#๐ Very Basic Practice Problems
203 messages ยท Page 1 of 1 (latest)
@ashen apex
Remember to:
- Ask your Python question, not if you can ask or if there's an expert who can help.
- Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
- Explain what you expect to happen and what actually happens.
:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.
...
- Write a program that determines whether a given value (entered by the user) is between the numbers 1 and 100. Print "Your number is between the given values" if the number is between 1 and 100. If it is not, print "Sorry, your number is out of range". What values will you use to test your program to ensure that it works?
That is first question
Here is my function:
def determine_range():
"""
This function determines whether numbers entered by the user
are betweeen 1 and 100
Parameters: None
Return Value: None
"""
try:
#ask user to enter a number
num_input = int(input("Enter a number: "))
#check if number entered is between 1-100
if num_input >= 1 and num_input <= 100:
print("Your number is between the given values")
else:
print("Sorry your number is out of range")
except ValueError:
print("Invalid Input.")
def main():
determine_range()
main()
I am trying to get into the habit of doing everything in a function
I think that with the functions and try except is well done but why do you have a function main that instantly just redirects to function determine_range?
Oh that's just how I structured it to practice my function skills
It wasn't really for any purpose

There are a few more!
if you want to be cute -- and arguably easier to understand -- you can write ```py
if 1 <= num_input <= 100:
The function above is very close to what ChatGPT generates for the problem, btw.
Have you written this yourself or used AI? (not judging, just curious what skill level you're at)
It's generally best practice to constrain the amount of code in the try block. In your case:
num_input = int(input("Enter a number: "))
Is the only line that can throw an error, so that should be the only line inside the try block
okie thank you!
Nope What would be the point of doing the questions if I just put them into chat gpt xD
lol
try:
#ask user to enter a number
num_input = int(input("Enter a number: "))
except ValueError:
print("Invalid Input.")
#check if number entered is between 1-100
if num_input >= 1 and num_input <= 100:
print("Your number is between the given values")
else:
print("Sorry your number is out of range")
You should early return in the except block
wait sorry my indentation is messed up
try:
#ask user to enter a number
num_input = int(input("Enter a number: "))
except ValueError:
print("Invalid Input.")
#check if number entered is between 1-100
if num_input >= 1 and num_input <= 100:
print("Your number is between the given values")
else:
print("Sorry your number is out of range")
hmm
This will throw a variable unbound error if you don't early return
Oh there is no return
It's just printing
Yeah I get what you are saying here. I added a return {} in the except block
try:
#ask user to enter a number
num_input = int(input("Enter a number: "))
except:
print("Invalid Input.")
return {}
#check if number entered is between 1-100
if num_input >= 1 and num_input <= 100:
print("Your number is between the given values")
else:
print("Sorry your number is out of range")
How's this?
you can do 1 <= num_input <= 100
I would return None instead of {} and what end it all said just to make it more clear for other readers of the code, its nice to practice that
Alright will do that thank you!
try:
#ask user to enter a number
num_input = int(input("Enter a number: "))
except:
print("Invalid Input.")
return None
#check if number entered is between 1-100
if 1 <= num_input <= 100:
print("Your number is between the given values")
else:
print("Sorry your number is out of range")
How does this look?
looks fine to me, but catchall except: is almost never what you want
maybe try to specify your error
other than that i think it's fine
okay thank you! Is it a ValueError?
Yes
Thank you. Would you be okay to check over the other ones as well?
thanks!
- When squirrels get together for a party, they like to have cigars. A squirrel party is successful when the number of cigars is between 40 and 60, inclusive. Unless it is the weekend, in which case there is no upper bound on the number of cigars. Prompt the user to enter the number of cigars and the day of the week. Print "Party On" if the party with the given values is successful, "Lame" otherwise
My function:
def squirrel_party():
"""
This function determines whether a squirrel party is successful
Parameter: None
Return Value: None
"""
try:
#ask user to enter the number of cigars
num_cigars = int(input("Enter the number of cigars for the squirrel party: "))
except ValueError:
print("Invalid Input")
return None
#ask user to enter the day of the week
day_week = input("Enter the day of the week (Sun/Mon/Tues/Wed/Thurs/Fri/Sat): ")
day_week = day_week.lower()
#check if the day of the week is saturday or sunday
if day_week == "sun" or day_week == "sat":
#if day of the week is saturday or sunday, there is no upper bound
if num_cigars >= 40:
print("Party On")
else:
print("Lame")
#check bounds for other days of the week
elif 40 <= num_cigars <= 60:
print("Party On")
else:
print("Lame")
def main():
squirrel_party()
main()
Once again I just called at the bottom there to make sure I understand functions, even if it is not necessary
should I move the except and return none
?
I edited the function up there
one moment
No problem!
yea it's good, i'd probably just write the logic like this tho
if day_week == "sun" or day_week == "sat" and num_cigars >= 40:
print("Party On")
elif 40 <= num_cigars <= 60:
print("Party On")
else:
print("Lame")
And, the standard way to call the main function, is by doing:
if __name__ == "__main__":
main()
I'm not really sure if that concerns you right now but it's good practice.
Ohh I did actually learn that call to main but I never really understood it's purpose
Thanks for the help with the logic
it's so that other modules can import functions from your file without it running the main function
it checks if the code is inside a module
Ohh okay!
Is it just a better way to write it rather than what I had?
to test the function
Yes that's how it's typically written
Great thank you!
It seems to be doing this an I am not sure why
can you share a full screenshot?
and what is the specific message
when you hover over it
Wait is it because I deleted the main function by accident
oops
Thank you!
I have 4 more functions if you don't mind!
feel free to send them here
i'll respond if i can
- You are driving a little too fast, and a police officer stops you. Write code to compute the result, encoded as an int value: 0=no ticket, 1=small ticket, 2=big ticket. If speed is 60 or less, the result is 0. If speed is between 61 and 80 inclusive, the result is 1. If speed is 81 or more, the result is 2. You will need to have the user input the speed on the radar. Write this both using if/elif and a nested conditional.
def result_speeding():
"""
This function computes the result of user's speed on the road
Parameter: None
Return Value: Int - 0 (no ticket)
Int - 1 (small ticket)
Int - 2 (big ticket)
"""
try:
#ask user to input their speed
driver_speed = int(input("Enter your speed: "))
except ValueError:
print("Invalid Input")
#determine result based on speed
if driver_speed <= 60:
return 0
elif 61 <= driver_speed <= 80:
return 1
else:
return 2
def main():
print(result_speeding())
if __name__ == "__main__":
main()
add a return None to the end of your except clause
like before
aside from that it's fine
ohh yup yup thanks!
- The number 6 is a truly great number. Given two integer values, a and b, print "True" if either one is 6. Or if their sum or difference is 6.
Here is my function:
def is_num_six(a, b):
"""
This function checks if either of the entered integers are 6 or if the
sum of their difference is 6
Parameters: Int - a
Int - b
Return Value: True - if a or b is 6 or sum of their differences is 6
False - if conditions above are not true
"""
#check if the integers meeet the conditions
if a == 6 or b == 6 or a + b == 6 or a - b == 6:
return True
else:
return False
def main():
try:
#ask user to enter a number for a and b
a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
print(is_num_six(a, b))
except ValueError:
print("Invalid Input")
if __name__ == "__main__":
main()
For this one I put my try and except with the inputs in the main. What is usually proper practice to put the inputs in main or within the function?
Since this question asks you to define a function which takes two integers as input, I'd say it's more correct to get the input from the main function, so you are right about that
but i'd move this line print(is_num_six(a, b)) outside of the try clause (like before)
since we are not expecting an ValueError here
Also, the else: line inside your function is useless
Ohh yes thanks
shouldnt you also check if b-a is 6? or am i wrong
Mhm makes sense
yea
it's for the difference part of the formula
yea so it checks both ways like @wraith marsh mentioned
Okie thanks! Does it also work to say abs(a-b) or no?
no now you check if its 6 or -6
not if either ways are 6
ah no wait
abs(a) - abs(b) doesnt work for both ways in one go
e.g. 7 and 1
you would get -6 once
ah nvm
abs(abs(a) - abs(b)) should do it?
i think we got a little of track xD
there we go
No worries thank you!
Here is the next one:
- Write a program that outputs the letter grade for an assignment given the numeric grade. The following grade scheme should be followed: A - 80 to 100, B - 65 to 79.999, C - 50 - 64.999, F otherwise. Write this both using if/elif/else and a nested conditional statement.
Here is my function:
def convert_num_to_letter(num_grade):
"""
This function takes a numeric grade for an assignment and
converts it to a letter grade
Parameter: Float - numeric grade
Return Value: String - letter grade
"""
#convert numeric grade to letter grade
if 80 <= num_grade <= 100:
return "A"
elif 65 <= num_grade < 80:
return "B"
elif 50 <= num_grade < 65 :
return "C"
else:
return "F"
def main():
#ask user for grade
try:
grade = float(input("Enter the assignment grade: "))
except ValueError:
print("Invalid input")
print(convert_num_to_letter(grade))
if __name__ == "__main__":
main()
Yeah I wasn't sure where to put the input for this one
that's the only thing, I think
if abs(abs(a - b) - 6) == 0 i think thats a solution for only one statement but i guess if you use 2 its more readable for the exercise before
just a question about the task what should happen if you input 79.9999? its bigger than the highest for B but smaller than the 80 for A
It's B
No?
I did actually check that
but not sure if this is what you mean
yeah your code says B because you cut at .0 but the task says 79.999. kinda dumb question sry xD
So did you just take away the else and put the return 'F' outside?
Yeah it's not necessary
Yea
yeah you dont need it
Okie thank you
i think you're doing well with these
you aren't really encountering any errors it's just like
semantics stuff
yeahh true
if statement:
return 1
else:
return 0
you never need the else because if the statement is True then you return your stuff in the if and if statement is False you dont need to check else, just execute the remaining code which would have been inside the else part
Yeah makes sense thanks!
np ๐
!e
def divide_else_finally(a, b):
try:
print(a / b)
except ZeroDivisionError as e:
print('catch ZeroDivisionError:', e)
else:
print('finish (no error)')
finally:
print('all finish')
divide_else_finally(1, 2)
divide_else_finally(1, 0)
if you want to try out more stuff with exceptions you can also use else and finally
-else is called if no exception is raised
-finally is called all the times at the end (doesnt matter if there was an exception or not)
@wraith marsh :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 0.5
002 | finish (no error)
003 | all finish
004 | catch ZeroDivisionError: division by zero
005 | all finish
Okie cool thanks!
There is just one more that I need to ask about : )
- Ask the user whether or not they have taken the following courses and store each response as a boolean variable using the course (eg. course_1) as the variable name. "Yes" responses are stored as True, "No" responses stored as False.
Check to see if a student has taken course_1, course_2 but not course_3 - if so, tell them that their next course must be course_3.
Here is my function:
def courses_taken():
"""
This function asks the user whether or not they have taken 3 courses
and stores each response as a boolean variable.
Parameters: None
Return Value: None
"""
#ask user if they have taken course 1
course_1 = input("Have you taken course_1 (Y/N)?: ")
if course_1 == "Y" or course_1 == "y":
course_1 = True
if course_1 == "N" or course_1 == "n":
course_1 = False
#ask user if they have taken course 2
course_2 = input("Have you taken course_2 (Y/N)?: ")
if course_2 == "Y" or course_2 == "y":
course_2 = True
if course_2 == "N" or course_2 == "n":
course_2 = False
#ask user if they have taken course 3
course_3 = input("Have you taken course_3 (Y/N)?: ")
if course_3 == "Y" or course_3 == "y":
course_3 = True
if course_3 == "N" or course_3 == "n":
course_3 = False
if course_1 == True:
if course_2 == True:
if course_3 == False:
print("The next course you must take is course 3")
def main():
courses_taken()
if __name__ == "__main__":
main()
Hmm why is it all italicized
discord makes stuff bold if you put it between two * italic for _
so *a* makes an a and _a_ and a
you can put \ in front to escape the characters
\ _ like this but without the whitespace between
- Ask the user whether or not they have taken the following courses and store each response as a boolean variable using the course (eg. course_1) as the variable name. "Yes" responses are stored as True, "No" responses stored as False.
Check to see if a student has taken course_1, course_2 but not course_3 - if so, tell them that their next course must be course_3.
Here is my function:
def courses_taken():
"""
This function asks the user whether or not they have taken 3 courses
and stores each response as a boolean variable.
Parameters: None
Return Value: None
"""
#ask user if they have taken course 1
course_1 = input("Have you taken course_1 (Y/N)?: ")
if course_1 == "Y" or course_1 == "y":
course_1 = True
if course_1 == "N" or course_1 == "n":
course_1 = False
#ask user if they have taken course 2
course_2 = input("Have you taken course_2 (Y/N)?: ")
if course_2 == "Y" or course_2 == "y":
course_2 = True
if course_2 == "N" or course_2 == "n":
course_2 = False
#ask user if they have taken course 3
course_3 = input("Have you taken course_3 (Y/N)?: ")
if course_3 == "Y" or course_3 == "y":
course_3 = True
if course_3 == "N" or course_3 == "n":
course_3 = False
if course_1 == True:
if course_2 == True:
if course_3 == False:
print("The next course you must take is course 3")
def main():
courses_taken()
if __name == "__main":
main()
that should be it?
Okie ty!
one thing you could do is use the .lower() method to only check for y and n instead of two extra for the upper case Y/N and another thing is you could use an elif for the N case because if Y is already true you dont have to check that case anymore
and last point is you dont have use if course_1 == True: you can just write if course_1: because the variable has that boolean value in itself and you dont have to check for it
and you could also just check for if course_1 and course_2 and not course_3: in one line
Mhm yeah I used lower before I just didn't think it would be super necessary for only 2 cases but I can yes!
I will change the if to elif that makes sense!
well you cant really have more cases than 2 xD
if course_1 and course_2:
if course_3 == False:
print("The next course you must take is course 3")
but yeah its just my opinion that it looks nicer
Okie I will fix it thank you!
Yeah I agree
you can still put that inner if also in the outer with an and but again just my opinion because the less indents you have the better, but you shouldnt have too many statements in one if too, so yeah depends on how much stuff you check for
was that the last exercise?
def courses_taken():
"""
This function asks the user whether or not they have taken 3 courses
and stores each response as a boolean variable.
Parameters: None
Return Value: None
"""
#ask user if they have taken course 1
course_1 = input("Have you taken course_1 (Y/N)?: ")
course_1.lower()
if course_1 == "y":
course_1 = True
elif course_1 == "n":
course_1 = False
#ask user if they have taken course 2
course_2 = input("Have you taken course_2 (Y/N)?: ")
course_2.lower()
if course_2 == "y":
course_2 = True
elif course_2 == "n":
course_2 = False
#ask user if they have taken course 3
course_3 = input("Have you taken course_3 (Y/N)?: ")
course_3.lower()
if course_3 == "y":
course_3 = True
elif course_3 == "n":
course_3 = False
if course_1 and course_2 and course_3 == False:
print("The next course you must take is course 3")
def main():
courses_taken()
if __name__ == "__main__":
main()
How's this
Yes last one for today. I have 43 to do but that is too much for all one day so I am doing a little each day to keep it more fresh in my head
ah you dont catch false input i see just now e.g. if someone inputs A instead of Y or N
Yeah I thought about that as well tbh
I just didn't know the best way to implement it
you have to reassign to the courses when you call .lower() on them
ah yes a.lower() returns the lowercase of a
oh but in the problem it says to keep the variables as the names of the course
so can I just overwrite it?
or do I have to make a new variable name?
you overwrite before you check the ifs
or just do input().lower()? does that work?
Okie thanks!
I think i've seen my prof do that before
That is the difference in the line length
yeah not that long
mhm
def courses_taken():
"""
This function asks the user whether or not they have taken 3 courses
and stores each response as a boolean variable.
Parameters: None
Return Value: None
"""
#ask user if they have taken course 1
course_1 = input("Have you taken course_1 (Y/N)?: ").lower()
if course_1 == "y":
course_1 = True
elif course_1 == "n":
course_1 = False
#ask user if they have taken course 2
course_2 = input("Have you taken course_2 (Y/N)?: ").lower()
if course_2 == "y":
course_2 = True
elif course_2 == "n":
course_2 = False
#ask user if they have taken course 3
course_3 = input("Have you taken course_3 (Y/N)?: ").lower()
if course_3 == "y":
course_3 = True
elif course_3 == "n":
course_3 = False
if course_1 and course_2 and course_3 == False:
print("The next course you must take is course 3")
def main():
courses_taken()
if __name__ == "__main__":
main()
I think it is good now right
?
course_1 = course_1 == 'y'
yeah but when you input e.g. a for an input you would get True in the final if for that course because a non empty string is True
oh wait yeah I didn't handle the exceptions
and you didnt assign another value because the ifs didnt trigger
one easy way would be a final else after each elif and set it to False but thats very basic
you would have to check if the input is either y or n
and then would be the question if you repeat and ask again or just end it
would I have to use a while loop somewhere if I wanted to keep reasking? I'd assume so
while course_1 or course_2 or course_3 != "y" or course_1 or course_2 or course_3 != "n"
Not sure
now you only check the last course_3 for "y" or "n" if either course_1 or course_2 are True the while would run forever because they keep the while condition always True
and you could check with if course_1 in ["y", "n"]: if its y or n
course_1 = ""
while not (course_1 in ["y", "n"]):
course_1 = input("Have you taken course_1 (Y/N)?: ").lower()
you could do something like that i think
but i gotta go sleep now sry, hope i could help ๐ if you have any further questions about it or just in general just dm me bye ๐
Oh okay sorry I was eating dinner but I appreciate the help !
maybe we can look at it again tom?
This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.