elijahk2 / Miscellaneous-Python

0 stars 0 forks source link

Python Talk #1

Open eholm62 opened 6 months ago

eholm62 commented 6 months ago

thechnically by submitting an issue on this repository i can send you messages in github

eholm62 commented 6 months ago

i think you can close this issue when you are done with it

elijahk2 commented 6 months ago

Ah ok.

elijahk2 commented 6 months ago

I think you are the only one who can close it.

elijahk2 commented 6 months ago

NVM I can close it as well.

elijahk2 commented 6 months ago

Will you give me commands you think I should know but tell me the proper syntax?

eholm62 commented 5 months ago

Yeah, and I'll tell you about functions for now, but you could also ask me specifically what you'd like to learn about. You can define functions with the def keyword, followed by the function name and its parameters (input). At the end of the function header you should put a colon to signify to the python interpreter (the thing that runs your code), that you are going to indent code that needs to be grouped with that function. Complete whatever logic you need to within the function body, then use the keyword return followed by whatever you would like to return. Just like with loops, you show the interpreter that you are exiting the body of a function by unindenting back to the original level of indentation the function was defined on. You can then call these functions you've defined from anywhere in the file following the function defenition, and however many times you'd like. I have an example program below to show you it all in use.

def factorial(n):
    product = 1
    for i in range(1, n + 1):
        product *= i
    return product

# actual program
user_input = input("Input a number: ")
print("The factorial of " + user_input + " is " + str(factorial(int(user_input))));
elijahk2 commented 5 months ago

So why would you want to use this?

eholm62 commented 5 months ago

In general, the rule is that you should encapsulate as much code as you can in functions. Not only does it make the code more readable, reusable, and modifiable, but it can also improve code performance. For example, if you have some operation that you will perform very often that takes a lot of code, you could put it in a funtion, then you only have to write one line of code every time you want to use all that code. It makes it simpler to keep track of what needs to be done. You can create a function, and once it's done and fully functional, you don't ever have to worry about how it atually works, you just get to use it wherever you want. Functions also don't have to return anything. You could make a function like this:

def my_print(text):
    print(text)

It doesn't return anthing, so using it in an expression like 1 + my_Print("hello") will not work, but it does still print something. You could technically put an entire program inside a function, then just call that function at the end of the file, like this:

def main():
    user_input = input("Input your name: ")
    print("Hello " + user_input)

main()

In fact, in most popular programming languages this is a requirement. You can't create a program without a main function in C and C++, and you can't create a Java program without a Main class and a main method. Python is an exception, allowing you to simply just write code directly in the program. print and range are both functions (well technically not range but it doesn't matter for you right now), and without them, it would be much more diffucult to write programs. Now just imagine how much easier it would become to make a program if you could design any function you could imagine.

A good way to think of functions relative to scratch, is as custom blocks. The blocks you are already given are like built in functions that come with the language, like print or range. Custom blocks are like those functions you write yourself, and whether or not you use them yourself, you can't argue that all the largest and most impressive scratch projects make use of custom blocks, because had they not, they likely would have never been finished.

There's an entire paradigm (philosophy) of programming, called functional programming, related to structuring your code around the use of functions. Python is mostly a functional programming language, meaning it was designed to be utilized with functions. It also has aspects of object oriented programming, but that isn't something you should learn about yet.

elijahk2 commented 5 months ago

Ok thank you

elijahk2 commented 5 months ago

Also, I've been a little busy with school, so I haven't really had much time to make anything. (and I have no ideas) So if you have ideas for simple programs that you think would help me learn, tell me the general idea and I will try to make it.

eholm62 commented 5 months ago

Ok I can do that

eholm62 commented 5 months ago

Try writing a program that reads an integer called n from the user then prints the nth row of pascals triangle. Here are the first few rows of pascals triangle: image You will probably want to learn about lists, which I can help you with if you want. Also, you might already know about how pascals triangle is constructed, but if you don't, try wikipedia or ask me. I didn't explain it right here because I don't think I'm good enough at explanations to properly explain it, but if you need help I can try my best.

elijahk2 commented 5 months ago

I know how pascals triangle works I think but I do need to know how lists work.

elijahk2 commented 5 months ago

ELLIOT I CREATED MY FIRST "GAME" (it is "fishsim.py" in my only repository and it can be run in the code spaces terminal or something. ask me if you have questions or tell me if there are any tips you have (I have several already))

eholm62 commented 5 months ago

Nice!! I'm going to bed now but I can take a look at it in more depth tomorrow.

eholm62 commented 5 months ago

I looked at the code and I'm excited to see how it plays

eholm62 commented 5 months ago

I played the game and I really enjoyed it! I found a trick to never lose and I'd say that's a big success because it was fun to try and find the correct algorithm to maximize profits. Heres a screenshot of where I just stoped: Screenshot 2024-05-11 4 19 01 PM

eholm62 commented 5 months ago

And I can help you with lists now too. You can create a list like this: lst = []. This specifies that the variable lst will store an empty list. Keep in mind you cannot actually call the variable list, because that represents the list type in python. It's common to call generic lists lst if there isn't anything more specific you can provide. Anyways if you want to create a list with objects already in it you can do it like this: lst = ["hello", "there", 6, 8, 8.0]", 6, 8, 8.0]. Notice how you can fill it with objects of different types. That list I created contains numbers (integers and non-integers which are called floats in python) and strings too. You can add items to the end of the list like this: lst.append("appended element"). Doing so will make it so that the list is now: lst = ["hello", "there", 6, 8, 8.0, "appeneded element"]. You can access elements of the list like this: lst[0]. That expression will evaluate to "hello", because "hello" is the first element in the list, and lists are numbered counting from zero. You can also modify elements of the list just like you would variables. For example: lst[0] = "goodbye" will modify list so that now the first element is "goodbye". You can also access the length of a list like this lst.len(), which will evaluate to be an integer. You can use this to easily access the last element of a list: lst[lst.len() - 1]. Accessing the last element of a list is common in many programmibg languages, even sometimes python, but python has a faster way to do it. lst[-1] will do the exact same thing. No need to use lst.len() in that case. The second to last element would be lst[-2] and so on.

eholm62 commented 5 months ago

Here's an example program I wrote making use of a list to generate the first so many fibonacci numbers, whatever the user specifies. Anything above the comment that says "important stuff below" is only there to validate the user input and make sure the code doesn't break if they give unexpected input. The important stuff in the algorithm is below that point.

user_input = input("Input an integer: ")

try:
    user_input = int(user_input)
except:
    print("Input must be a non-negative integer")
    exit()

if user_input < 2:
    if user_input == 0:
        print("Below are the first 0 fibonacci numbers:")
        print([])
        exit()
    elif user_input == 1:
        print("Below is the first fibonacci number: ")
        print([1])
        exit()
    else:
        print("Input must be a non-negative integer")
        exit()

# important stuff below

fib_nums = [1, 1]

for i in range(2, user_input):
    fib_nums.append(fib_nums[i - 2] + fib_nums[i - 1])

print("Below are the first " + str(user_input) + " fibonacci numbers:")
print(fib_nums)
eholm62 commented 5 months ago

Oh yeah and just so you know the terminology, the number inside the brackets when retrieving an element from a list is called the index. Thats actually where the convention to use i as a loop variable came from because it's common to iterate through a list like this:

for i in range(0, lst.len()):
    print(lst[i])

It became common to use i as the name for loop variables even if they don't represent indicies.

Like many things in python there is a simpler way to do it. You could just do this:

for element in lst:
    print(element)
elijahk2 commented 5 months ago

Alright, thank you! I use i in scratch for loops just like this so I understand it. The fishsim.py game was a simulation of something we did in History class to simulate the Tragedy of the Commons (if you know you know) obviously it is a little different but I used the best strategy in class and ended up beating everybody as far as profits and stability goes. Thanks for the help! I used a new import (module, I believe it is called) for the floor() command to make the fish reproduce 1 for every 2 in the lake as well. Internet is truly amazing when it comes to teaching yourself programming!

elijahk2 commented 5 months ago

import module as in the import math command

elijahk2 commented 5 months ago

I have an issue where sometimes I'll be editing my programs in Codespaces and when I try to commit I get a pop-up with a red X which says "unable to run" or something like that and it doesn't let me commit to my repository. I then have to copy all my code and paste it manually into the file on GitHub. Do you know what I can do to fix this?

eholm62 commented 5 months ago

I've never had that issue myself and on the surface level I can't seem to find anything about that by searching on google but I could dig deeper because I didn't look super thouroughly. Just from hearing how you describe it it seems like you may be having trouble connecting to the codespaces, because everything in the codespace actually happens on a remote computer somewhere, so you have to have a good internet connection for it to function. It's also possible that it's an error on GitHub's side because that can happen from time to time, so see if that issue just goes away after a bit.

elijahk2 commented 5 months ago

Ok. Also, how do I make it detect keyboard inputs? Do I need pygame for that and if so how do I get it?

eholm62 commented 5 months ago

Yes, pygame should allow you to do that, although I'm not super familiar with pygame myself. There also should be a way to do it without pygame but I'll have to do some experimentation to see what works then report back to you. But yes, if you want to use the keyboard input to make a game, I believe pygame is the answer.

eholm62 commented 5 months ago

Remember that codespaces can't display visual data, so you'll have to use replit. In replit, just adding the line import pygame should work. I can help you set up a project on replit, and I can also help you link your GitHub to your replit so that you can access your GitHub repository from replit. I'll do that today if I have enough time later.

elijahk2 commented 5 months ago

Ok that would be great!

elijahk2 commented 5 months ago

alright I have a replit account

elijahk2 commented 5 months ago

but I have no idea what is going on

elijahk2 commented 5 months ago

Is there a way to have something like a cloud variables (like in scratch)? I'm assuming no, it would have to be an actual program not something run in the Code spaces terminal and you would need your own server or something.

eholm62 commented 5 months ago

Yeah, you're pretty much right. I've never tried to get something like cloud variables to work, but yes I'm pretty sure it would be difficult to get it working unless you ran the program locally (not online) and spend some money. I'd have to to do some more research to figure out a better way. But an idea I have is to make use of google drive. You might even be able to run the code in codespaces. You could possibly create a google account just for your program, then use the 15 free gigabytes provided to store a file that contains all your cloud variables. You'd have to have a way to store the variables in a way so that it's easy to retreive them and interpret them. You'd also have to figure out how to interface with google drive in code. Another possibility is to use [https://www.openstack.org/](), which I really don't really know anything about, but bsed on some very limited research it seems like you might be able to do what you want with that. I'll do some experimenting on my own to see what works. Give me a bit and I can explain replit to you as well.

eholm62 commented 5 months ago

First go to replit and click "Create Repl". image

Then click "Import from GitHub". image

Because your GitHub account isn't yet linked to your replit it should lead you through a process to link you're account. I can't recreate that because my account is already linked so you'll just have to do that on your own. It should walk you through the entire process. I don't remember if it's hard or not. Anyways, after that, select the reopository you want to import. You can also paste the url of the repo in the url tab if you don't want to select from the list. I'll clone (import) my JavaFractalsWithTurtle repository. Screenshot 2024-05-13 10 26 15 AM

You can click git in the bottom left Tools menu to access the ability to commit and push code to the true repo on GitHub. image

Here's what it looks like for me, after changes have been made. You can put a commit message where it says "Summary of Your Commit". Then click "Stage and commit all changes", to commit. By doing so, you've commited to the repository on replit, meaning you can revert to that commit or branch off of that commit at any time from replit, but the changes haven't been pushed to GitHub yest. To do that you can click "Sync with Remote". Keep in mind this will also pull any changes from GitHub. If you have changes on replit that conflict with changes on GitHub, you'll have to do a manual merge. If you don't. To avoid this try not to work in replit unless it's up to date with the remote GitHub repo, or if you do, don't edit the same files in different ways. image

To access the terminal (it's called shell on replit) scroll through the tools menu again and click "Shell". Once you've done that it'll look like this if you've closed all your other tabs in replit, which is what I prefer to do just to keep the workspace clear. It's the same kind of shell so you can use the same commands you would in codespaces. The only difference is that it might not automatically have python installed, in which case it'll just ask you if you'd like to install it, then take action based on your answer. image

You can create files from the file menu on the left, then click on that file to open it in the editor. It'll look something like this. image

You should be able to import pygame just by adding the line import pygame to the beginning of your python file. Any visual output should be shown in a window in the output tab. If the output tab doesn't open automatically when you run a pygame file, try opening it manually from the tools menu. It should just be blank until any window shows up. It may say something like this below, which is what happened to me. This probably means the replit servers are having issues of some sort, and there's not really anything you can do about that. I think it would be good to continue working on getting python working locally on your actual computer's terminal, because that always works. image

eholm62 commented 5 months ago

You could also create a replit project based on the replit pygame template, then build from that. You can then create a GitHub repository from a replit project. Which I can help you with if that's the path you choose.

elijahk2 commented 5 months ago

Ok I'll see what I can do. I'm a little busy with finals and stuff but I'll find time eventually.

eholm62 commented 5 months ago

Yeah me too so I can't really do much experimenting to help right now but I'm able to respond fairly quickly so ask questions if you have any.

eholm62 commented 5 months ago

Ok so I just found out that the replit output isn't broken right now for everyone, just for us at my school because they somehow blocked it on our school chromebooks. You should be able to code and get output just fine.

elijahk2 commented 5 months ago

Ok cool. Also, do people at your school say "what's up" occasionally? And if so, do you usually respond, "not much, how about you?" or something like that? Because I JUST REALIZED that "What's Up" = Hello. It is so odd.

eholm62 commented 5 months ago

Yeah I don't really think about it much though. I guess it comes from like asking what's up with you, meaning what's wrong, but it just evolved to mean how's it going or what's going on. It is pretty weird I guess. To be honest I never use it because I literally never greet people. If I want to talk to someone I just say their name

elijahk2 commented 5 months ago

Yeah I feel the same way. I never use it either, other people (trying to be cool I guess) are the ones who do.

elijahk2 commented 5 months ago

Also the plan for the upcoming year is like this: We are going on a vacation to Minnesota in June and I'm getting a job in the other parts so I don't know how much time I'll have for this but I should have a decent amount after school is out.

eholm62 commented 5 months ago

Actually for me it's something pretty similar. Im going to Niagara falls for a week leaving next Monday, and I've got a job but I'll still end up having more free time than I ever did during the school year.

elijahk2 commented 5 months ago

Yeah same here. Good luck with your job!