[PYTHON] HR grabs programming # 2 Variables

It's Obon! I'm off work, but I live in Tokyo and can't go out, so I'm doing my best in programming at home.

See the previous article for the background. https://qiita.com/Ayanaru/items/87d5516f7005d24bf0ea

This time, a variable.

What is a variable?

A variable is like a hako to which you can assign a value. It seems to be useful in various ways. This time we will approach its charm.

You can name the data

For example, one person was X yen and Y people. How much is the total? Total amount = X x Y If you write this in Python, it will look like this.

total_price = price * count

Variable names can be set freely and can be expressed in an easy-to-understand manner using English words. Things like X and Y that can be assigned this value are called "variables".

For example, let's say you want to create a system that calculates the amount of money you collect at a drinking party each time. If there are 30 people for 3000 yen per person, enter it and output only the total amount of "90000".

price = 3000 #User enters the amount
people = 30  #User enters the number of people
total_price = price * people  #Variables are assigned to expressions
print(total_price)  #"90000" is displayed

Substituting another value after this will overwrite it. Next, let's make 10 people for 5000 yen per person. Let's display the sentence "Today's bill is 50,000 yen."

price = 5000
people = 10
total_price = price * people
print(total_price)  #"50000" is displayed

You can also apply what you learned last time to write the display.

print ('Today's accounting' + str(total_price) + 'It is a circle.')
#"Today's bill is 50,000 yen." Is displayed.

str is an abbreviation for string. It means "character string". ** If there is a numerical value in the sentence you want to output, use str (). ** **

The same value can be used repeatedly

For example, calculating the area of a square

length = 5 #One side length
area = length * length #Formula for calculating the area
print(area)  #25

Even if the number becomes large, if you enter the number on one side, the area will be output. Eliminates the need to repeatedly enter large numbers.

length = 123456 
area = length * length
print(area)  #15241383936

I don't really realize it when I look at only simple examples, so I asked again when engineers actually use variables.

Benefits of using variables

If you want to read the same data over and over again on your website, you end up entering that data in multiple places. Also, if that data changes, you'll have to update the same thing in multiple places.

But if you use variables, you only have to fix the first defined variable, that is, fix one place and all the rest will be reflected! !!

With this alone, I could imagine that programming would be very useful when repeating huge amounts of data and complex calculations.

That's it for this time. Thank you for reading until the end.

Recommended Posts

HR grabs programming # 2 Variables