#๐Ÿ”’ Very Basic Practice Problems

203 messages ยท Page 1 of 1 (latest)

ashen apex
#

Hi there, I have just completed some very basic python practice problems from my prof and I was looking for some advice on them/things I can improve. Please don't mention something too complicated that a beginner programmer wouldn't have learned yet though : )

round eagleBOT
#

@ashen apex

Python help channel opened

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.

unborn seal
#

...

ashen apex
#
  1. 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

old rampart
#

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?

ashen apex
#

It wasn't really for any purpose

old rampart
ashen apex
#

There are a few more!

unborn seal
#

if you want to be cute -- and arguably easier to understand -- you can write ```py
if 1 <= num_input <= 100:

harsh root
#

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)

hollow mauve
ashen apex
#

lol

ashen apex
hollow mauve
ashen apex
#

wait sorry my indentation is messed up

ashen apex
# hollow mauve You should early return in the except block
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

hollow mauve
#

This will throw a variable unbound error if you don't early return

ashen apex
#

It's just printing

ashen apex
#

    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?

idle patio
#

you can do 1 <= num_input <= 100

wooden gorge
#

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

ashen apex
ashen apex
# idle patio you can do 1 <= num_input <= 100
 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?

idle patio
#

maybe try to specify your error

#

other than that i think it's fine

ashen apex
idle patio
ashen apex
# idle patio Yes

Thank you. Would you be okay to check over the other ones as well?

ashen apex
#
  1. 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

idle patio
#

one moment

ashen apex
#

No problem!

idle patio
ashen apex
#

Thanks for the help with the logic

idle patio
#

it checks if the code is inside a module

ashen apex
#

Ohh okay!

#

Is it just a better way to write it rather than what I had?

#

to test the function

idle patio
#

Yes that's how it's typically written

ashen apex
ashen apex
idle patio
#

and what is the specific message

#

when you hover over it

ashen apex
#

oops

old rampart
#

Honestly looks like she removed the main function

#

Yes

ashen apex
#

Sorry that was silly. Is this correct?

idle patio
#

oh okay

#

yea that looks good

ashen apex
#

Thank you!

ashen apex
idle patio
#

i'll respond if i can

ashen apex
#
  1. 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()
idle patio
#

like before

#

aside from that it's fine

ashen apex
#

ohh yup yup thanks!

#
  1. 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?

idle patio
#

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

wraith marsh
#

shouldnt you also check if b-a is 6? or am i wrong

ashen apex
wraith marsh
#

yea

ashen apex
#

What does that do?

#

does it just subtract in both ways

#

?

idle patio
#

it's for the difference part of the formula

ashen apex
#

I just mean like the abs

idle patio
#

abs is the absolute value function

#

you know |x|

ashen apex
#

Oh yup yup

#

so always positive

idle patio
#

yea so it checks both ways like @wraith marsh mentioned

ashen apex
#

Okie thanks! Does it also work to say abs(a-b) or no?

wraith marsh
#

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?

idle patio
#
>>> abs(1 - 7)
6
>>> abs(7 - 1)
6
>>>
#

@ashen apex sorry

wraith marsh
#

i think we got a little of track xD

idle patio
#

there we go

ashen apex
#

No worries thank you!

#

Here is the next one:

  1. 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

wraith marsh
#

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

ashen apex
#

No?

#

I did actually check that

#

but not sure if this is what you mean

wraith marsh
#

yeah your code says B because you cut at .0 but the task says 79.999. kinda dumb question sry xD

ashen apex
# idle patio

So did you just take away the else and put the return 'F' outside?

#

Yeah it's not necessary

idle patio
#

Yea

wraith marsh
#

yeah you dont need it

ashen apex
#

Okie thank you

idle patio
#

i think you're doing well with these

#

you aren't really encountering any errors it's just like

#

semantics stuff

ashen apex
#

yeahh true

wraith marsh
#
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

wraith marsh
#

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)

round eagleBOT
#

@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
ashen apex
#

Okie cool thanks!

#

There is just one more that I need to ask about : )

#
  1. 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

wraith marsh
#

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

#
  1. 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?

ashen apex
#

Okie ty!

wraith marsh
#

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

ashen apex
#

I will change the if to elif that makes sense!

wraith marsh
ashen apex
wraith marsh
#

but yeah its just my opinion that it looks nicer

ashen apex
#

Yeah I agree

wraith marsh
#

was that the last exercise?

ashen apex
# wraith marsh you can still put that inner if also in the outer with an `and` but again just m...

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

ashen apex
wraith marsh
#

ah you dont catch false input i see just now e.g. if someone inputs A instead of Y or N

ashen apex
#

I just didn't know the best way to implement it

idle patio
wraith marsh
ashen apex
#

so can I just overwrite it?

#

or do I have to make a new variable name?

wraith marsh
#

you overwrite before you check the ifs

ashen apex
#

mhm so like course_1 = course_1.lower()

#

?

idle patio
#
- course_1.lower()
+ course_1 = course_1.lower()```
#

Yes

wraith marsh
#

or just do input().lower()? does that work?

ashen apex
ashen apex
idle patio
#

ye that's fine too

#

but might make the lines a lil long

ashen apex
#

That is the difference in the line length

wraith marsh
#

yeah not that long

ashen apex
#

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

#

?

idle patio
#

course_1 = course_1 == 'y'

wraith marsh
#

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

ashen apex
#

oh wait yeah I didn't handle the exceptions

wraith marsh
#

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

ashen apex
#

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

wraith marsh
#

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 ๐Ÿ™‚

ashen apex
round eagleBOT
#
Python help channel closed

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.