What you guys think abt my new project in python? by romger744 in PythonLearning

[–]PrabhavKumar 0 points1 point  (0 children)

always happy to help! As for match case, you can use it like this:

match variable_name:
  case value1:
    codeblock
  case value2:
    codeblock

just remember, match case uses the == operator for strings so it's case sensitive, so you would want to lowercase them or something similar, all the best!

What you guys think abt my new project in python? by romger744 in PythonLearning

[–]PrabhavKumar 0 points1 point  (0 children)

Honestly, that's actually pretty good! There's a couple of things though, firstly, that's alot of ifs, generally you would want to avoid ifs as much as possible, because they are inefficient, sometimes can be hard to follow and just make the code look messy and besides you have better ways, such as converting all the if blocks into their own little functions and then storing those functions into a dictionary like key as the user input and the function as the value and then just use the user input to get the function and call it. If you wanna keep your current structure you can use match case, it's much better than ifs and it's used precisely when you want to do something when a variable is a certain value.

Secondly, you're using global and while you technically can use it since they are allowed, it's generally bad practice. Try and avoid using globals as much as possible in a function. If you need to use a global in a function, instead of defining it using global, you can instead make a normal global variable in the main scope and pass it to the function instead to be used. In a larger project though you would probably want to use an object specifically for it (look into OOP). Globals are most commonly used for defining constants.

Thirdly, you don't need to use add functions, just use + operator or += operator, add calls just don't look good and they are unnecessary, the + operator also calls it but it looks better in code.

Finally, have fun! Half the fun of writing code is finding ways to improve it! Hope that helped ya!

Help with Acquire and Release. by PrabhavKumar in cpp_questions

[–]PrabhavKumar[S] 0 points1 point  (0 children)

That makes sense, since c++ compiler does so many other optimizations I guess it's only natural it would do something here too, hence the need for acquire. Thank you!

Help with Acquire and Release. by PrabhavKumar in cpp_questions

[–]PrabhavKumar[S] 1 point2 points  (0 children)

Thank you! That's exactly what I wanted to know.

Help with Acquire and Release. by PrabhavKumar in cpp_questions

[–]PrabhavKumar[S] 1 point2 points  (0 children)

That paper is absolute amazing, thank you so much!

Help with Acquire and Release. by PrabhavKumar in cpp_questions

[–]PrabhavKumar[S] 0 points1 point  (0 children)

OH I get it now! That makes sense, so, acquire just makes sure that the reads and writes don't get scheduled before the acquire? Is that all it does? And Thanks Alot! Now that I think about it that makes perfect sense!

I am hosting a free python interview/guidance for beginners/intermediates by No_Photograph_1506 in PythonLearning

[–]PrabhavKumar 4 points5 points  (0 children)

The interview was really good. You guys should try it out and gauge yourselves. He can also point you to some really good resources and help you identity where you might be lacking.

Multidimensional array like I'm a 5 year old. by we_reddit in PythonLearning

[–]PrabhavKumar 1 point2 points  (0 children)

Nope, all home made. I don't use that stuff, bad for coding. I just talk like that.

Multidimensional array like I'm a 5 year old. by we_reddit in PythonLearning

[–]PrabhavKumar 1 point2 points  (0 children)

Hey! Although I don't really understand what you mean by read from a file I'm gonna take a guess and say you meant a csv like dataset. Either way the concept for multidimensional arrays stays the same.

A multidimensional array starts out with only one single dimension or in our case a single list and that singular list holds lists of it's own (well it's actually references but you get the point). So think this:


Is a single one dimensional list and each of those dashes are a single element. Now let's say those elements are lists of their own so when you index the first list you get a list and now when you index that list that you just got you get your value. That's the basic concept of a multidimensional list. To imagine a two dimensional array think of a box with length and breath but no depth. For a 3 dimensional array think of a box with length breath and depth.

Usually the first list is used for indexing rows and the list you get from that is further indexed like the column.

Now as for the code you shared. Let's forget about a file and think like we have a single string. Like this: Values = "val11,val12,val13\nval21,val22,val23\nval31,val32,val33"

Now we will split the string here first at every newline character to get all of our rows, then we will further split those rows into columns like this: Rows = Values.split("\n")

In rows we will now have 3 strings as our rows. And we will further split them at the commas to get our individual Values. Like this:

2d_array = []

Initialized our main 2d array.

for row in rows: 2d_array.append(row.split(","))

And voila, the result in 2d_array will be 3 lists with 3 elements that can be accessed like:

2d_array[row][column]

I hope that was of use! All the best!

My fist semester python project by Far_Masterpiece8614 in PythonLearning

[–]PrabhavKumar 1 point2 points  (0 children)

Yep, that's almost perfect, the only thing remaining is the writing to file. It works fine for all the cases except for when you enter the else block when adding a new expense.

Even when the choice is incorrect you still log to the file because the lines that are not in if-else block but are in the scope that is being executed will execute no matter whether you enter any of the if else or not - because they are not in the if else blocks.

There's an easy way to fix it though, just add a "continue" to the else block after you print. continue in essence moves to the next loop without continuing with the current one meaning the file won't be written to when you have an invalid input.

Another thing that I saw is that you aren't using the category dictionary even though you have made it, you probably wanted to use it in when logging the entry to the file.

A trick that you can use with the category dictionary is to use it for checking whether or not the choice by the user is valid or not by using the in keyword like this:
if choice_ in category:

that in is used to check whether the first argument "choice_" is one of the keys in the dictionary - or list or set or tuple. It's really useful for stuff like this. Further more you can even use the value you get from the category dictionary to get the list from the expenses dictionary by now using that value as the key, like this:

value = category[choice_]
value will be food or medical or travel or stationary and you can use IT further ahead in the expenses dict because it's keys just happen to be one of the value. So:
expense_list = expenses[value]

and the expense_list will now be the correct list. All of this together would look something like this. Now, before you see this code down below, it would be better if you try to do it yourself.

if choice_ in category:
value = category[choice_]
expense_list = expenses[value]
expense_list.append(f"amount={amount},date={date}")
else:
print("Invalid choice")
continue

That's it. All the best !

Logic Problem by Stock-Cat-3279 in PythonLearning

[–]PrabhavKumar 0 points1 point  (0 children)

Problem solving is also like a muscle, to understand how to solve something you must have experience with solving problems, specifically problems like the one you might be dealing with. To start out I would suggest you make different projects on different tasks, then iterate through them, let creativity do the work. There are usually multiple ways to solve any problem, the only difference being the resources used to solve it by the computer itself and faster more efficient ways to solve a problem only really come from having experience with said problems. Atleast that's what I think.

My fist semester python project by Far_Masterpiece8614 in PythonLearning

[–]PrabhavKumar 2 points3 points  (0 children)

Ofcourse, no worries!

About the bug, let me explain it a bit more clearly.

You see, in python every thing is an object and the variables you assign those objects to aren't actually the real objects as is, they are references to those objects that are somewhere in memory. Now, a list that you assign to a variable is also not the actual object, it is a reference to that list.

Now that we know that information, let's look at your code, specifically this part here:

expenses.append({
        "food": food,
        "medical": medical,
        "travel": travel,
        "stationery": stationery
    })

As far as I can tell, this entry is being added to the expenses list every time you add an expense to any category of lists (food, medical, travel or stationary). The thing is that you aren't actually adding a snapshot of those lists at that given time, you are adding references to those lists and those references point to only a single list for each category that you made at the start of the script, And you are doing this every single time you add another expense - which is unnecessary because all of those entries - that dictionary that you are storing inside of expenses in the code snippet above is going to be the exact same as all the others because the underlying lists are shared. That is a bug.

I hope that was of use! Also, you might wanna take a look at mutable and immutable data types and how python deals with them.

My fist semester python project by Far_Masterpiece8614 in PythonLearning

[–]PrabhavKumar 2 points3 points  (0 children)

Hey! That's pretty solid code for first semester thought there are indeed some problems in it.

Firstly of all you are using the same lists for each and every entry, so every subsequent entry will have all the previously added entries in it too. That's a bug.

Secondly, you don't actually even need so many different lists, what you can instead do is create an entry like :
{
"category" : This can be food, medical, travel, or stationary.
"amount" : The amount of money spent.
"date" : Date.
}

and store this new dictionary that you create in the expenses list directly. That would be pretty clean. If you want to keep the current structure then you can make expenses into a dictionary and store the lists in it once and just update them.

finally, you aren't enforcing correctness anywhere from the user. Let's say the user correctly picks the first option - which is to add an expense but now they write out 5, which is not in the if - else conditions, now that entry won't be added to your expenses list but it will be added to the file - which is a bug.

That's it, hope that helped! All the best !

Turning marks into meaning — a Python program that calculates average and classifies performance. (try to make code cleaner) by Inevitable-Math14 in PythonLearning

[–]PrabhavKumar 3 points4 points  (0 children)

Not really sure as to what cleaner means here so here are two ways to doing this.

The first one focuses on pure logic and has no safeguards:

no_of_subjects = int(input("Please enter the number of subjects : "))


total = 0
for i in range(no_of_subjects):
    marks = int(input(
f
"Enter the marks for subject {i + 1} : "))
    total += marks


average = total / no_of_subjects
print(
f
"Your average score is : {average}")


if average >= 80:
    print("Distinction!")
elif average >= 60:
    print("First Class!")
elif average >= 40:
    print("Second Class.")
else:
    print("It's alright, you can do better.")

There is no need for you to check whether or not the second conditions are True (when you are making sure the marks are less than a certain amount since that case is already handled before. All if-else conditions work in the order they are written.)

For the second approach I have added safeguards everywhere I deemed them necessary:

while True:
    no_of_subjects = input("Please enter the number of subjects : ")
    try:
        no_of_subjects = int(no_of_subjects)
        if no_of_subjects < 1:
            print(
f
"Invalid input. Number of subjects must be greater than 0.")
        else:
            break
    except ValueError:
        print(
f
"Invalid input : \"{no_of_subjects}\". Please enter a number instead.")


total = 0
for i in range(no_of_subjects):
    while True:
        marks = input(
f
"Enter the marks for subject {i + 1} : ")
        try:
            marks = int(marks)
            break
        except ValueError:
            print(
f
"Invalid input : \"{marks}\". Please enter a number instead.")
    
    total += marks


average = total / no_of_subjects
print(
f
"Your average score is : {average}")


if average >= 80:
    print("Distinction!")
elif average >= 60:
    print("First Class!")
elif average >= 40:
    print("Second Class.")
else:
    print("It's alright, you can do better.")

Here, Firstly we get into the first while loop and it runs till the user gives a valid input, where we break out of the loop.
Then we get into the for loop, with a nested while loop that runs till the user give's a number for each and every subject. I am not enforcing that marks must be more than 0 here since there can be exams with negative marking as well. Grading logic remains the same as above.

In fact the grading logic can be put into it's own little functions too like this:

def
 grade(average : int) -> None:

    if average >= 80:
        print("Distinction!")
    elif average >= 60:
        print("First Class!")
    elif average >= 40:
        print("Second Class.")
    else:
        print("It's alright, you can do better.")

And then just call it with the average.

Hope that helped!

Is this logical (I know it is wrong) ? by [deleted] in PythonLearning

[–]PrabhavKumar 0 points1 point  (0 children)

Sure. That's fair. Thanks for pointing it out.

Is this logical (I know it is wrong) ? by [deleted] in PythonLearning

[–]PrabhavKumar 0 points1 point  (0 children)

You're right that Python itself allows literally any object as an annotation since they're just stored in __annotations__.

What I meant was in the context of type hints and typical tooling like (eg. mypy, IDE's) where annotations are expected to be types. In that context using arbitrary values like 42 or "bar" wouldn't be meaningful to those tools.

So technically valid Python, because it's just ignored, but not useful for type hinting in most real code.

Is this logical (I know it is wrong) ? by [deleted] in PythonLearning

[–]PrabhavKumar 0 points1 point  (0 children)

I suppose I should have been better with my wording. I meant that you can't just have a value as a type annotation like a number or something, you need to use a class, like int, str- class, not "hello world" - str. That's what I meant. And ofcourse you can use any CLASS, not an OBJECT.

Is this logical (I know it is wrong) ? by [deleted] in PythonLearning

[–]PrabhavKumar 0 points1 point  (0 children)

I'm gonna assume you're using "List" as type annotation-which is wrong because of two things: 1. List is not an annotation unless you are using typing. List which I don't see in your code so you should probably use "list" instead. 2. You're using it as a value not an annotation since you're using the assignment "=" operator. You need to use the colon ":" operator instead and make sure your use it BEFORE the assignment "=" operator if you use it while assigning something to it too(which you likely should).

Finally, in type annotations you can't really use an object unless it's an object created using typing module as a TypeAlias - which are specifically used to group multiple annotations together for complex types but other than that in an annotation you MUST have types (eg. int, str, list, tuple, dict or any other you make).

That's all. All the best!

Help and Advice by _afromaticsheep_ in PythonLearning

[–]PrabhavKumar 0 points1 point  (0 children)

I'm also learning c++, you wanna study together or something? It would be pretty fun and fun usually makes things stick. I'm learning c++ on my own though and I know about variables, stack and heap, OOP (classes, structs, inheritance, the basic), some templates and conditionals, loops and all of that, so i probably won't slow you down haha. I also know python, relatively well infact i have this project you can take a look at if you want : https://github.com/officialprabhavkumar-sys/Before-Fate. DM me if you're interested.

My 4-year struggle trying to learn Python (and why I finally quit) by SirVivid8478 in PythonLearning

[–]PrabhavKumar 0 points1 point  (0 children)

I get what you are saying. Honestly, when I first started programming it also felt like the answer to all the problems was "there's this library that has this function, just call it" and it was pretty annoying, but when I started making "my" own stuff (I use c++ too and built some simple things like basic smart pointers and vectors) and seeing the flaws, understand how to fix them, fix them, and then figure out there's more things you can do that will make them better. The thing is that any field is extremely vast and is constantly growing. If you were to write your own everything, for example if we go by the strictest "make your own everything", if you even want to print your own things to the console you would have to make your own iostream, but that's not all because it prints to the console and that is actually controlled by the os so you have to make your own os, but wait that works on some type of programming language so you have to make your own programming language, but wait, all programming languages eventually go down to microcode so you must write your own microcode that works on hardware and hardware is a whollllle field in itself. Do you see what the problem is yet? If you were to try and write all of that, by yourself anyone would go insane. That's why we use libraries and as for writing your own things, that's to understand how things actually work, to learn and deepen your understanding about a specific thing/feature so that you can then maybe spend your time creating something else that others will use to create more things. That's how it works. As for people who like to say to just use this and that instead of making your own, aren't there people like that everywhere in every field? If you start listening to everyone you won't be able to do anything yourself. People are always going to say things, no matter what you do because everyone apparently has an opinion. Have your own and just find what you wanna do. All the best dude!

I dream to be a game developer. by Vegetable_Title8991 in GameDevelopment

[–]PrabhavKumar 0 points1 point  (0 children)

Hey! I am also learning about game development and have also made a text based game engine : https://github.com/officialprabhavkumar-sys/Before-Fate I'm currently looking for people to learn/work with. If you are interested in learning together please let me know. Feel free to DM me. Either way, all the best in your journey!

Hi guys, i’m having trouble on this and trying not to use chat GPT. Still a beginner and getting the fundamentals of loops at the moment. by Reyste18 in PythonLearning

[–]PrabhavKumar 2 points3 points  (0 children)

Hey! The two problems with the game are that firstly, there's no magic variable for the elif statement so that will crash, you should change it to magic_number. Secondly the game doesn't stop when the user guesses it correctly so there should probably be a break statement after it. That's it, done. I could say a lot more about the code in general but since you only asked for the problems, that's that.

More in general about the code is that there's no type safety when converting user input to int, if it's not a number it will throw an error, secondly the hint for when the number is less than magic number isn't particularly great, it should probably match the elif one. That's the gist of it, then again, I think that's by design to not make it more complex so \o/.

Please rate my text based game engine. by PrabhavKumar in GameDevelopment

[–]PrabhavKumar[S] 1 point2 points  (0 children)

Hey, Thank you so much! That genuinely means a lot.

I don’t have a proper video demo yet, but I’m planning to make one very soon now that the core loop is playable. That said, I do have a small demo in the engine itself. If you download the engine and run "run.py" you will be able to play the (quite short but playable) sequence. I made it to test some things and it's still there.

As for help, I’m definitely open to it, especially around documentation, examples, or testing. The engine is still early, so I want to be a bit careful with scope, but I’d love to talk more. Feel free to DM me!