0

*asterisk symbol,python

Asterisk symbol is sometimes used for multiplication and sometimes for repetition, how can we identify its purpose? 4*'2' -------;O/p:-2222 spam=2 eggs=3 del spam eggs=4 spam=5 print (spam*eggs) ---;;;O/p:-20

27th Jul 2020, 6:22 PM
Yukthamukhi Rudra
Yukthamukhi Rudra - avatar
6 Answers
+ 3
If both numbers are integers it will result in ,for say 4*5=20 but if one is string "4"*5,it will result in 44444
27th Jul 2020, 6:29 PM
Abhay
Abhay - avatar
+ 9
It's basic meaning is multiplication only. The difference is that whenever you multiply an integer to integer, it gives the result. Like: print(4*3) # prints 12 because it's an integer. Unlike integers, whenever you multiply a string with a number, it doesn't gives the result (As strings cannot be multiplied by number) So, whenever you'll multiply a string with an integer, Python understands it to print it that particular number of times. For example: print(4*"2") #prints 2222 because double quotes with anything written make it as a string in python.
27th Jul 2020, 6:33 PM
Arctic Fox
Arctic Fox - avatar
+ 4
In Python, for every datatype you can define separately what a certain operator does. That's called 'operator overload' and is realized by 'magic methods', which you will learn about later. The important point for now is to remember that there is no fundamental meaning of *, but it means something different for every type. With numbers, it means what it means in maths, for example: 5 times 7. So 35. With strings, it means what it would mean at a printer's or something: Print 5 times that word. So 3 * 'hi' means 'hihihi'. That's just how the creator of Python decided it should be done. It could be anything else - and can be, as soon as you define your own datatypes. Btw, there are more use cases for *, in case you want to make wide eyes: https://www.sololearn.com/discuss/1695602/?ref=app
27th Jul 2020, 7:13 PM
HonFu
HonFu - avatar
+ 3
In strings, it is only defined for str and int. If you want to multiply a number with a string, you need to first convert the string with int or float. (In other languages, like Java or Javascript, it is defined differently.)
27th Jul 2020, 7:40 PM
HonFu
HonFu - avatar
+ 1
Thankyou 🙏
27th Jul 2020, 6:30 PM
Yukthamukhi Rudra
Yukthamukhi Rudra - avatar
+ 1
For Numbers it multiply, For String also same but assume as repeatations.. For iterables, it works like a pointer in C.. Like List = list(range(10)) print(*List) Prints 0 to 9..
27th Jul 2020, 7:13 PM
Jayakrishna 🇼🇳