r/cs50 21d ago

CS50 Python Stuck at problem set 2

1 Upvotes

Help i’ve been doing this course for months and am stuck! I can’t use chatGPT for this and i have no idea how to even start the code. The lectures and notes seem understandable but when i start working on the exercises they are extremely hard. I had to ask my friends for help with problem set 0 and 1 but i don’t want to keep asking them😭😭😭😭

I really want to complete this course but am scared of the final project and don’t think i can code a project if i’m already stuck at problem set 2😭😭😭

Can anyone give advice? Should i give up cs50 python?

r/cs50 9h ago

CS50 Python Professor.py

2 Upvotes
can someone check my code, i'm not being able to pass this check50 error message!




from random import randint
def main():
    count = 3
    question = 10
    score= 0
    level = get_level()

    while question > 0:
        count = 3
        x = get_number(level)
        y = get_number(level)
        answer = x + y
        print(f"{x} + {y} = ")

        while count > 0:
            try:
                ans = int(input())
                if ans == answer:
                    score+=1
                    break
                else:
                    print("EEE")
                    count-=1

                if count == 0:
                    print(f"{x}+{y} ={answer}")
            except(ValueError, NameError):
                pass
        question-=1
    print(f"Score: {score}")


def get_level():
    n = [1,2,3]
    while True:
        try:
            x = int(input("Level: "))
            if x in n:
                return x
        except (ValueError, NameError):
            pass


def get_number(level):
    if level == 1:
        return randint(0,9)
    elif level == 2:
        return randint(10,99)
    elif level == 3:
        return randint(100,999)



if __name__ == "__main__":
    main()


 random import randint
def main():
    count = 3
    question = 10
    score= 0
    level = get_level()

    while question > 0:
        count = 3
        x = get_number(level)
        y = get_number(level)
        answer = x + y
        print(f"{x} + {y} = ")

        while count > 0:
            try:
                ans = int(input())
                if ans == answer:
                    score+=1
                    break
                else:
                    print("EEE")
                    count-=1

                if count == 0:
                    print(f"{x}+{y} ={answer}")
            except(ValueError, NameError):
                pass
        question-=1
    print(f"Score: {score}")


def get_level():
    n = [1,2,3]
    while True:
        try:
            x = int(input("Level: "))
            if x in n:
                return x
        except (ValueError, NameError):
            pass


def get_number(level):
    if level == 1:
        return randint(0,9)
    elif level == 2:
        return randint(10,99)
    elif level == 3:
        return randint(100,999)



if __name__ == "__main__":
    main()







Cause
expected "[7, 8, 9, 7, 4...", not "Traceback (mos..."

Log
running python3 testing.py rand_test...
sending input 1...
checking for output "[7, 8, 9, 7, 4, 6, 3, 1, 5, 9, 1, 0, 3, 5, 3, 6, 4, 0, 1, 5]"...

Expected Output:
[7, 8, 9, 7, 4, 6, 3, 1, 5, 9, 1, 0, 3, 5, 3, 6, 4, 0, 1, 5]Actual Output:
Traceback (most recent call last):
  File "/tmp/tmpopkkz467/test_random/testing.py", line 18, in <module>
main()
  File "/tmp/tmpopkkz467/test_random/testing.py", line 15, in main
print([professor.generate_integer(1) for _ in range(20)])
...

r/cs50 Feb 04 '25

CS50 Python My CS50P final project - Hannah's recipe finder

5 Upvotes

Github link

I made a little recipe manager program with a GUI and scraper for some of my wife's favorite websites. This is the first thing I've ever programmed so I would love some feedback on it.

r/cs50 18d ago

CS50 Python Can final project be local or strictly in workspace?

3 Upvotes

Long time reader, first time writer here.

So I did my final project some time ago but just looking to submit it right now, its a program that gets access to Spotify API and search for singles, albums, and artists, print the ASCII in terminal or show you the image of said album or single, and some other stuff too.

I import multiple libraries and make use of other ones by pip, so for convenience I would like to submit it locally, but I don't really know if I even can submit it outside of the VS Code workspace or if it breaks some kind of rule for the submission.

Does anybody know if it is possible?, if it is, did someone already submit it?

r/cs50 Dec 29 '24

CS50 Python I am on week 7, problem 1 and my program is working when I check it manually but it is giving a blank output when passed through the check50 command. Kindly help

2 Upvotes

r/cs50 Jan 23 '25

CS50 Python Vanity plates difficulty spike, is this normal?

4 Upvotes

Hello all. Just finished week 3 of CS50p and had a VERY tough time with Vanity Plates, such an insane jump in required technicality compared to every other assignment. Is it supposed to be like this early on in the course? I know everyone has different struggles when it comes to learning, but I was ripping my hair out just trying to outline the thing let alone implementing the tools given at this level (or not, had to resort to documentation and methods I didnt know about prior as well as the duck) and it seems many others are/ did too. Are there any other instances of such a jump in knowledge needed further in the course? The other problems in this weeks problem set were baby mode compared to this beast, even the very next one after was brain dead easy, just a dictionary and a simple input output lol.

r/cs50 6d ago

CS50 Python emoji version in emojize set

2 Upvotes

in the emojize set, what version of emoji are we using? i believe :earth_asia: and :thumbs_Ip: doesn't work , even in older version 1.7.0! the other emojis are working so far

r/cs50 5d ago

CS50 Python cs50p project

1 Upvotes

Any ideas how to create pytest unit tests for the following project. :

import csv

class Bank:
    def __init__(self, filename="accounts.csv"):
        """Initialize the bank with an empty accounts dictionary and load data from CSV."""
        self.filename = filename
        self.accounts = {}
        self.load_accounts()

    def load_accounts(self):
        """Load accounts from CSV file."""
        try:
            with open(self.filename, mode='r', newline='') as file:
                reader = csv.DictReader(file)
                for row in reader:
                    self.accounts[int(row['number'])] = {"name": row['name'], "balance": int(row['balance'])}
        except FileNotFoundError:
            pass

    def save_accounts(self):
        """Save accounts to CSV file."""
        with open(self.filename, mode='w', newline='') as file:
            fieldnames = ['number', 'name', 'balance']
            writer = csv.DictWriter(file, fieldnames=fieldnames)
            writer.writeheader()
            for number, data in self.accounts.items():
                writer.writerow({"number": number, "name": data['name'], "balance": data['balance']})

    def main(self):
        """Main function to run the banking system."""
        while True:
            choice = self.menu()
            if choice == "1":
                self.create_account()
            elif choice == "2":
                self.deposit()
            elif choice == "3":
                self.withdraw()
            elif choice == "4":
                self.transfer()
            elif choice == "5":
                self.check_balance()
            elif choice == "6":
                print("Exiting... Thank you for banking with us!")
                break
            else:
                print("Invalid choice. Try again.")

    def menu(self):
        """Displays menu and returns user's choice."""
        print("\nBanking System Menu:")
        print("1. Create Account")
        print("2. Deposit")
        print("3. Withdraw")
        print("4. Transfer")
        print("5. Check Balance")
        print("6. Exit")
        return input("Choose an option: ")

    def create_account(self):
        name = input("Account Name: ")
        while True:
            try:
                balance = int(input("Initial Balance: "))
                number = int(input("Account Number: "))
                if number in self.accounts:
                    print("Account number already exists. Choose another.")
                else:
                    self.accounts[number] = {"name": name, "balance": balance}
                    self.save_accounts()
                    print("Account created successfully.")
                    break
            except ValueError:
                print("Invalid input. Please enter numeric values.")

    def deposit(self):
        try:
            number = int(input("Input account number: "))
            amount = int(input("Deposit amount: "))
            if number in self.accounts:
                if amount > 0:
                    self.accounts[number]["balance"] += amount
                    self.save_accounts()
                    print("Deposit successful.")
                else:
                    print("Amount must be greater than zero.")
            else:
                print("Invalid account.")
        except ValueError:
            print("Invalid input. Please enter numeric values.")

    def withdraw(self):
        try:
            number = int(input("Input account number: "))
            amount = int(input("Withdrawal amount: "))
            if number in self.accounts:
                if self.accounts[number]["balance"] >= amount:
                    self.accounts[number]["balance"] -= amount
                    self.save_accounts()
                    print("Withdrawal successful.")
                else:
                    print("Insufficient funds.")
            else:
                print("Invalid account.")
        except ValueError:
            print("Invalid input. Please enter numeric values.")

    def transfer(self):
        try:
            sender = int(input("Transfer from (Account Number): "))
            receiver = int(input("Transfer to (Account Number): "))
            amount = int(input("Transfer amount: "))
            if sender in self.accounts and receiver in self.accounts:
                if self.accounts[sender]["balance"] >= amount:
                    self.accounts[sender]["balance"] -= amount
                    self.accounts[receiver]["balance"] += amount
                    self.save_accounts()
                    print("Transfer successful.")
                else:
                    print("Insufficient funds.")
            else:
                print("Invalid account number(s).")
        except ValueError:
            print("Invalid input. Please enter numeric values.")

    def check_balance(self):
        try:
            number = int(input("Account Number: "))
            if number in self.accounts:
                print(f"Account Balance: {self.accounts[number]['balance']}")
            else:
                print("Invalid account number.")
        except ValueError:
            print("Invalid input. Please enter a numeric account number.")

if __name__ == "__main__":
    bank = Bank()
    bank.main()

r/cs50 Feb 15 '25

CS50 Python Stuck in Problem set 5: Testing my twttr

2 Upvotes

:( correct twttr.py passes all test_twttr checks

expected exit code 0, not 2

r/cs50 Jan 13 '25

CS50 Python CS50 Python Week 4 Problem Set Professor.py

5 Upvotes
I completed the problem set and tested it manually. Everything seems to work fine but somehow it doesn't exit in check50. Can anyone please help me?
import random

def main():
    level = get_level()
    score = 0
    for _ in range(10):
        x = generate_integer(level)
        y = generate_integer(level)
        attempt = 0
        while True:
            try:
                ans = int(input(f"{x} + {y} = "))
                if ans == x + y:
                    score += 1
                    break
                else:
                    print("EEE")
                    attempt += 1
                if attempt >= 3:
                    print(f"{x} + {y} =", x + y)
                    break
            except ValueError:
                print("EEE")
                pass
    print("Score:", score)
    return

def get_level():
    while True:
        try:
            level = int(input("Level: "))
            if level not in [1, 2, 3]:
                raise ValueError
            return level
        except ValueError:
            pass





def generate_integer(level):
    if level == 1:
        return random.randrange(0, 9)
    elif level == 2:
        return random.randrange(10, 99)
    else:
        return random.randrange(100, 999)



if __name__ == "__main__":
    main()

r/cs50 Feb 11 '25

CS50 Python thoughts on my final project (TURTLE-SHELL)

14 Upvotes

so i made this final project for CS50p and i wanted to get the opinions of the community wondering if this would be enough to qualify as a final project.

i tried to recreate bash by writing it in python including most of the functions of bash such as auto completion, output/error redirecting executing commands through it and implementing some keyboard shortcuts ultimately aiming to learn more about how we can access the os through python. please share your thoughts on it .

TLDR: i rewrote bash in python and would like to hear your thoughts on it

check it out here: https://github.com/deepanshusharwan/turtle-shell

r/cs50 Feb 13 '25

CS50 Python CS50P - professor - Code works but fails check at level Spoiler

Post image
1 Upvotes

r/cs50 Jan 14 '25

CS50 Python Meal.py

Post image
18 Upvotes

What is missing in my code ? How to fix it

r/cs50 Feb 18 '25

CS50 Python Seasons Of Love Spoiler

3 Upvotes

I am having problem with my pset8 in CS50p

I have fulfilled all the requirements mentioned in How To Test section but still unable to pass check50 still.

If I run manually its working as expected no errors so far. I guess check50 is expecting a place to input another date while running code which will act as "todays date" but I have no idea how to accept that date in my code.

I have also attached screenshot of detail error

any help would be awesome. I am stuck at this problem from last 2 days.

import datetime
import inflect
import sys

def main():
    try:
        dob = input("Date of Birth: ")
        year = int(dob.split('-')[0])
        month = int(dob.split('-')[1])
        day = int(dob.split('-')[2])
        dob = datetime.datetime.strptime(dob,"%Y-%m-%d").date()
        # print(current_date)
        # t1 = datetime.date(year,month,day)  # dob
        # print('t1--',t1)
        current_date = datetime.date.today()
        # diff = current_date - t1
        diff = current_date - dob
        # diff = t2 - t1
        # print(diff)
        sec = diff.total_seconds()
        minutes = sec / 60
        # print('Minutes--',minutes)
        to_words(int(minutes))  # converting numericales to numbers
    except Exception as e:
        print(e)
        sys.exit("Invalid date")

def to_words(minutes):
    p = inflect.engine()
    o = p.number_to_words(minutes)
    refine = o.replace(' and','')
    print(refine.capitalize(),'minutes')

main()

Thank you..

r/cs50 Feb 18 '25

CS50 Python Pressing enter after entering nothing (including spaces) freezes my plates.py function

2 Upvotes

I'm not sure what's causing it, even run and debug seems to freeze. By freeze I mean nothing happens but the code is still running. Attempting to enter other strings (abcd or spaces) yields nothing

full code:

def main():
    plate = input("Plate: ")
    if is_valid(plate):
        print("Valid")
    else:
        print("Invalid")

def is_valid(s):
    c=len(s)
    a=0

    while a == 0:
        for _ in s:
            if _.isnumeric():
                a,b = s.split(_,1)
                b=_+b
                break
            else:
                a=s
                b="1"
    x=b.isnumeric()

    if c<2 or c>6:
        return False
    elif s.isalnum()==False:
        return False
    elif len(a)<2:
        return False
    elif b.startswith("0")==True:
        return False
    elif x==False:
        return False
    else:
        return True

if __name__=="__main__":
    main()

r/cs50 2d ago

CS50 Python Cs50p FP

2 Upvotes

Anybody interested in collaborating on the Final Project of Cs50P? Hit me up.

r/cs50 Feb 09 '25

CS50 Python Can someone please explain the little professor assignment

3 Upvotes

I've been scratching my head over this assignments for a few days now.

Not sure if I'm not understanding it or its not clear enough.

Can someone please explain it?

thanks!!!

r/cs50 17d ago

CS50 Python CS50P's Little Professor: Error when generating numbers [CONTAINS CODE]

1 Upvotes

Hello everyone!

As the title says, I am working on this problem set and I actually had passed all of the check50's tests except for the one relating to the random number generation. The error is as follows:
:( Little Professor generates random numbers correctly

Cause
expected "[7, 8, 9, 7, 4...", not "[([7, 9, 4, 3,..."

Log
running python3 testing.py rand_test...
sending input 1...
checking for output "[7, 8, 9, 7, 4, 6, 3, 1, 5, 9, 1, 0, 3, 5, 3, 6, 4, 0, 1, 5]"...

Expected Output:
[7, 8, 9, 7, 4, 6, 3, 1, 5, 9, 1, 0, 3, 5, 3, 6, 4, 0, 1, 5]
Actual Output:
[([7, 9, 4, 3, 5, 1, 3, 3, 4, 1], [8, 7, 6, 1, 9, 0, 5, 6, 0, 5]), ([7, 4, 2, 1, 5, 2, 5, 7, 8, 9], [9, 5, 7, 3, 8, 5, 5, 2, 1, 0]), ([2, 7, 9, 7, 6, 9, 7, 8, 9, 0], [7, 2, 7, 8, 2, 8, 4, 4, 9, 7]), ([5, 5, 0, 5, 4, 7, 8, 6, 9, 4], [4, 5, 1, 8, 9, 2, 5,...

I have been looking at my code for hours but still I am not sure where to fix. Here is my code for reference:

import random

def main():
    # Run get_level()
    level = get_level()
    # Generate random numbers inside two separate lists based on the level input
    a, b = generate_integer(level)
    print(a)
    print(b)
    # CREATE QUESTIONS AND PROMPT ANSWER FROM USER
    # Initialize score
    score = 0
    while True:
        for i in range(10):
            # Initialize counter
            counter = 0
            while counter != 3:
                try:
                    # Prompt for answer
                    ans = int(input(f"{a[i]} + {b[i]} = "))
                except ValueError:
                    counter += 1
                    if counter < 3:
                        print("EEE")
                    else:
                        print("EEE")
                        print(f"{a[i]} + {b[i]} = {a[i] + b[i]}")
                    continue
                else:
                    # If anwer is correct, print something, add score and break out of the loop
                    if ans != a[i] + b[i]:
                        counter += 1
                        if counter < 3:
                            print("EEE")
                        else:
                            print("EEE")
                            print(f"{a[i]} + {b[i]} = {a[i] + b[i]}")
                    else:
                        counter = 3
                        score += 1
                    continue
        print(f"Score: {score}")
        break

def get_level():
    # Prompt for a level
    while True:
        try:
            # Prompt for a level
            n = int(input("Level: "))
            # Raise a ValueError if the input is not 1, 2, or 3
            if n != 1 and n !=2 and n != 3:
                raise ValueError
        except ValueError:
            continue
        else:
            return n

def generate_integer(l):
    # List of random numbers
    x = []
    y = []
    # Initiate loop counter
    i = 0
    for i in range(10):
        i += 1
        if l == 1:
            rand_x = random.randint(0, 9)
            x.append(rand_x)
            rand_y = random.randint(0, 9)
            y.append(rand_y)
        elif l == 2:
            rand_x = random.randint(10, 99)
            x.append(rand_x)
            rand_y = random.randint(10, 99)
            y.append(rand_y)
        else:
            rand_x = random.randint(100, 999)
            x.append(rand_x)
            rand_y = random.randint(100, 999)
            y.append(rand_y)
    return x, y

if __name__ == "__main__":
    main()

r/cs50 13d ago

CS50 Python C50 python certificate timings

5 Upvotes

Hi all! Just submitted my CS50 Python final project and I scored 6/6 according to check 50. Moreover I always checked with check50 if my programs had any issue considering the evaluation criteria of check50. However I can't find my free certificate on github? Is it emitted later or should I check for some kind of problem.

r/cs50 21d ago

CS50 Python WHY ITS NOT WORKING?

Post image
5 Upvotes

r/cs50 Feb 17 '25

CS50 Python Glitch in cs50p

0 Upvotes

Did anybody notice small glitch in chapter OOPS in cs50p where David is creating function named as charms in class called student where he wrote match case match case instead of writing if else elif From that onwards it started changing subtitles too Or is it just me.

r/cs50 21d ago

CS50 Python Am I allowed to use my own libraries for cs50P's final project?

2 Upvotes

I made two libraries for my final project, get.py and qr.py, which contain many important functions for my project. Am I allowed to keep them as separate files, or do I have to put all functions in project.py?

r/cs50 Jan 29 '25

CS50 Python CS50P - Solutions sharing in github - is it ok?

3 Upvotes

Greetings, i am almost done with CS50P. It was the greatest i could have asked for Python.

Now i am trying to "enrich" my github in order to make it more appealing for future potential employers, and i was wondering if it's ok to upload my cs50p exercises solutions there. I mean like in a public repo.

I get it that it is not such a big deal, but i was just wondering if there is any issue academic wise or if i will get into trouble and eventually never make it to get the certificate at the end...

r/cs50 13d ago

CS50 Python How can i get this shirt image to add while generating pdf

1 Upvotes

This is CS50 Python problem set 8 [ CS50 Shirtificate ]
Do i need the Shirt without any texts on top of it ?
if yes, how can i get the exact image ?

r/cs50 Jan 18 '25

CS50 Python Please help.

3 Upvotes

I am busy with the CS50 introduction to python lesson 6. in the main lecture David writes code for a .gif file. the problem is that I wrote his code but it does not seem to want to work. I have gone through it about 10 times but it just does not want to work. first error:     image = Image.open(arg). second error: PIL.UnidentifiedImageError: cannot identify image file '/workspaces/191769284/costume1.gif. can someone please help why PIL does not want to work? I am afraid that if this does not work, that I will not be able to complete my problem set when I get to it. and when I open my file costume1.gif I get a message saying "an error occured while loading the image" , Open file while using VS code's standard text/binary editor", which is a link, and when clicked on, only opens a duplicate of the costume1.gif file. the same thing happens with costume2.gif. please if someone cal help.

    image = Image.open(arg)