Python

Hey can you guys help me im trying to learn functions in python but i cant grasp it (pic related)

Other urls found in this thread:

theregister.co.uk/2017/03/23/cursor_devours_cpu_cycles_ms_code_editor/
codecademy.com/en/courses/python-beginner-en-pwmb1/1/5?curriculum_id=4f89dab3d788890003000096
programmableweb.com/api/weather-channel')
twitter.com/SFWRedditGifs

self bump

you don't call the cube function but a non existent cube variable
functions should be accompanied by parentheses within which are the arguments

% operator will return the remainder after division

15%3 = 0
15%5 = 0
14%3 = 2

use mod in your if statement like this
if number % 3 == 0 :
#do stuff

also to call functions you need brackets so

cube (number)

that as well

So can you show me the solution to this and ill try to break it down

Why do you have a conditional statement in your second function?

i was trying to put a value in place for number

def cube (number) :
return number ** 3

def by_three (number) :
if number % 3 == 0 :
return cube(number)
return False

by_three(6)
# expected output = 36

I am a dipshit
# expected output 216

Sorry, I didn't read the instructions, lol

this

Thanks im gonna try and break it down now

so what does "if number % 3 == 0 :" do

I will explain this as well as I can. It is not evident in python but functions can be thought of as little black boxes that take an input on one end and give you something on the other end.

int cube ( int number ) {
return number * number * number;
}

The C function I wrote above states that it will return to you an Integer. It also states that it wants an input that is an Integer as well.

Once you think about them in this way you can probably understand what they want you to do.
You can combine multiple functions end to end.

I mean this:
print( function1( function2( 10 ) ) )

Here is how you read the code above.

the print() function prints any value.

In this case print() will print the output of function1().

function1() needs an input so it uses whatever function2() returns

function2( number ) in turn gets an input of 10

You don't have to know what they do to put them all together as long as you know that input is inside the brackets and output goes to the left.


jsut read your question here
I answered it
here

>implicit type conversion from float to boolean
ugly desu

or maybe "if" checks some other variable in the "/" method and sees if it's true?

In any case, a good opportunity to get acquainted with the frustratingly arbitrary internals of python.

'if number % 3 == 0' pretty much translates to "if the remainder of number divided by 3 is equal to 0"

The % sign is the operator 'modulo' which evaluates an expression to the value of how what the remainder is of a number divided by a number

So 9 % 3 = 0 because 9 is divisible by 3 and has no remainder.
So 9 % 3 == 0 is True

so why do i "return cube(number)" as a child of
number % 3 == 0 :
[number % 3 == 0 :
return cube(number)]

Are you following the instructions?
I am sure they explained what the "if" statement does.

Your program executes like this.
We are given a number. That number is given to the by_three function. If the number is divisible by three, our function (by_three) calls function cube and gives it the same number. After cube runs, it returns a number back to by_three and by_three returns it to us. On the other hand if the number is not divisible by 3, function by_three does not call cube and returns False.

Because the value that 'number % 3' evaluates to will be destroyed once it leaves the local scope of the 'by_three()' function. So you need 'return cube(number)' to call the 'cube()' function on the returned value of the 'by_three()' function in order to evaluate it in the 'cube()' function

I'm kind of on your level, I think. I just learned this about a week ago. I've been going through 2 different books though and watching a lot of youtube videos. I recommend Automate The Boring Stuff and How To Think Like A Computer Scientist. Looks like you're using Codecademy, right? I haven't tried that yet

I got kind of lost when I started learning Dictionaries in Automate The Boring Stuff, so I switched to How To Think Like A Computer Scientist

Switch to starting out with python and thank me later.

I got it now thanks but one last thing, how do i know when to do / or when to do %

Also sorry for asking such ignorant questions but thats what kinds confused me at first

Thanks, user. I'll check it out, but I'm really liking How To Think Like A Computer Scientist because at the end of each chapter it has a lot of practice exercises and I feel like that's what's helping me learn and helping everything stick to my memory is the practice exercises
but I'll definitely look into Starting Out With Python

use '/' if you want to divide 2 numbers and use '%' if you want the remainder of a number divided by another number

you do the / operator to divide something by something.
a = 6
b = 3
c = a / b # c will be 2


% is used mainly to check if a number can be divided evenly into another number by beginners

a = 6
b = 3
c = a % b # c will be 0

There are other applications but they will confuse you further.

also my friend recommended me to use code academy and so i went with it

Starting out wiht python does. Trust me senpai, give it a look before you continue.

ok got it thanks

adding to this
When the CPU performs division it automatically calculates remainder as well. In essence % is division but you use the other value in the CPU registers.

I recommend using pycharm.

Got lots of little things to help you learn Python.

ehhhh

I would say visual studio code or a generic text editor.

Pycharm is so huge for their starting projects.

It's what I used when I started. Just lots of little highlights and whatnot that made debuging fast. Plus it has github built in so my work got done with my partner

It depends on the architecture. On ARM, the sdiv/udiv instructions don't provide the remainder.

>I would say visual studio code
>visual studio code
13(!!!)% CPU usage just to display a blinking cursor!

theregister.co.uk/2017/03/23/cursor_devours_cpu_cycles_ms_code_editor/

You can't just mash the keyboard and expect everything to work. This isn't javascript.

I would strongly recommend a basic text editor for learning to program.
Nopepad++ for windows, idle vim notepadqq for linux.

phew i finally completed functions section thanks guys

hey it's a learning process just keep up the good work

it said i was making an infinite loop

he's doing it correctly

link the test
is this code acad? I wanna do it too

codecademy.com/en/courses/python-beginner-en-pwmb1/1/5?curriculum_id=4f89dab3d788890003000096

>if is defined so it executes when its expression is a non-zero value
Oh boo-hoo it's just like C. So arbitrary.

>cube of a number is (number ^ 2) * 3

Mate your problem isn't with python it's with 5th grade math

OK class, today we are going to walk 2 kilometers, but for every kilometer we walk, we'll add another two.

you dont use ^ in python for exponents

Looks like Python Newb got what he needed, so hopefully I can hijack this thread without causing too much upset.

I'm trying to write out the following script, but I just can't wrap my head around Python, the formatting is just too foreign to me. Does anyone know how to do it?

-retrieve .json from (url)
-find first value (and define?)in row of block via largest second value in .json file:
{"name":{"category":[[1,12],[2,54],[3,6]...etc]
-send the value back to the url
-loop the script without capping my raspi's ram.

most of the people that helped me have already left the thread

In line 3 what is the program doing? You are taking the START_LIST and appending (g ** 2). but you are adding items to the START_LIST for each iteration of the loop.
in line 4 what are you sorting and what are you supposed to be sorting

>-retrieve .json from (url)

pseudocode incoming

import requests
import json

r = requests.get('url')
j = json.loads(r.txt)

in j now you have a json

>-find first value (and define?)in row of block via largest second value in .json file:
no idea what that means but youll have to do some formatting

>-send the value back to the url

requests.post('url', data=json.dumps(yournewjson)

>-loop the script without capping my raspi's ram.
while True:
time.sleep(x)

Ah... crap.

Just as well, I feel like what I imagine posters on /out/ feel like when they ask 'how do I start hiking?'

>-find first value (and define?)in row of block via largest second value in .json file:
what did he mean by this?

>no idea what [find first value] means
someone sent me:
[block]col1[np.where(max(col2))]

I think I'm supposed to:
[[name][category]col1[np.where(max(col2))]
but since I don't have the preceding code worked out, I'm not that far yet.

>while True:
>time.sleep(x)
So that repeats everything after (while true:) every (x) seconds, right? What prevents the ram from overloading? (I was told that infinite loops cause problems).

In the block of data, I'm given pairs of numbers like [34,65]. Out of all the pairs, I'm trying to find the (34) because (65) is the largest number in any given pair.

>In the block of data, I'm given pairs of numbers like [34,65]. Out of all the pairs, I'm trying to find the (34) because (65) is the largest number in any given pair.

That's not right. Sorry, I suck at explaining this. If it were formatted as a table, I'm trying to find the value from column 1, based on what the highest value in column 2 is (in the same row, or pair).

imagine the date in the table is a value of x, y pairs ie
x col ycol
x1 y1
x2 y2
x3 y3


put the data in a list of tuple pairs

list = [(x1, y1),
(x2, y2),
(x3, y3)]

(x1, y1) = list[0]
(x2, y2) = list[1]
(x3, y3) = list[2]

x1 = list[0][0]
x2 = list[1][0]
....

get the max y ( max out of list[0][1], list[1][1] list[2][1]) and go from there

hope that helps

does OP still need help?

-Get .json file from weatherchannel's api
-find city number from .json file by highest temperature
{"US":{"City":[[1,98],[2,102],[3,65]...etc
-send the city number (2, because temp 102 is highest) back
-repeat daily

While True:
import requests
import json
r = requests.get('programmableweb.com/api/weather-channel')
j = json.loads(r.txt)

[[US][City]col1[np.where(max(col2))]

#this is where I put the recieving url?

time.sleep(86400)

>Is this even close to being right?

>what is mod
Do you even basic math?

Python is a great language for learning with since it is so simple, but does it have any practical uses?

It doest it is just a babbys first languge, move onto asm when you are done with python

yes

It's quite common in Physics.

I mean outside of academia.

Why don't you google it. Nobody uses it at all in the whole world. All Programming is done in assembly and html + css.

Agreed, pycharm is the best. A bunch of fagzords will say stupid shit like "learn vim first"... don't.

PyCharm has PEP8 shit so your code isn't complete garbage.

"pep 8 standards
:set autoindent
:set shiftwidth=4
:set softtabstop=4
:set tabstop=3
:set textwidth=79
:set expandtab
:set autoindent
:set fileformat=unix
:set encoding=utf-8

OP I know you have your solution but *Raymond Hettinger voice* _there must be a better way_...
def cube (number) :
return number ** 3

def by_three(number) :
return cube(number) if not number % 3 else False


The two changes here are the ternary operator, and implicit truthiness of ints

Obviously ignore the 'not'

This is a less pythonic way to write it, other languages mix up the order so I'd prefer op's method, will make things easier in the long run.

Jesus learn functions and logic first code monkey

The ternary operator may be less readable, but omitting "== 0" is definitely more Pythonic.

/ isn't modulo though

anyway I didn't realize it wasn't proper code and was just OP's fuckup, which I should've realized but whatever.

yeah, he seems to be getting confused by stuff he should've gotten comfortable with in algebra,

`idk ive tried looking back at other assignments but still

I don't program in python, but uh...
> **
Does Python use pointers? lol

Double asterisk is power.

ok lets go over what your code is doing starting.

How many elements are in start_list? There are 5.
g = 5 which is the first element in the start_list.
>square_list = start_list.append(g ** 2)
you are telling the computer to append whatever (g ** 2) is onto the start_list. then put that list equal to the square_list.
what are the elements in the start_list? [5, 3, 1, 2, 4, 25] 25 is the newly appended value because 5^2 is 25.
How many elements are in start_list after line 3 has ran? 6
Then you sort start_list. What does start_list look like now? [1, 2, 3, 4, 5, 25] note it still has 6 elements.
Can you do the next iteration? How many elements will start_list have?

I don't know how I can help you more than this short of giving you the answer. This is a logic problem.

>This is a less pythonic way to write it
How? Ternary is language feature for a reason.

Do you know what a function is in mathematics? There you go.

I just checked the codeacademy tutorial and the first sections cover things op asked us about before going into the function declarations...

I'd just like to explain line 5 for you. #4 says:

'If that number is divisible by 3,
by_three should call 'cube(number)'
and return its result. Otherwise, 'by_three'should return False'

So how do you find out if a number is divisible by 3 without leaving a remainder? Use the modulus operator '%'. It checks if the value on the right can go into the value on the left. If the right goes into the left without leaving a remainder it will give you a value of 0. If the right goes into the left but does leave a remainder then it will give you a value that is equal to how much is remaining. Sp:

9 % 3 = 0 (3 can go into 9 three times without leaving a reminder)

21 % 3 = 0 (3 can go into 21 seven times without leaving a reminder)

5 % 3 = 2 (3 can go into 5 once but will leave a a reminder of 2)


Now, we know that if 'number' is divisible by 3 it will produce the value 0, therefore If we want to find out if an argument is divisible by 3 we must "compare it" to 0 using python's comparison operators like:
== (the same as)
!= (not the same as)
< (less than)
> (greater than) ,etc.

line 5 basically says:
check if (number % 3) is the same value as 0. In the event that 'number' is divisible by 3 then (number % 3) will evaluate to 0 and since 0 is the same as 0 (0 == 0) all of line 5 will evaluate to True and the code under the if statement will execute. If 'number' is not divisible by 3 and leaves a remainder then all of line 5 will evaluate to False and will execute the code under the else statement, returning False.

IMPORTANT! With the code I have and that they have asked you to write you won't actually see the value that is returned by the 'by_three' function. You've merely called the function but you didn't give instructions to print the value of what is return by the 'by_three' function. If you want to see the value then line 11 should look like this:

print by_three(9)

Cheers and keep coding!