See Function Definitions in the Language Reference.
If the form
*identifieris present, it is initialized to a tuple receiving any excess positional parameters, defaulting to the empty tuple. If the form**identifieris present, it is initialized to a new dictionary receiving any excess keyword arguments, defaulting to a new empty dictionary.
Also, see Function Calls.
Assuming that one knows what positional and keyword arguments are, here are some examples:
Example 1:
# Excess keyword argument (python 3) example:
def foo(a, b, c, **args):
print("a = %s" % (a,))
print("b = %s" % (b,))
print("c = %s" % (c,))
print(args)
foo(a="testa", d="excess", c="testc", b="testb", k="another_excess")
As you can see in the above example, we only have parameters a, b, c in the signature of the foo function. Since d and k are not present, they are put into the args dictionary. The output of the program is:
a = testa
b = testb
c = testc
{'k': 'another_excess', 'd': 'excess'}
Example 2:
# Excess positional argument (python 3) example:
def foo(a, b, c, *args):
print("a = %s" % (a,))
print("b = %s" % (b,))
print("c = %s" % (c,))
print(args)
foo("testa", "testb", "testc", "excess", "another_excess")
Here, since we're testing positional arguments, the excess ones have to be on the end, and *args packs them into a tuple, so the output of this program is:
a = testa
b = testb
c = testc
('excess', 'another_excess')
You can also unpack a dictionary or a tuple into arguments of a function:
def foo(a,b,c,**args):
print("a=%s" % (a,))
print("b=%s" % (b,))
print("c=%s" % (c,))
print("args=%s" % (args,))
argdict = dict(a="testa", b="testb", c="testc", excessarg="string")
foo(**argdict)
Prints:
a=testa
b=testb
c=testc
args={'excessarg': 'string'}
And
def foo(a,b,c,*args):
print("a=%s" % (a,))
print("b=%s" % (b,))
print("c=%s" % (c,))
print("args=%s" % (args,))
argtuple = ("testa","testb","testc","excess")
foo(*argtuple)
Prints:
a=testa
b=testb
c=testc
args=('excess',)
Answer from S.Lott on Stack OverflowSee Function Definitions in the Language Reference.
If the form
*identifieris present, it is initialized to a tuple receiving any excess positional parameters, defaulting to the empty tuple. If the form**identifieris present, it is initialized to a new dictionary receiving any excess keyword arguments, defaulting to a new empty dictionary.
Also, see Function Calls.
Assuming that one knows what positional and keyword arguments are, here are some examples:
Example 1:
# Excess keyword argument (python 3) example:
def foo(a, b, c, **args):
print("a = %s" % (a,))
print("b = %s" % (b,))
print("c = %s" % (c,))
print(args)
foo(a="testa", d="excess", c="testc", b="testb", k="another_excess")
As you can see in the above example, we only have parameters a, b, c in the signature of the foo function. Since d and k are not present, they are put into the args dictionary. The output of the program is:
a = testa
b = testb
c = testc
{'k': 'another_excess', 'd': 'excess'}
Example 2:
# Excess positional argument (python 3) example:
def foo(a, b, c, *args):
print("a = %s" % (a,))
print("b = %s" % (b,))
print("c = %s" % (c,))
print(args)
foo("testa", "testb", "testc", "excess", "another_excess")
Here, since we're testing positional arguments, the excess ones have to be on the end, and *args packs them into a tuple, so the output of this program is:
a = testa
b = testb
c = testc
('excess', 'another_excess')
You can also unpack a dictionary or a tuple into arguments of a function:
def foo(a,b,c,**args):
print("a=%s" % (a,))
print("b=%s" % (b,))
print("c=%s" % (c,))
print("args=%s" % (args,))
argdict = dict(a="testa", b="testb", c="testc", excessarg="string")
foo(**argdict)
Prints:
a=testa
b=testb
c=testc
args={'excessarg': 'string'}
And
def foo(a,b,c,*args):
print("a=%s" % (a,))
print("b=%s" % (b,))
print("c=%s" % (c,))
print("args=%s" % (args,))
argtuple = ("testa","testb","testc","excess")
foo(*argtuple)
Prints:
a=testa
b=testb
c=testc
args=('excess',)
I only have one thing to add that wasn't clear from the other answers (for completeness's sake).
You may also use the stars when calling the function. For example, say you have code like this:
>>> def foo(*args):
... print(args)
...
>>> l = [1,2,3,4,5]
You can pass the list l into foo like so...
>>> foo(*l)
(1, 2, 3, 4, 5)
You can do the same for dictionaries...
>>> def foo(**argd):
... print(argd)
...
>>> d = {'a' : 'b', 'c' : 'd'}
>>> foo(**d)
{'a': 'b', 'c': 'd'}
import os
from datetime import date
def program():
Year = input("year of birth:" )
Month = input("month of birth:" )
Day = input("day of birth:" )
Date_of_Birth = (Day + "/" + Month + "/" + Year)
print('Your Date of Birth is ' + Date_of_Birth)
d = date.today()
y = d.year
os.system("cls")
age = y - int(Year)
print('Your age is ' + str(age))
if ((int(Month)==12 and int(Day) >= 22)or(int(Month)==1 and int(Day)<= 19)):
Signo_Zodiacal = ("\n Capricorn")
elif ((int(Month)==1 and int(Day) >= 20)or(int(Month)==2 and int(Day)<= 17)):
zodiac_sign = ("\n aquarium")
elif ((int(Month)==2 and int(Day) >= 18)or(int(Month)==3 and int(Day)<= 19)):
zodiac_sign = ("\n Pices")
elif ((int(Month)==3 and int(Day) >= 20)or(int(Month)==4 and int(Day)<= 19)):
zodiac_sign = ("\n Aries")
elif ((int(Month)==4 and int(Day) >= 20)or(int(Month)==5 and int(Day)<= 20)):
zodiac_sign = ("\n Taurus")
elif ((int(Month)==5 and int(Day) >= 21)or(int(Month)==6 and int(Day)<= 20)):
zodiac_sign = ("\n Gemini")
elif ((int(Month)==6 and int(Day) >= 21)or(int(Month)==7 and int(Day)<= 22)):
zodiac_sign = ("\n Cancer")
elif ((int(Month)==7 and int(Day) >= 23)or(int(Month)==8 and int(Day)<= 22)):
zodiac_sign = ("\n Leo")
elif ((int(Month)==8 and int(Day) >= 23)or(int(Month)==9 and int(Day)<= 22)):
Signo_Zodiacal = ("\n Virgo")
elif ((int(Month)==9 and int(Day) >= 23)or(int(Month)==10 and int(Day)<= 22)):
zodiac_sign = ("\n Libra")
elif ((int(Month)==10 and int(Day) >= 23)or(int(Month)==11 and int(Day)<= 21)):
zodiac_sign = ("\n Scorpio")
elif ((int(Month)==11 and int(Day) >= 22)or(int(Month)==12 and int(Day)<= 21)):
zodiac_sign = ("\n Sagittarius")
print(zodiac_sign)
program()
fixed by me
def again():
print("")
print("Please check you month")
print("Month must be the following")
print("01 - January")
print("02 - Febuary")
print("03 - March")
print("04 - April")
print("05 - May")
print("06 - Jun")
print("07 - Jully")
print("08 - August")
print("09 - September")
print("10 - October")
print("11 - Novemver")
print("12 - December")
print("")
def zodiac():
month = input("Month of birth(eg. 01,04,,12):")
day = int(input("Day of birth:"))
bday = ( month + "/" + str(day))
if (int(month) > 12):
again()
zodiac()
elif month == "01":
if (day > 31):
print("")
print("Invalid Date")
print("Please try again!")
print("")
zodiac()
elif (day <= 20):
print("Your Birthday is(mm/dd):",bday)
print("Then your zodiac sign is Capricorn!")
else:
print("Your Birthday is(mm/dd):",bday)
print("Then your zodiac sign is Aquarius")
elif month == "02":
if (day >28):
print("")
print("Invalid Date")
print("Please try again")
print("")
zodiac()
elif (day <= 18):
print("Your Birthday is(mm/dd):",bday)
print("Then your zodiac sign is Aquarius")
else:
print("Your Birthday is(mm/dd):",bday)
print("Then your zodiac sign is Pisces")
elif month == "03":
if (day > 31):
print("")
print("Invalid Date")
print("Please try again!")
print("")
zodiac()
elif (day <= 20):
print("Your Birthday is(mm/dd):",bday)
print("Then your zodiac sign is Pisces")
else:
print("Your Birthday is(mm/dd):",bday)
print("Then your zodiac sign is Aries")
elif month == "04":
if (day > 30):
print("")
print("Invalid Date")
print("Please try again!")
print("")
zodiac()
elif (day <= 20):
print("Your Birthday is(mm/dd):",bday)
print("Then your zodiac sign is Aries")
else:
print("Your Birthday is(mm/dd):",bday)
print("Then your zodiac sign is Taurus")
elif month == "05":
if (day > 31):
print("")
print("Invalid Date")
print("Please try again!")
print("")
zodiac()
elif (day <= 20):
print("Your Birthday is(mm/dd):",bday)
print("Then your zodiac sign is Taurus")
else:
print("Your Birthday is(mm/dd):",bday)
print("Then your zodiac sign is Gemini")
elif month == "06":
if (day > 30):
print("")
print("Invalid Date")
print("Please try again!")
print("")
zodiac()
elif (day <= 21):
print("Your Birthday is(mm/dd):",bday)
print("Then your zodiac sign is Gemini")
else:
print("Your Birthday is(mm/dd):",bday)
print("Then your zodiac sign is Cancer")
elif month == "07":
if (day > 31):
print("")
print("Invalid Date")
print("Please try again!")
print("")
zodiac()
elif (day <= 22):
print("Your Birthday is(mm/dd):",bday)
print("Then your zodiac sign is Cancer")
else:
print("Your Birthday is(mm/dd):",bday)
print("Then your zodiac sign is Leo")
elif month == "08":
if (day > 31):
print("")
print("Invalid Date")
print("Please try again!")
print("")
zodiac()
elif (day <=23):
print("Your Birthday is(mm/dd):",bday)
print("Then your zodiac sign is Leo")
else:
print("Your Birthday is(mm/dd):",bday)
print("Then your zodiac sign is Virgo")
elif month == "09":
if (day > 30):
print("")
print("Invalid Date")
print("Please try again!")
print("")
zodiac()
elif (day <= 23):
print("Your Birthday is(mm/dd):",bday)
print("Then your zodiac sign is Virgo")
else:
print("Your Birthday is(mm/dd):",bday)
print("Then your zodiac sign is Libra")
elif month == "10":
if (day > 31):
print("")
print("Invalid Date")
print("Please try again!")
print("")
zodiac()
elif (day <= 23):
print("Your Birthday is(mm/dd):",bday)
print("Then your zodiac sign is Libra")
else:
print("Your Birthday is(mm/dd):",bday)
print("Then your zodiac sign is Scorpio")
elif month == "11":
if (day > 30):
print("")
print("Invalid Date")
print("Please try again!")
print("")
zodiac()
elif (day <= 23):
print("Your Birthday is(mm/dd):",bday)
print("Then your zodiac sign is Scorpio")
else:
print("Your Birthday is(mm/dd):",bday)
print("Then your zodiac sign is Sagittarius")
elif month == "12":
if (day > 31):
print("")
print("Invalid Date")
print("Please try again!")
print("")
zodiac()
elif (day <= 21):
print("Your Birthday is(mm/dd):",bday)
print("Then your zodiac sign is Sagittarius")
else:
print("Your Birthday is(mm/dd):",bday)
print("Then your zodiac sign is Capricorn")
else:
print("")
again()
zodiac()
zodiac()
print("")
again = input("Type 'zodiac' if you want to try again: ")
if (again == "zodiac"):
zodiac()
The *args and **kwargs are common idioms to allow an arbitrary number of arguments to functions, as described in the section more on defining functions in the Python tutorial.
The *args will give you all positional arguments as a tuple:
def foo(*args):
for a in args:
print(a)
foo(1)
# 1
foo(1, 2, 3)
# 1
# 2
# 3
The **kwargs will give you all
keyword arguments as a dictionary:
def bar(**kwargs):
for a in kwargs:
print(a, kwargs[a])
bar(name='one', age=27)
# name one
# age 27
Both idioms can be mixed with normal arguments to allow a set of fixed and some variable arguments:
def foo(kind, *args, bar=None, **kwargs):
print(kind, args, bar, kwargs)
foo(123, 'a', 'b', apple='red')
# 123 ('a', 'b') None {'apple': 'red'}
It is also possible to use this the other way around:
def foo(a, b, c):
print(a, b, c)
obj = {'b':10, 'c':'lee'}
foo(100, **obj)
# 100 10 lee
Another usage of the *l idiom is to unpack argument lists when calling a function.
def foo(bar, lee):
print(bar, lee)
baz = [1, 2]
foo(*baz)
# 1 2
In Python 3 it is possible to use *l on the left side of an assignment (Extended Iterable Unpacking), though it gives a list instead of a tuple in this context:
first, *rest = [1, 2, 3, 4]
# first = 1
# rest = [2, 3, 4]
Also Python 3 adds a new semantic (refer PEP 3102):
def func(arg1, arg2, arg3, *, kwarg1, kwarg2):
pass
Such function accepts only 3 positional arguments, and everything after * can only be passed as keyword arguments.
Note:
A Python dict, semantically used for keyword argument passing, is arbitrarily ordered. However, in Python 3.6+, keyword arguments are guaranteed to remember insertion order.
"The order of elements in **kwargs now corresponds to the order in which keyword arguments were passed to the function." - What’s New In Python 3.6.
In fact, all dicts in CPython 3.6 will remember insertion order as an implementation detail, and this becomes standard in Python 3.7.
It's also worth noting that you can use * and ** when calling functions as well. This is a shortcut that allows you to pass multiple arguments to a function directly using either a list/tuple or a dictionary. For example, if you have the following function:
def foo(x,y,z):
print("x=" + str(x))
print("y=" + str(y))
print("z=" + str(z))
You can do things like:
>>> mylist = [1,2,3]
>>> foo(*mylist)
x=1
y=2
z=3
>>> mydict = {'x':1,'y':2,'z':3}
>>> foo(**mydict)
x=1
y=2
z=3
>>> mytuple = (1, 2, 3)
>>> foo(*mytuple)
x=1
y=2
z=3
Note: The keys in mydict have to be named exactly like the parameters of function foo. Otherwise it will throw a TypeError:
>>> mydict = {'x':1,'y':2,'z':3,'badnews':9}
>>> foo(**mydict)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foo() got an unexpected keyword argument 'badnews'
I've done this before. The simplest solution that I ended up with was an array of the following key/values:
120:Cap, 218:Aqu, 320:Pis, 420:Ari, 521:Tau,
621:Gem, 722:Can, 823:Leo, 923:Vir, 1023:Lib
1122:Sco, 1222:Sag, 1231: Cap
Then you write the birth date in the mdd format, ie, month number (starting with 1 for January) and two digit day number (01-31). Iterate through the array, and if the date is less than or equal to an item in the array, you have your star sign.
EDIT I needed this so here's this concept as a working function
zodiacs = [(120, 'Cap'), (218, 'Aqu'), (320, 'Pis'), (420, 'Ari'), (521, 'Tau'),
(621, 'Gem'), (722, 'Can'), (823, 'Leo'), (923, 'Vir'), (1023, 'Lib'),
(1122, 'Sco'), (1222, 'Sag'), (1231, 'Cap')]
def get_zodiac_of_date(date):
date_number = int("".join((str(date.date().month), '%02d' % date.date().day)))
for z in zodiacs:
if date_number <= z[0]:
return z[1]
You could give them some more information about position of the planets and the stars.
import ephem
>>> u = ephem.Uranus()
>>> u.compute('1871/3/13')
>>> print u.ra, u.dec, u.mag
7:38:06.27 22:04:47.4 5.46
>>> print ephem.constellation(u)
('Gem', 'Gemini')
» pip install zodiac-sign
A single star * unpacks a sequence or collection into positional arguments. Suppose we have
def add(a, b):
return a + b
values = (1, 2)
Using the * unpacking operator, we can write s = add(*values), which will be equivalent to writing s = add(1, 2).
The double star ** does the same thing for a dictionary, providing values for named arguments:
values = {'a': 1, 'b': 2}
s = add(**values) # equivalent to add(a=1, b=2)
Both operators can be used for the same function call. For example, given:
def sum(a, b, c, d):
return a + b + c + d
values1 = (1, 2)
values2 = {'c': 10, 'd': 15}
then s = add(*values1, **values2) is equivalent to s = sum(1, 2, c=10, d=15).
See also the relevant section of the tutorial in the Python documentation.
Similarly, * and ** can be used for parameters. Using * allows a function to accept any number of positional arguments, which will be collected into a single parameter:
def add(*values):
s = 0
for v in values:
s = s + v
return s
Now when the function is called like s = add(1, 2, 3, 4, 5), values will be the tuple (1, 2, 3, 4, 5) (which, of course, produces the result 15).
Similarly, a parameter marked with ** will receive a dict:
def get_a(**values):
return values['a']
s = get_a(a=1, b=2) # returns 1
this allows for specifying a large number of optional parameters without having to declare them.
Again, both can be combined:
def add(*values, **options):
s = 0
for i in values:
s = s + i
if "neg" in options:
if options["neg"]:
s = -s
return s
s = add(1, 2, 3, 4, 5) # returns 15
s = add(1, 2, 3, 4, 5, neg=True) # returns -15
s = add(1, 2, 3, 4, 5, neg=False) # returns 15
In a function call, the single star turns a list into separate arguments (e.g. zip(*x) is the same as zip(x1, x2, x3) given x=[x1,x2,x3]) and the double star turns a dictionary into separate keyword arguments (e.g. f(**k) is the same as f(x=my_x, y=my_y) given k = {'x':my_x, 'y':my_y}.
In a function definition, it's the other way around: the single star turns an arbitrary number of arguments into a list, and the double start turns an arbitrary number of keyword arguments into a dictionary. E.g. def foo(*x) means "foo takes an arbitrary number of arguments and they will be accessible through x (i.e. if the user calls foo(1,2,3), x will be (1, 2, 3))" and def bar(**k) means "bar takes an arbitrary number of keyword arguments and they will be accessible through k (i.e. if the user calls bar(x=42, y=23), k will be {'x': 42, 'y': 23})".