Python question

I'm a total noob at coding (I actually started just a few hours ago), and I'm trying some python exercises.

I am asked to
>Compare a variable “user_guess” to a variable “hidden_answer,” and tell the user whether the guess is too low, too high, or exactly right.

Just for fun, I even tried to make the program keep asking the user for a number until he gets it right.

Pic related is what I came up with, and it works, but how can I avoid repeating like a nigger the input for the user_guess variable after each conditional?
Is there a more elegant way to do this?

Other urls found in this thread:

analyticsvidhya.com/blog/2016/01/python-tutorial-list-comprehension-examples/
docs.python.org/3/library/random.html
docs.python.org/3/library/random.html#random.randint
docs.python.org
twitter.com/NSFWRedditVideo

Think about how the interpreter moves through each sequence of instructions in your program. If you set user_guess to something like 0, and prompted for user guess just after your while loop, what would happen?

just remove line 9 and deindent 12?

>prompted for user guess just after your while loop
Yeah, I didn't see that while I was thinking about it the first time, now I see it.

Pic related works the same.

You don't need an else after the loop.

Makes sense, actually.
Nice.

you don't want your old guesses to be shown when guessing a new one? you can either use ncurses or do it the ghetto way with importing os and use os.system("clear") or os.system("CLS") on windows at the start of the loop

Whatever you wrote goes way beyond my current comprehension. 3 or 4 hours ago I had never even looked at a line of code in my life...

tqdm does it without curses or os

I think this is the best way to do what you need.
hidden_answer = 14
user_guess = None
while user_guess != hidden_answer:
user_guess = int(input ('Guess the number: '))
if user_guess < hidden_answer:
print('Low')
elif user_guess > hidden_answer:
print('High')
print('OK')

Yeah python doesn't have a do-while loop so this is best answer

Yep, alternatively this is a bit more concise but perhaps a little more advanced.
hidden_answer = 14
while True:
user_guess = int(input ('Guess the number: '))
if user_guess == hidden_answer:
break
print('High' if user_guess > hidden_answer else 'Low')
print('OK')

>but how can I avoid repeating like a nigger the input for the user_guess variable after each conditional?
>Is there a more elegant way to do this?
à function. But this is fine beginner stuff, keep at it. You could also use what you know and rather do this instead:

hidden_answer = 14
while True:
user_guess = int(input('Guess the number: '))
if (user_guess == hidden_answer):
print('OK')
break
elif (user_guess < hidden_answer):
print('Low')
else:
print('High')

I actually wrote exactly this after another anopn made me think of it.

Can you explain the reason for using the condition "while True"? What are you doing exactly?
Thanks.

Wtf are you talking about? It has while-true loops, which are literally the same thing

>Can you explain the reason for using the condition "while True"? What are you doing exactly?

When using "while True" then the only way to get out of the while loop is with a "break" statement. So it basically means "keep this while loop going forever until there is a "break" statement"

Nothing wrong with what you were doing, but this way it would be easier to get everything inside the while loop.

"break" statements will break out from any while loop even with the one in OP. So there is no need to make up some statement that is true while the loop is running, can just use the "while True".

It is not always the best option, sometimes what you did is better, but I feel it's easier to read when practically the whole while loop is an "if-else" conditional.

Is this what Sup Forums has come down two helping some random noob , pls just stop for you are not helping this guy buy spoonfeeding him.

Not the same I don't think.


int i = 15;
do { printf("you're a big guy");} while(i>10);
[\code]

What's the while(true) equivalent of this?

So basically it's an easy way to start a loop (that you have to break manually), correct?
I learned some useful things, so fuck off.

while true is (in principle) like saying "for as long as 1+1==2, do this", except while statements (and if statements for that matter) basically take the condition you describe (in the example before, 1+1==2) and reduce that to either True or False. so saying "while True" is like a shortcut.

sometimes you see people trying to be clever by doing things like "while 1" or whatever. it's essentially the same idea; when you turn 1 into a boolean, it comes out as True (rather than False). everything does except for 0.

as an aside, i'm not a big fan of "while 1". it's syntactically valid, but "while True" is clearer about the purpose. i feel like every time i encounter a programmer who does something marginally esoteric like "while 1", they turn out to be a bit of a douche, too.

Yeah, god forbid an actually useful thread exists rather than another "isntall gentoo" shitpost or some faggots talking about watches.

Not bad for someone who has only been at it for a few hours, user. I think you'll go far

To be fair user, while(True) isn't valid in C, for example, so it's possible people do while(1) out of habit.
You can also create a for-loop that runs forever.

for(;;) {

//expression

//conditional 1

//conditional 2
break;
}

With older compilers this was slightly superior choice because it didn't have to keep testing the loop condition every time, I think nowadays it's just a matter of preference, though

>So basically it's an easy way to start a loop (that you have to break manually), correct?
it's an easy way to start an *infinite* loop. you COULD make the loop more functionally relevant by doing something like this

from random import randint
user_guess=False
hidden_answer=randint(0,100)

while user_guess!=hidden_answer:
try:
user_guess=int(input("give me a guess >> "))
except ValueError:
print("you fucking fuckface, i need an integer")
print("Too {}".format("high" if user_guess>hidden_answer else "low") if user_guess!=hidden_answer else "You got it!")


# @ mbp ~ $ python3 rand.py
# give me a guess >> 50
# Too low
# give me a guess >> 75
# Too high
# give me a guess >> 62
# Too high
# give me a guess >> 56
# Too low
# give me a guess >> 59
# Too low
# give me a guess >> 61
# Too high
# give me a guess >> 60
# You got it!

>To be fair user, while(True) isn't valid in C, for example, so it's possible people do while(1) out of habit.
oh, fuck, i forgot about that. i'll have to be more careful judging people in the future. thanks

What is pep8?

The equivalent of that snippet in any language is
while True: print("you're a big buy")

pep8 is a guide. you can use whatever line length limit you want (80 chars is too restrictive in my opinion, and based on constraints that are no longer present; also, 120 better represents what i can fit in half of a screen), and 2 spaces are sufficient for me to visually differentiate scope.

also, this is a post on Sup Forums.

Don't listen to these morons who tell you to use "while True", it's fucking terrible style.

The condition upon which a loop breaks should be readable from just reading the loop condition by itself, making a loop "while True" and then using breaks inside of the conditionals completely undermines that and only serves to make your code less readable.

People will argue with me about this no-doubt, but I assure you it's bad style and any professional should agree.

>To be fair user, while(True) isn't valid in C, for example, so it's possible people do while(1) out of habit.
the booleans are now available in C though, with that defines the _Bool type, true, and false, but they aren’t used that much (I noticed lots of C99’s features and newer aren’t that known)

Ok, but that code is too complicated for me, I don't get it.


Anyway, would any of you mind looking at this other exercise?
I think that B is decent enough, but how do I do that with a single if statement (ex. C)?

Pic related

i agree with you in principle. if the condition is known at the outset (like it is here), and especially if it's simple enough that you should be able to articulate the condition concisely (again, as here), then there's no reason to use such a blunt hammer as "while True".

that being said, in practice "while True" is a small and common enough kludge that i wouldn't shit the bed over it. people are lazier and shittier about other things that i actually care about.

>Ok, but that code is too complicated for me, I don't get it.
let's walk through what you didn't understand before i take a look at other problems. there are some previously undiscussed ideas in my code but for the most part i don't think any of it is so complex that we should just ignore it.

>So basically it's an easy way to start a loop (that you have to break manually), correct?

That is exactly why people do it. But as it is an infinite loop and it's a dangerous way to do it.

But I disagree with that it's bad style. It gives the oppurtunity to break from the while loop with several conditions.

cd code
ls
..
..
ls

print("too high")

First of all, what do the first three lines do?

I don't know what the "try" statement does.
I guess that you also make sure that the user inputs an integer.

By looking at the rest of it I think I can sort of understand what you're doing, but I wouldn't be able to repeat that, I just don't know the theory behind it.

>Ok, but that code is too complicated for me, I don't get it.
You should take up this guy's offer because apart from shit style (breaks pep8) he has some clever moves and considerations. Including comprehensions ( analyticsvidhya.com/blog/2016/01/python-tutorial-list-comprehension-examples/ ) which you should learn to understand most professional python code and it's not too difficult to learn.


>but how do I do that with a single if statement (ex. C)?

Try using (parantheses) to separate each truth statement or at least each side of the "or"

remove line 2 and initialize user_guess.

You're talking out your ass. It's a perfectly common idiom in Python.

>First of all, what do the first three lines do?
Im not the guy, but might help out.

from random import randint
hidden_answer=randint(0,100)

imports the function "randint" from the "random" library. The random library is part of the so called "standard library" which comes included with Python. It's basically code to do simple things like for example in this case "randint" chooses a random integer (integer is a whole number without decimals). To see what other things randint can do you should read the documentation where you can also read about the other stuff in random

docs.python.org/3/library/random.html

The "hidden_answer=randint(0,100)" just chooses a random integer between 0 and 100.

"user_guess=False" is just so that it has another value than hidden answer. It could just as well be 101 or something, but I guess False was chosen so that you did not need to change both if you go over 100 on the randint.

>I don't know what the "try" statement does.
>I guess that you also make sure that the user inputs an integer.
The "try" statement basically checks to see if you get an error and the following "except" is what happens if the error is of the type "ValueError". Without errorhandling like this then the program might just crash if the user inputs something other than an integer.

The reason that it becomes a ValueError is because that is the error that happens if you put something other than an integer in the statement: int(input("give me a guess >> "))

the first line imports a library that Python has called random, but specifically i only load a single function from that library, called randint. there's some information about randint here docs.python.org/3/library/random.html#random.randint

but the gist is that you call it with 2 integers and it gives you back a random number in that range. it's convenient for giving you relatively unexpected values. if you hard code your test case (like to 14), there's always a weird chance that the code you write will somehow overlook an edge case. in this circumstance i can't think of one specifically, but randomness has a way of hardening your logical reasoning.

the second line just initiates user_guess to something. i could have made it a number, but since hidden_answer was going to be something random, i didn't want to take a chance that they could be the same. the literal value False will never be equal to a number, so it's a safe option. but i could've made it equal to "poop" or -1000000 if i wanted to. in either of those cases it would have evaluated as different from hidden_answer the first time.

you basically figured out the try statement on your own. the try statement just "tries" to do the stuff within the code block. when you call input("give me a guess"), it actually gives back a string. there's no way to *guarantee* that the user will give you back a string that'll parse as an integer, so someone could reply to that prompt with something like "no thanks", and then when you call int(input("give me a guess")) it'll try to turn "no thanks" into an integer and crash.

so what try does is it basically gives you the ability to handle errors (which are called "exceptions") by following up with something like "except ValueError". it has a vaguely similar feel to an "if/else" statement, but in this case if the code in the "try" block fails because of a "ValueError", then the thing within "except ValueError" happens instead of the whole script crashing.

also, some of these things are syntactic showing off. the whole

print("Too {}".format("high" if user_guess>hidden_answer else "low") if user_guess!=hidden_answer else "You got it!")


thing is arguably somewhat complicated and if it's too confusing you can think of it as functionally equivalent to

if user_guess!=hidden_answer:
if user_guess>hidden_answer:
print("Too high")
else:
print("Too low")
else:
print("You got it!")


but as you can see, that's a lot more vertical space for a lot of conditional statements that are pretty simple (in my opinion, although admittedly i'm more used to this stuff than you are).

This confirms the idea I got by looking at the code then (even though of course I would not be able to write that on my own, I even still make a lot of mistakes with syntax).
Well, I have no trouble reading it if you put it like that. I didn't know you could write it like that.

Thanks, anons.

programming is a never-ending treadmill of you getting better but seeing someone ahead of you who seems more comfortable doing stuff in more concise, cleverer terms. the key is to see that stuff and learn from it, and eventually to get comfortable doing it yourself. if you stick with it, putting all of those conditionals in one line like i did in the first code block of will eventually be trivial to you. i promise.

i was totally flummoxed by this stuff when i started out, and now i'm a phd student in CS at one of the top 5 universities in the world. just give it time.

import random
hidden_answer = random.randint(0,100)
while True:
user_guess = int(input ('Guess the number: '))
if user_guess < hidden_answer:
print('The number is lower than hidden')
elif user_guess > hidden_answer:
print('The number is higher than hidden')
else:
break
print('Well done user!')

yeah we talked about some of this before. while True isn't a great choice if you have such an obvious and concise condition that you're aiming for, because it obfuscates the purpose of the while loop a bit.

python's big advantage is readability. don't undercut it.

>is too complicated for me
break it down, try to understand it.
When you are stopped at something, look it up.
docs.python.org is a good resource for finding documentation for functions.

As for many statements together or one giant statement, that is up to you.
If you end up writing a bunch of statements as one, use parenthesis, it makes things easier to read, especially if you mix and and or statements.
You can put a parenthesis on your code and break the statement up or you can use \ at the end of the line to break it up.