#🔒 Confused?

349 messages · Page 1 of 1 (latest)

trim elm
#

So I understand that we want the user to input a positive int number

We make sure that its positive by starting off with a while loop only accepting numbers greater than 0. But I don't really see where to go after this

I just learnt nested loops (and the course has yet to teach me for loops yet)

hollow schoonerBOT
#

@trim elm

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.

nimble python
#

we want to repeat asking them when it ISN'T a positive number

#

The loop asks over and over until they enter something positive

trim elm
#

wait wait

#

while number > 0: wouldnt this repeat if the user inputs something less than 0?

nimble python
#

yes

#

but you want to ask the user for a positive number, no?

trim elm
#

yeah

cobalt vault
nimble python
#

so "while number is less than 0, ask the user for a number"

nimble python
cobalt vault
#

that code which they have in their message would not repeat if the user inputs a number less than 0

tawdry crystal
trim elm
#

so now that covers the check if its positive or negative

nimble python
#

we often want to think of while loops flipped from how we would do our if

trim elm
#

okay

#

now if the int is positive

nimble python
#

once the loop ends, we know the int will be positive

trim elm
#

we want to perform the list of multiplication opeartions

nimble python
#

we don't need to do an additional check

trim elm
#

so we just print outside of the loop?

#

yeah print outside of the loop bcs it keeps looping until its positive

nimble python
#

you'll want another loop now to handle printing the multiplication table

trim elm
#

but what would the condition be? we dont need to check if its positive now we need to have it so the list of operations doenst exceed the number

nimble python
#

There's no condition necessary

#

have you learned for loops yet?

#

oh sorry just read your original message

trim elm
#

nope so i dont think theyre expecting us to use that

#

all good

nimble python
#

ok then yes, you'll need some new variables here

trim elm
#

i could set i = 0 then on the next line while i < number and increment i each time

nimble python
#

so number is going to act as the max value

trim elm
#

yes

nimble python
#

but you'll need a nested loop

#

so you'll want another variable to keep track of the count of the inner loop as well

#

j = 0 would work nicely

trim elm
#

would i put it inside the while loop or outside below the i variable?

nimble python
#

no : should be at the end of the line though

#

for j = 0

trim elm
#

oh yh

#

habit

#

but what condition would we need for the nested loop?

nimble python
#

well how high should the inner loop count?

trim elm
#

till the number?

#

wait lets go back a step how comes we would need a nested loop for this? I'd like to understand this too before moving on

#

bcs we've dealt with the part to ensure the list of multiplcation opeartsions doesnt exceed the number ( all i havent added in yet is the increment part)

#

is the nested loop going to be needed for the actual printing out?

nimble python
#

if your number is 3, you need every combination of 1, 2, 3 x 1, 2, 3

trim elm
#

oh okay so j needs to keep on going until number so while j < number:

#

thats the condition done how do we now figure out each combination for each number

nimble python
trim elm
nimble python
#

also just to think about the final output, you probably don't need 0, and you do want number

#

so i and j can start at 1

#

and your condition should be <= instead of <

trim elm
#

what would it print out if we put 0 instead

#

for this example

nimble python
trim elm
#

cool yeah we dont need 0

#

do we need to print out the combinations now using a f string?

nimble python
#

Yes exactly 🙂

trim elm
#

but one thing

#

wdym

nimble python
#

oops wrong channel

trim elm
#

print(f"{j} x {}") what would i put in the second curly bracket ?

nimble python
#

what other variables do you have available?

trim elm
#

print(f"{j} x {i}")?

#

and then print(f"{i} x {j}") outside ?

nimble python
#

you only need 1 print

trim elm
#

oh

nimble python
#

it happens inside the inner loop

trim elm
#

did it salute

nimble python
#

now let's see why most people prefer for loops here 🙂

#

!e

for i in range(1, 4):
    for j in range(1, 4):
        result = i * j
        print(f'{i} x {j} = {result}')
hollow schoonerBOT
nimble python
trim elm
trim elm
nimble python
#

for loops make simple counting much simpler

gentle merlin
#

for loops and range make this alot more convenient

#

tbh i cant even think of how to do this with nested while loops

#

but im pretty dumb

trim elm
#

number = int(input("Please type in a number: "))

while number < 0:
    number = int(input("Please type in a number: "))

i = 1

while i <= number:
    j = 1

    while j <= number:
        print(f"{i} x {j} = {j*i}")
        j+= 1

    i+= 1

idk how to format the code properly 😭

nimble python
trim elm
#

but you get the idea

nimble python
trim elm
#

with the correct indentations

nimble python
#
number = -1
while number < 0:
    number = int(input("Please type in a number: "))

i = 1
while i <= number:
    j = 1
    while j <= number:
        print(f"{i} x {j} = {j*i}")
        j+= 1
    i+= 1
trim elm
#

oh that works yeah

#

didnt even think of it like that

#

anyways another exercise done and dusted (im about to be stuck on another one sob_pray )

nimble python
#

that's good though! Seems like you got through this ok with a bit of thought

#

If you haven't been, I really recommend having your own editor where you can test code for these exercises

gentle merlin
#

did this actually want a nested loop btw? it dosent seem like its asking for one

nimble python
#

it makes testing really quick, and you can see your results right away

gentle merlin
#

you can test the code on their online interpreter too

nimble python
trim elm
gentle merlin
#

my smooth brain just did this

unit_1 = 1
unit_2 = 1
number = int(input("Please input a positive number: "))

if number >= 0:
    print("Enter a number above 0")

while unit_1 <= number:
    print(f'{unit_1} x {unit_2} = {unit_1 * unit_2}')
    unit_2 += 1
    if unit_2 > number:
        unit_2 = 1 
        unit_1 += 1
nimble python
gentle merlin
#

it does

trim elm
nimble python
gentle merlin
#

once he gets to the later parts the course uses tmc inside of vscode to do things

nimble python
nimble python
gentle merlin
#

yeah

#

it just makes more sense in my head like this if i cant use range or for loops though

nimble python
#

a for loop is actually a while loop in disguise

trim elm
#

pengu have u done the mooc.fi course?

nimble python
#

so it helps to think of them that way

gentle merlin
#

yeah

trim elm
gentle merlin
#

i finsihed it yeah

trim elm
#

its been pretty good so far

gentle merlin
#

its pretty good

#

but since it was in finish originally sometimes the questions read kinda weirdly

trim elm
#

were you already proficient in another language or was python your first?

gentle merlin
#

and the error messages arent always clear

#

python is my first

trim elm
#

nice what have you moved onto do since completing the mooc?

gentle merlin
#

kinda stuck in a rut atm tbh ive never been good with self learning lol

trim elm
#

same lol but completing the mooc means youve pretty much learnt a decent amount of python

gentle merlin
#

very slowly going through their dap course atm but they removed it recently

nimble python
gentle merlin
#

i just kinda learned it to get into programming tbh

#

i didnt have any goal in mind at the time

#

cyber security and ai seem interesting but i dont feel like i have enough knowledge to branch into those atm

trim elm
#

for ai/ml i think kaggle has good intro courses

gentle merlin
#

might take a look at some point

trim elm
#

how long did the python mooc take you and how much time did u spend on it per day?

gentle merlin
#

it took me a while since i eventually only started doing one or two exercises a day

#

took me a few months to do the advanced course

#

could have done it a lot faster

#

but i was maybe 1-3 hours a day?

#

some of the later exercises took me a while

gentle merlin
#

the basic course shouldnt take that long tbh

trim elm
#

did u do any random projects outside of the mooc?

gentle merlin
#

i did do some, but i could never really think of what to make

trim elm
hollow schoonerBOT
#
Kindling Projects

The Kindling projects page contains a list of projects and ideas programmers can tackle to build their skills and knowledge.

gentle merlin
#

the only real unique project i made was hangman with llm integration for hints

trim elm
#

im already stumped 😭

#

was it normal to get stuck at an exercise beginning like this

gentle merlin
#

yeah

#

everything is new so its expected

#

the lectures on the course do help abit

#

they are pretty dry though

trim elm
#

calm

nimble python
trim elm
#

nope

nimble python
#

Do you know how to split a string up like that into its words?

trim elm
#

as in string slicing?

nimble python
#

Not quite

#

Have you learned about lists?

trim elm
#

nope

#

all ive learnt so far is

#

input, variables, arithmetic operations, conditional statements, while loops, nested loops, string slicing index stuff

nimble python
#

would you know how to print every letter of the string 1 at a time?

gentle merlin
#

they should be expecting you to use string slicing for this

nimble python
gentle merlin
#

or indexing

nimble python
#

yeah, definitely indexing

gentle merlin
#

i used slicing in my really dumb solution

trim elm
nimble python
trim elm
#

prints infinitely oops

nimble python
#

Do you understand what indexing is?

trim elm
#

yes

#

indexing starts with 0

nimble python
#
sentence[0]
sentence[1]
sentence[2]
...
#

so basically you just want to do this

trim elm
#

0 = s

#

etc

nimble python
#

until you reach the end of the string

#

So you've already seen how to make a number count up using a while loop

#

but how do you know when to stop the loop?

vast cape
#

"can't use for loops" as in OP doesn't understand for loops, or isn't allowed to use for loops?

trim elm
#

until i is == len of the word

nimble python
vast cape
#

ah okay

nimble python
#

len - 1

#

if a string has 10 letters, the index is 0-9

trim elm
#

oh yeah bcs length is always one more

nimble python
#

the last index is always len - 1

#

so start by writing that out

trim elm
#

ive written this out so far

nimble python
#

perfect

#

ok, now let's think about what it actually wants you to print

#

the first letter of each word

trim elm
#

yup

nimble python
#

which is basically "the first character after you encounter a space"

#

(and also the very first letter of the string)

#

we can do this a few different ways

trim elm
#

so we want some sort of if statement to check if theres a space?

nimble python
#

yes exactly

trim elm
#

but then this wouldnt work for the first character

#

or would it still work

nimble python
#

depends on how we set this up

#

have you learned about bool?

trim elm
#

yes

nimble python
#

There's a technique called "boolean flags"

#

basically, we have a boolean that keeps track if we've recently seen a space

#

I really like to think about them like light switches

trim elm
#

like on = true
off = false ?

nimble python
#

exactly

#

so here's the setup

If we see a space, turn on the lightswitch
If the lightswitch is on, print the letter and turn off the lightswitch

#

The order we do this in is important though. I actually described it in reverse

#

First we check if the lightswitch is on. If it is, print the letter and turn off the light switch

#

If the current letter is a space, turn on the lightswitch

trim elm
#

so would I need variables for the "switches"

nimble python
#

just 1 variable, yeah

trim elm
#

and would it initialise it to true or false

#

false right since it starts at the beginning

nimble python
#

That depends if you want to print the first letter or not 😉

#

If you always want to print the first letter, then it should start on

#

because we print letters when the switch is on

trim elm
#

but if the switch is on from the start wouldnt it skip the first letter until it finds the space

#

and prints the letter after it

nimble python
#

we flip on the switch to indicate that the next letter should print

trim elm
#

ohh

nimble python
#

but if we start with it on, the first letter is the next letter

trim elm
#

makes sense

vast cape
trim elm
#

if switch == True:
        print(sentence[i])
        switch = False
nimble python
#

a neat thing about booleans is we don't have to actually write the == True

#

we can just do if switch

vast cape
#

i was gonna interrupt but nevermind - my apologies

trim elm
#

oh since its already true

nimble python
trim elm
nimble python
#

because we don't want to turn on the switch and then check if it's on

#

it should check the next letter

trim elm
#

so now we can successfully print the first letter

#

now we'd need a condition for when the switch is false?

nimble python
#

We don't need a condition for when the switch is False

#

if it's false, we don't do anything

#

the other condition is "is this letter a space"

trim elm
#

cool

#

so if sentence[i] == " ": something like this?

nimble python
#

exactly 🙂

trim elm
#

question is

#

do we need to nest this or

#

we just have it outside

nimble python
#

no nesting

#

it needs to be inside the while loop

#

but not inside the other condition

trim elm
#

cool

#

would it be better to make it a elif or a whole new if statement

nimble python
#

depends if you think they're related

#

do you only want to check if one is true?

trim elm
#

another exercise complete salute2

#

heres code

nimble python
#

let's see it

trim elm
#

sentence = str(input("Please type in a sentence: "))

switch = True
i = 0

while i <= len(sentence) - 1:
    
    if switch:
        print(sentence[i])
        switch = False
    elif sentence[i] == " ":
        switch = True

    i+= 1
nimble python
#

it doesn't need to be elif, but nice!

#

it will start to matter in some edge cases but for simple sentences it's just fine

gentle merlin
#

my initial solution for this was so massovley overcomplicated for what it was

gentle merlin
#

my heart sank when i looked at the model solution

trim elm
#

ty for helping btw

nimble python
#

!e

text = 'ab cd ef'

print(*[ch[0] for ch in text.split()], sep='\n')
hollow schoonerBOT
gentle merlin
#

when i first did it i did this

sentence = input("Please type in a sentence")   
space = sentence.find(" ")
index = space
    
if " " not in sentence[0:space+1]:
    print(sentence[0])
if " "  in sentence[0:space+1]:
    print(sentence[0])
    print(sentence[space+1])
    space+=1
    
while True:
    if sentence[space] != " ":
        space+=1
    if sentence[space] == " ":
        print(sentence[space+1])
        space+=1
    if " " not in sentence[space:] or " " not in (sentence[0:space+1]):
        break
#

and then i look at the model solution and its one line

nimble python
nimble python
# trim elm

yeah, this is another way where you just see if the previous index is a space (and the current is NOT a space)

trim elm
#

I really like the switch idea though worked pretty well

#

with the boolean flags

nimble python
#

yeah, it's a really handy technique

#

and I find the lightswitch analogy helps people understand it better

trim elm
#

yeah its definitely helpful ty once again

nimble python
#

np!

trim elm
#

will carry on coding tmrw , learnt that its better to do one or two exercises per day over a long period of time then to do 5 in a day get burnt out and procrastinate

nimble python
#

just like learning the piano, you don't learn a song once and move on

#

you go back and practice those songs

trim elm
#

as in should I go back to exercises to try see how i could make it more efficient or ?

nimble python
#

just to see if you can still solve it

trim elm
#

ah okay

nimble python
#

I see people write programs and then come back a week later and they couldn't remember how to do it

#

"Don't practice until you get it right. Practice until you can't get it wrong"

trim elm
#

got it!

#

would you revisit an exercise like a day after or a couple days later

nimble python
#

it's better when it's still fresh

#

the longer you wait, the more you'll lose it

#

I usually learn something by following along a guide/tutorial, then immediately opening a blank file and seeing if I can do it again without the guide this time

#

then I'll do it again tomorrow and see how much I remember

trim elm
#

so tomorrow I can basically do the same thing for the two exercises I completed today

nimble python
#

yeah, it should go much quicker

#

then add a few new exercises on top

trim elm
#

I always have this chat to refer to if i need help (I will still be trying to do without the help)

trim elm
gentle merlin
#

tbh looking back at part 3 i still have 0 clue how i would do this exercise, they do have a couple of really weird ones like this

trim elm
trim elm
gentle merlin
#

in functions

#

slightly further than you

trim elm
#

apart from the mooc did you try any other course

#

like cs50p?

gentle merlin
#

no

trim elm
#

fair, im assuming they all teach the same thing anyways so no need to do multiple

#

you know you could go on to learn a python framework maybe

gentle merlin
#

i was thinking about going into cs50p for a refreshe though sinces ive been really lacking on actually coding

trim elm
#

it would probably be quick to finish too since you already learnt most from mooc

gentle merlin
#

the stuff im doing rn i barely understand

trim elm
#

one question how comes your learning to program? is it for a specific career or just for fun

#

don’t mean to be all personal just curious

#

for me it’s both

gentle merlin
#

its abit of both i guess

trim elm
gentle merlin
#

doing image processing in their dap course

#

but that course kinda sucks tbh

#
#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt

def center(a):
    height, width = a.shape[:2]
    return (height -1) / 2, (width -1 ) / 2

def radial_distance(a):
    height, width = a.shape[:2]
    x, y = center(a)
    a, b = np.indices((height, width))
    return np.sqrt((a-x)**2 + (b-y)**2)

def scale(a, tmin=0.0, tmax=1.0):
#     """Returns a copy of array 'a' with its values scaled to be in the range
# [tmin,tmax]."""
    amax, amin = np.max(a), np.min(a)
    if amax != amin:
        a_copy = (a-amin)/(amax-amin) * (tmax - tmin) + tmin 
        # tmin + (a-tmin)*(tmax-tmin)/(amax-amin)

    else:
        a_copy = np.zeros(a.shape)
    return a_copy

def radial_mask(a):
    distance = radial_distance(a)
    mask = abs(1.0 - scale(distance))  
    row, col = (a.shape[0] -1) // 2, (a.shape[1] -1) // 2
    mask[row, col] = 1.0     
 
    return mask

def radial_fade(a):
    mask = radial_mask(a)
    if a.ndim == 3:
        mask = mask.reshape((a.shape[0], a.shape[1], 1)).astype(a.dtype)
    return a * mask

def main():
    a = plt.imread("painting.png")

    mask  = radial_mask(a)
    faded = radial_fade(a)
    
    fig, axes = plt.subplots(3, 1)
    axes[0].imshow(a)
    axes[1].imshow(mask, cmap = "gray")
    axes[2].imshow(faded)
    plt.show()
    
if __name__ == "__main__":
    main()

this took multiple hours of bashing my head against a wall

#

and all it does is fade the outside of an image

#

no idea what you would use it for tbh

trim elm
#

if you feel like the course is useless and u don’t enjoy it

#

i’d say just drop it

#

and u mentioned how ur interested in cybersec/ai

#

maybe look into how u could start with those

#

or learn a python framework

gentle merlin
#

i should, but im stubborn so i may aswell finnish what ive started

#

anyway you should !close the thread now since you're done with the exercise

hollow schoonerBOT
#
Python help channel closed with !close

This help channel has been closed. 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.