24
loading...
This website collects cookies to deliver better user experience
name = 'Shreyas'
age = 20
message = f'{name} is {age} years old'
# Shreyas is 20 years old
# we can also write expressions inside the braces
vote_status = f'{name} {"can vote" if age>=18 else "cannot vote"}'
# Shreyas can vote
a,b,c = (1,2,3)
# a = 1
# b = 2
# c = 3
*
also known as the unpacking/packing operator. It packs multiple values to a single variable and forms a iterable which we can use to our liking. For example:random_values = [True, 17, 'dev_to', 84.3943, f'{12*3}', -35]
a,b,*c,d = random_values
# a = True
# b = 17
# c = ['dev_to', 84.3943, f'{12*3}']
# d = -35
*args
in a function, if uncertain about the number of parameters to be passed, using *args
, all the parameters are packed into a tuple.def product(*numbers):
result = 1
for n in numbers:
result *= n
return result
product(1,2,3)
# 6
product (12,334,31,353,3)
# 131578632
input()
saves a lot of time and is intuitive.parse_args()
which returns a namespace object.# example.py
import argparse
parser = argparse.ArgumentParser(description='simple script info')
parser.add_argument('--num','-n', default=20)
args = parser.parse_args()
print(args.num)
python example.py --num 5
5
python example.py
20
Python
>>> print('hello')
hello
>>>
# example.py
unit_price = 10
stock = 200
def get_stock():
return stock
def purchase_units(quantity):
global stock
if stock-quantity > 0:
stock -= quantity
return quantity*unit_price
return -1
get_stock()
python example.py
add -i
flag before the name, it will run the script once first, but the interpreter will still be active, now you can call functions of that script, get values of variables, etc. python -i example.py
200
>>> unit_price
10
>>> purchase_units(5)
50
>>> stock
195
>>>
for index in range(0,len(example_list)):
which is fine, but enumerate does it better.enumerate()
for each iteration, enumerate returns a tuple, the first element a counter/index and the second element in the item of that iterable. We can unpack the tuple in the for loop and use as we wish.example_list = [4,30,38,7,48]
for counter, element in enumerate(example_list):
print(counter, element)
# 0 4
# 1 30
# 2 38
# 3 7
# 4 48
for counter, element in enumerate(['a','b','c'], start=97)
print(counter, element)
# 97 a
# 98 b
# 99 c