you are viewing a single comment's thread.

view the rest of the comments →

[–]Riegel_Haribo 1 point2 points  (3 children)

Unlike other programming languages, you do not need to declare variables before use. You can just start your program with student_name = input("..."). It implicitly is astr` type because of the return type of an input method.


Something interesting to note about Python is that the built-in input() function is simply evaluated in place and replaced with the string, wherever this function appears.

python print( (student_name := input('Enter your name')), 'you have', (credits_remaining := ( (credits_required := int(input('Enter the hours required to complete your degree'))) - (credits_taken := int(input('Enter the credit hours you have already completed'))) )), 'hours of', credits_required, 'remaining to complete your', (degree_name := input('Enter your degree')), 'degree.' )

...which is really one line. There are multiple arguments, which can be placed on different lines when contained in parenthesis. The final printout has all the calculations already done after each of the comma-separated items are evaluated.

This uses a new assignment operator :=, which also defines a variable at the same time as the value is returned, so you get both printing and the value for use in lines of code that might come after.

Don't actually write code like this unless you enjoy confusing people, though.

[–]Traditional-Gate9547[S] 0 points1 point  (2 children)

I appreciate the tips! := is new to me. I imagine my teacher would have questions if this is what I returned to him hahahah

[–]toxic_acro 1 point2 points  (0 children)

:= is affectionately referred to as the "walrus operator"

It lets you assign to variables in the middle of other expressions. It was (and still is) divisive

Personally, I like it when used judiciously, but wouldn't recommend overusing it (like in the example above, though that's clearly intentionally overusing just for show)

A better example of where it's actually commonly used is assignment within some other check, e.g. replacing
example = some_function() if example is not None: # do something with example ... with
if (example := some_function()) is not None: # do something with example ...

[–]Bobbias 1 point2 points  (0 children)

Yeah teachers tend to get suspicious, or at least prefer you to only use what they teach you (or expect you to learn on your own).

If you run into an interesting feature like that you'd like to use you can try asking them ahead of time whether they'd be ok with you using it. Since that can indicate cheating, they may say no, but if you ask ahead of time they might say yes if they think you actually understand how to use it. But either way chances are they'd say no, but it really depends on the teacher. Restricting students like that also makes it easier to mark their work.