-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwalrus_operator.py
64 lines (37 loc) · 991 Bytes
/
walrus_operator.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# Using The Walrus operator
# python 3.8+
# Syntax
# (any_variable_name := value)
# (number := 45)
# Example 1
# Without Walrus operator
x = 12
value1 = x < 52 # value1 = true (Assignment)
print(value1) # output true
# With Walrus operator
y = 3
print(value2 := y > 1) # value2 = true (Assign and return the value)
print(value2)
# Example 2
# Without Walrus operator
numbers = []
num = input("Type a number: ")
while num.isdigit():
numbers.append(int(num))
num = input("Type a number: ")
print("Without walrus operator", numbers)
# With Walrus operator
numbers2 = []
while (num2 := input("Type a number: ")).isdigit():
numbers2.append(int(num2))
print("With Walrus operator", numbers2)
# Example 3
# Without Walrus operator
base = 10
if base == 10:
answer = input("Type your answer: ")
if answer != "":
print("Nice")
# With Walrus operator
if (base2 := 30) == 30 and (answer2 := input("Type your answer")) != "":
print("Nice")