Why is this correct? Looks to me like it shouldn't work. - Page 4 - Overclock.net - An Overclocking Community

Forum Jump: 

Why is this correct? Looks to me like it shouldn't work.

Reply
 
Thread Tools
post #31 of 51 (permalink) Old 12-26-2017, 08:04 AM
 
 
gonX's Avatar
 
Join Date: May 2006
Location: Odense, Denmark
Posts: 29,522
Rep: 1157 (Unique: 647)
Quote:
Originally Posted by PhotonFanatic View Post

Thanks once again for the help everyone. Much appreciated.

Now I ask

Is raw_input always preceded by a variable? As in, the raw_input function will not work, unless a variable is assigned first?

If you mean if you have to assign the return value of a function to a variable, then no, it's technically not required. But with some functions, like raw_input(), it would be pointless not to assign a variable.
Can you give a code example?

Also, raw_input() is a Python 2 function. It has been renamed to input() in Python 3. Is the guide you're following based on Python 2?

What does OCN offer as a site?
What are infractions and warnings?
How to make quality posts
#well
(19 items)
CPU
Intel Core i7 4770k
Motherboard
Gigabyte Z87X-UD4H
GPU
Sapphire RX 580
RAM
2x G.Skill F3-2400C10-8GTX
Hard Drive
Samsung 840 EVO
Optical Drive
Generic DVD±RW Burner
Power Supply
Corsair TX850
Cooling
Noctua NH-D14
Case
Fractal Design Core 2500
Operating System
Arch Linux
Monitor
Dell U2711
Monitor
Samsung SyncMaster 2233
Monitor
LG W2453TQ
Keyboard
Ducky DK9008G2, Cherry MX Blue, Overclock.net Edition
Mouse
Logitech G303
Mouse
Xtrfy GP3 HeatoN
Audio
Beyerdynamic DT-770 80 Ohm
Audio
AntLion ModMic v3
Audio
M-Audio Fast Track USB
▲ hide details ▲


gonX is offline  
Sponsored Links
Advertisement
 
post #32 of 51 (permalink) Old 12-26-2017, 08:07 AM
Guru Meditation
 
TUFinside's Avatar
 
Join Date: Oct 2013
Posts: 2,064
Rep: 53 (Unique: 44)
As long as i have my meal, who cares about mathematics ? rolleyes.gif

CPU
Intel Core i7-8809G (Quad-Core 3.1 GHz / 4.2 GHz Turbo - Cache 8 Mo - TDP 100W)
GPU
AMD Radeon RX Vega M GH Graphics
RAM
G.Skill RipJaws Series SO-DIMM 16 Go (2 x 8Go) DDR4 3000 MHz CL16
Hard Drive
Intel SSD 760P Series M.2 NVMe
Hard Drive
Intel SSD 760P Series M.2 NVMe
Operating System
Windows 10 Pro
Monitor
Gechic 1305H
Keyboard
Cooler Master TKL with Topre switches
Mouse
Logitech M590 silent mouse
▲ hide details ▲
TUFinside is offline  
post #33 of 51 (permalink) Old 12-29-2017, 11:37 AM
New to Overclock.net
 
Petrol's Avatar
 
Join Date: May 2011
Location: Toronto
Posts: 994
Rep: 82 (Unique: 46)
Quote:
Originally Posted by herkalurk View Post

Code:
        if [ `grep -c "^#dateext" ${ROTATE}` -eq 1 ]
        then
                sed -i 's/^#dateext/dateext/g' ${ROTATE}
                echo "Uncommented dateext"
                SUCCESS[${#SUCCESS[*]}]="Log date extnesions uncommented in config\n"
        elif [ `grep -c "^dateext" ${ROTATE}` -eq 1 ]
        then
                echo "dateext already enabled"
                SKIP[${#SKIP[*]}]="Log date extensions already enabled in config\n"
        elif [ `grep -c "^dateext" ${ROTATE}` -eq 0 ]
        then
                sed -i "s/compress/compress\n\ndateext/g" ${ROTATE}
                echo "Added dateext"
                SUCCESS[${#SUCCESS[*]}]="Log date extensions setting added to config\n"
        else
                echo "Unsure of what to do? dateext isn't normal"
                FAIL[${#FAIL[*]}]="Log date extnesions settings aren't normal, please fix manually\n"
        fi

Here's another example I found in my scripts...

I don't like elif because I find it more mentally taxing than cascading/nesting if/else statements, which are easier to reason through because they reduce all possibilities to simply IF or ELSE. This is not a critique but I rewrote the above without elifs, see if the flow is easier to understand:
Code:
INPUT=$(sed -n '/^.\?dateext/p' ${ROTATE})

if [ -n "$INPUT" ]; then
        if [ -n "$(echo "$INPUT" | sed -n '/^#/p')" ]; then
                #...
                echo "uncommented dateext"
                #...
        else
                #...
                echo "dateext already enabled"
                #...
        fi
else
        #...
        echo "added dataext"
        #...
fi


Quote:
Originally Posted by Fuell 
Ignorance is bliss. But then someone finds you and beats the crap out of you.
Petrol is offline  
Sponsored Links
Advertisement
 
post #34 of 51 (permalink) Old 12-29-2017, 09:22 PM - Thread Starter
New to Overclock.net
 
PhotonFanatic's Avatar
 
Join Date: Dec 2009
Posts: 1,878
Rep: 19 (Unique: 18)
Quote:
Originally Posted by gonX View Post

If you mean if you have to assign the return value of a function to a variable, then no, it's technically not required. But with some functions, like raw_input(), it would be pointless not to assign a variable.
Can you give a code example?

Also, raw_input() is a Python 2 function. It has been renamed to input() in Python 3. Is the guide you're following based on Python 2?

Yes code academy says that they're currently using python 2 to teach. But I figure I can work out all the little details later on, once I have a greater mastery of Python in general.

As for a code example, my question would go something like this:

Can you just say:

raw_input() = "Please enter your username"

#And then you'd hit the "run" button. I don't have any experience with actually coding in jetbrains. I looked at it, and I didn't see a run button, which will test your code over on the right.

But if that won't work, why not?

Would it be more like this:

example_variable = raw_input("Please enter your username")

print example_variable
Quote:
Originally Posted by Petrol View Post

I don't like elif because I find it more mentally taxing than cascading/nesting if/else statements, which are easier to reason through because they reduce all possibilities to simply IF or ELSE. This is not a critique but I rewrote the above without elifs, see if the flow is easier to understand:

Thank you, this helps me a lot. And I do find elif to be mentally taxing. Much more so than figuring out what is true or false in a long line of boolean operators. So let me get this straight. Its easier to just do this:


if

else

if

else

if

else

if

else

...On and on and on, as many times as needed. But is that limiting? Would elif expand the functionality? Or could you forever just use an unlimited amount of elses and ifs? (on anything and everything)

"Executing execution.exe"
Bang for the buck
(12 items)
CPU
3570k @ 4.6Ghz @1.35v
Motherboard
Gigabyte Z77x UD3H
GPU
evga GTX 970 SSC
RAM
16Gb Gskill Ripjaws 2133Mhz @ 9-11-10-28
Hard Drive
Samsung Evo 850
Power Supply
Silverstone 900 watt
Cooling
Thermalright Ultra 120 Extreme
Case
Silverstone Raven (1st edition)
Operating System
Windows 10 Spy Delux
Monitor
Xstar 27" PLS 1440p
Keyboard
Wireless ergonomic
Mouse
Logisys Wireless trackball
▲ hide details ▲
PhotonFanatic is offline  
post #35 of 51 (permalink) Old 12-29-2017, 09:45 PM - Thread Starter
New to Overclock.net
 
PhotonFanatic's Avatar
 
Join Date: Dec 2009
Posts: 1,878
Rep: 19 (Unique: 18)
Here is another question. Why does my code after "if" not have to be on the next line? But after "else" it does? Here's the correct answer to the exorcise in question:


print 'Welcome to the Pig Latin Translator!'

# Start coding here!
original = raw_input("Enter a word:")
if len(original) > 0:
print original
else:
print "empty"

Here is what I did, which was marked as wrong:

print 'Welcome to the Pig Latin Translator!'

# Start coding here!
original = raw_input("Enter a word:")
if len(original) > 0:
print original
else: print "empty"

"Executing execution.exe"
Bang for the buck
(12 items)
CPU
3570k @ 4.6Ghz @1.35v
Motherboard
Gigabyte Z77x UD3H
GPU
evga GTX 970 SSC
RAM
16Gb Gskill Ripjaws 2133Mhz @ 9-11-10-28
Hard Drive
Samsung Evo 850
Power Supply
Silverstone 900 watt
Cooling
Thermalright Ultra 120 Extreme
Case
Silverstone Raven (1st edition)
Operating System
Windows 10 Spy Delux
Monitor
Xstar 27" PLS 1440p
Keyboard
Wireless ergonomic
Mouse
Logisys Wireless trackball
▲ hide details ▲
PhotonFanatic is offline  
post #36 of 51 (permalink) Old 12-30-2017, 04:32 AM
 
 
gonX's Avatar
 
Join Date: May 2006
Location: Odense, Denmark
Posts: 29,522
Rep: 1157 (Unique: 647)
To explain the necessity of elif as opposed to multiple if/else statements, consider the following task:

A student has turned in his assignment. You must assign a grade based on the amount of correct answers the student has.
Your program will have 1 input, the amount of correct answers in percentage, as an integer between 0 and 100.

A result of 90 or greater, yet still below or equal to 100, will produce an A.
A result between 80 and 89 will produce a B.
A result between 70 and 79 will produce a C.
Any other input will will result in a failing grade (F).

Your program must return the grade as a character: A, B, C, or F.


I just made this in the BASH language and it's 13 lines long. I could make it 10, but using best practices I get 13.
I'll post my code once you show me some code that uses elif.

With the inputs being 100, 80, 79, 30, 0, 101, -1 respectively, you should be getting A, B, C, F, F, F, F

---

As for the syntax question in post #35, don't forget Python uses leading whitespace instead of curly braces to indicate grouping of statements. The way your code is written right now should be a syntax error in itself:
https://docs.python.org/2.0/ref/indentation.html

Your 'if' expression need a boolean expression to even know if it has to enter the 'if', go to the next 'elif', if any, or finally go to the 'else' statement.
The line with the 'if' has an expression it has to evaluate, which is why 'code can exist on the same line' as the 'if'.

---

The answer to the raw_input command would be the latter of the 2:
Code:
output = raw_input("Please write something now:")
print output

Doing the former you suggested, aside from being a syntax error, would be an attempt to reassign the raw_input function.

What does OCN offer as a site?
What are infractions and warnings?
How to make quality posts
#well
(19 items)
CPU
Intel Core i7 4770k
Motherboard
Gigabyte Z87X-UD4H
GPU
Sapphire RX 580
RAM
2x G.Skill F3-2400C10-8GTX
Hard Drive
Samsung 840 EVO
Optical Drive
Generic DVD±RW Burner
Power Supply
Corsair TX850
Cooling
Noctua NH-D14
Case
Fractal Design Core 2500
Operating System
Arch Linux
Monitor
Dell U2711
Monitor
Samsung SyncMaster 2233
Monitor
LG W2453TQ
Keyboard
Ducky DK9008G2, Cherry MX Blue, Overclock.net Edition
Mouse
Logitech G303
Mouse
Xtrfy GP3 HeatoN
Audio
Beyerdynamic DT-770 80 Ohm
Audio
AntLion ModMic v3
Audio
M-Audio Fast Track USB
▲ hide details ▲


gonX is offline  
post #37 of 51 (permalink) Old 12-30-2017, 11:14 PM
Retired Staff
 
herkalurk's Avatar
 
Join Date: May 2010
Location: Portland, OR
Posts: 2,039
Rep: 69 (Unique: 58)
Code:
#!/bin/bash

echo "What score did you get out of 100?"
read score

re='^[0-9]+$'
if ! [[ ${score} =~ ${re} ]] ; then
   echo "error: Not a number" >&2; exit 1
fi

if [ `echo ${score}` -ge 90 ]
then
        echo "Your grade was an A"
elif [ `echo ${score}` -ge 80 ]
then
        echo "Your grade was a B"
elif [ `echo ${score}` -ge 70 ]
then
        echo "Your grade was a C"
else
        echo "Your grade was an F"
fi



herkalurk is offline  
post #38 of 51 (permalink) Old 12-31-2017, 05:45 PM
 
 
gonX's Avatar
 
Join Date: May 2006
Location: Odense, Denmark
Posts: 29,522
Rep: 1157 (Unique: 647)
Well, I intended for PhotonFanatic to do it tongue.gif I'll post my code once he does it as well. Same language as herkalurk's, looks really similar too

What does OCN offer as a site?
What are infractions and warnings?
How to make quality posts
#well
(19 items)
CPU
Intel Core i7 4770k
Motherboard
Gigabyte Z87X-UD4H
GPU
Sapphire RX 580
RAM
2x G.Skill F3-2400C10-8GTX
Hard Drive
Samsung 840 EVO
Optical Drive
Generic DVD±RW Burner
Power Supply
Corsair TX850
Cooling
Noctua NH-D14
Case
Fractal Design Core 2500
Operating System
Arch Linux
Monitor
Dell U2711
Monitor
Samsung SyncMaster 2233
Monitor
LG W2453TQ
Keyboard
Ducky DK9008G2, Cherry MX Blue, Overclock.net Edition
Mouse
Logitech G303
Mouse
Xtrfy GP3 HeatoN
Audio
Beyerdynamic DT-770 80 Ohm
Audio
AntLion ModMic v3
Audio
M-Audio Fast Track USB
▲ hide details ▲


gonX is offline  
post #39 of 51 (permalink) Old 01-01-2018, 12:20 PM
New to Overclock.net
 
Petrol's Avatar
 
Join Date: May 2011
Location: Toronto
Posts: 994
Rep: 82 (Unique: 46)
elif is not necessary for this scenario either. I've modified herk's version a bit and copied the sanity check to my version to make the two as similar as possible, and added a timer to show the difference in execution times is negligible.

with elif:
Code:
#!/bin/bash

timer=$(date +%N)
re='^[0-9]+$'
score=$1
if ! [[ ${score} =~ ${re} ]] ; then
   echo "error: Not a number" >&2; exit 1
fi

if [ "$score" -ge 90 ]; then
        echo "Your grade was an A"
elif [ "$score" -ge 80 ]; then
        echo "Your grade was a B"
elif [ "$score" -ge 70 ]; then
        echo "Your grade was a C"
elif [ "$score" -ge 60 ]; then
        echo "Your grade was a D"
else
        echo "Your grade was an F"
fi
timer=$(( $(date +%N) - $timer ))
elapsed=$(echo "scale=10; $timer * 10^-9" | bc)
echo "this took $elapsed seconds"

without elif
Code:
#!/bin/bash

timer=$(date +%N)
num=90
score=$1
re='^[0-9]+$'
grades=("A" "B" "C" "D" "F")

if ! [[ ${score} =~ ${re} ]] ; then
   echo "error: Not a number" >&2; exit 1
fi

if [ "$score" -lt 50 ]; then
        echo "you're better off not knowing your grade!"
else
        for i in ${!grades[@]}; do
                if [ "$score" -ge "$num" ]; then
                        echo "your grade was ${grades[$i]}"
                        break
                else
                        num=$(( $num - 10 ))
                fi
        done
fi

timer=$(( $(date +%N) - $timer ))
elapsed=$(echo "scale=10; $timer * 10^-9" | bc)
echo "this took $elapsed seconds"

Most obvious is how the version without elif has less repetition. Less obvious is that the version without elif is also easier to modify, in situations where there might be more conditions or where the conditions may even change at runtime. So elif is handy for quick-n-dirty work but even in such a limited task not required, and once the task grows, depending on elif raises the risk of introducing hard-to-notice runtime errors.


Quote:
Originally Posted by Fuell 
Ignorance is bliss. But then someone finds you and beats the crap out of you.
Petrol is offline  
post #40 of 51 (permalink) Old 01-27-2018, 08:58 PM - Thread Starter
New to Overclock.net
 
PhotonFanatic's Avatar
 
Join Date: Dec 2009
Posts: 1,878
Rep: 19 (Unique: 18)
The help is much appreciated guys! But at this point, I'm so new that explanations actually help me a lot more than looking at code. I can only read about half of the code that was listed. The explanation about grading a student's paper really helped though. As you can see the only reason they counted it wrong was because I put something on the wrong line.

So instead of

else: print "empty"

It was supposed to be:

else:
print "empty"

I was just wondering why it couldn't be on the same line. But I guess it really doesn't matter, I've come to the conclusion that the vast majority of learning to code is just memorizing the rules. So now onto my next question:

What is the difference between: %20d %20s and %s? I may just be me, but it seems like code academy has a bad habit of throwing a lot of things in the lessons that they don't bother to explain. And then, those things are included in the quizzes.

"Executing execution.exe"
Bang for the buck
(12 items)
CPU
3570k @ 4.6Ghz @1.35v
Motherboard
Gigabyte Z77x UD3H
GPU
evga GTX 970 SSC
RAM
16Gb Gskill Ripjaws 2133Mhz @ 9-11-10-28
Hard Drive
Samsung Evo 850
Power Supply
Silverstone 900 watt
Cooling
Thermalright Ultra 120 Extreme
Case
Silverstone Raven (1st edition)
Operating System
Windows 10 Spy Delux
Monitor
Xstar 27" PLS 1440p
Keyboard
Wireless ergonomic
Mouse
Logisys Wireless trackball
▲ hide details ▲
PhotonFanatic is offline  
Reply

Quick Reply
Message:
Options

Register Now

In order to be able to post messages on the Overclock.net - An Overclocking Community forums, you must first register.
Please enter your desired user name, your email address and other required details in the form below.
User Name:
If you do not want to register, fill this field only and the name will be used as user name for your post.
Password
Please enter a password for your user account. Note that passwords are case-sensitive.
Password:
Confirm Password:
Email Address
Please enter a valid email address for yourself.
Email Address:

Log-in



Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Show Printable Version Show Printable Version
Email this Page Email this Page


Forum Jump: 

Posting Rules  
You may post new threads
You may post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are Off
Pingbacks are Off
Refbacks are Off