+ 2

Python :=

I just don’t understand the use case for the := operator in python, can someone please explain ?

8th Oct 2021, 1:36 PM
Elfin
Elfin - avatar
3 odpowiedzi
+ 7
Jibraeel Abdelwahhab , the samples you provided are correct (except the spelling of print(...)) # here is a sample for a code that takes input in a loop until an empty string is encounterd: inputs = [] inp = " " while inp: inp = input() if inp: inputs.append(inp) print(inputs) #the same task done with the walrus operator: inputs = [] while inp := input(): inputs.append(inp) print(inputs) the code: while inp := input() takes an input, stores it in a variable, and evaluates the while statement. this is what is called 'assignment expression' enabled by this operator that was introduced in python 3.8
8th Oct 2021, 2:18 PM
Lothar
Lothar - avatar
+ 1
Hello, i dont have a firm mastery over the python language but I can try to help you understand the walrus operator. := from my understanding means to declare and recieve input on a variable in a print statement. For example: the slow way X = input() Print(x) The walrus way: Print(x:=input())
8th Oct 2021, 2:05 PM
Jibraeel Abdelwahhab
Jibraeel Abdelwahhab - avatar
+ 1
":=" is walrus operator, new in python 3.8; it's used to declare variables and compare them in the same time; It's mostly used in statements, loops... etc
8th Oct 2021, 2:37 PM
Sousou
Sousou - avatar