In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article focuses on "the basic use of python variables", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "the basic usage of python variables".
Basic use of variables
Programs are used to process data, and variables are used to store data.
target
Variable definition
Type of variable
Naming of variables
01. Variable definition
In Python, each variable must be assigned before it is used, and the variable will not be created until the variable is assigned
The equal sign (=) is used to assign a value to a variable * = on the left is a variable name * = on the right is the value stored in the variable
Variable name = value
After the variable is defined, it can be used directly later.
1) variable exercise 1-the variable iPython# defines qq_number is used to save the qq number In [1]: qq_number = "1234567" # output content saved in qq_number In [2]: qq_numberOut [2]: '1234567 definition # variable used to store qq password In [3]: qq_password = "123" # output content stored in qq_password In [4]: qq_passwordOut [4]:' 123'
In an interactive way, if you want to view the contents of a variable, you can enter the variable name directly without using the print function.
2) variable exercise 2-- PyCharm# defines qq number variable qq_number = "1234567" # defines qq password variable qq_password = "123" # in the program, if you want to output the contents of the variable, you need to use the print function print (qq_number) print (qq_password)
Use the interpreter to execute, and if you want to output the contents of a variable, you must use the print function
3) variable exercise 3-- buy apples in the supermarket
You can use the calculation results of other variables to define variables
After the variable is defined, it can be used directly later.
Demand
The price of apples is 8.5 yuan per jin.
Bought 7.5 jin of apples.
Calculate the amount of payment
# define Apple price variable price = 8.00 define purchase weight weight = 7.0calculated amount money = price * weightprint (money) thinking question
If you just buy an apple, you will return 5 yuan.
Please recalculate the purchase amount
# define the Apple price variable price = 8.00 define the purchase weight weight = 7.0calculated amount money = price * weight# if you buy an apple, you will return 5 yuan money = money-5print (money)
Ask a question
How many variables are defined in the above code? * three: price/weight/money
Is money = money-5 defining new variables or using variables? * directly use the previously defined variable * the variable name is defined only when it appears for the first time * the variable name appears again, not to define the variable, but to use the previously defined variable directly.
In program development, can you modify the values saved in the previously defined variables? * can * the value stored in the variable can be changed
02. Type of variable
Create a variable in memory that includes: 1. The name of the variable 2. The data stored in the variable 3. Variable stores the type of data 4. The address of the variable (marked)
2.1 Walkthrough of variable types-personal information
Demand
Define variables to save Xiao Ming's personal information
Name: Xiao Ming
Age: 18
Gender: male
Height: 1.75m
Weight: 75.0 kg
Use single-step debugging to confirm the type of data saved in the variable
Ask a question
How many data types are there in the walkthrough? * 4 kinds of * str-string * bool-Boolean (true or false) * int-integer * float-floating point number (decimal)
Do you need to specify a type when defining variables in Python? * not necessary * Python can automatically deduce the type of data stored in the variable according to the value to the right of the = equal sign
2.2 types of variables
It is not necessary to specify a type to define a variable in Python (required in many other high-level languages)
Data types can be divided into digital and non-digital types.
Digital * integer (int) * floating point (float) * Boolean (bool) * true True non-zero-true * false False 0 * complex (complex) * is mainly used in scientific calculations, such as plane field problems, wave problems, inductance and capacitance problems, etc.
Non-numeric * string * list * tuple * dictionary
Tip: in Python 2.x, integers are also divided into:
* int (integer) * long (long integer)
Use the type function to view the type of a variable
In [1]: type (name) 2.3 calculation between different types of variables 1) numeric variables can be calculated directly
In Python, two numeric variables can be calculated directly.
If the variable is of type bool, the number corresponding to * True is 1 * False and the corresponding number is 0.
Rehearsal steps
Define the integer I = 10
Define floating point number f = 10.5
Define Boolean b = True
In iPython, the above three variables are used to perform arithmetic operations on each other.
2) use + concatenation strings between string variables
In Python, you can use + splicing between strings to generate new strings
In [1]: first_name = "three" In [2]: last_name = "Zhang" In [3]: first_name + last_nameOut [3]: 'three' 3) string variables can be used as integers * to repeatedly concatenate the same string In [1]: "-" * 50Out [1]:'- -'4) No other calculations can be performed between numeric variables and strings In [1]: first_name = "zhang" In [2]: X = 10In [3]: X + first_name-- -- TypeError: unsupported operand type (s) for +: 'int' and' str' type error: `+` unsupported operation types: input of `int` and `str`2.4 variables
The so-called input is to use code to obtain the information entered by the user through the keyboard.
For example, go to the bank to withdraw money and enter the password on ATM
In Python, if you want to get the user's input information on the keyboard, you need to use the input function
1) about functions
A pre-prepared feature (code written by others or yourself) that can be used directly without paying attention to internal details
Functions that have been learned so far
Function description print (x) outputs x to the console type (x) View the variable type of x 2) input function realizes keyboard input
In Python, you can use the input function to wait for user input from the keyboard
Anything entered by the user is considered to be a string by Python
The syntax is as follows:
String variable = input ("hint:") 3) Type conversion function description int (x) converts x to an integer float (x) converts x to a floating point number 4) variable input exercise-supermarket Buy Apple enhanced version
Demand
The cashier enters the price of the apple, unit: yuan / jin
The cashier enters the weight of the apple purchased by the user, in jin
Calculate and output the payment amount
Exercise method 1. Enter Apple unit price price_str = input ("Please enter Apple price:") # 2. Require Apple weight weight_str = input ("Please enter Apple weight:") # 3. Calculate amount # 1 > convert Apple unit price to decimal price = float (price_str) # 2 > convert Apple weight to decimal weight = float (weight_str) # 3 > calculate payment amount money = price * weightprint (money)
Ask a question
In the drill, how many variables are defined for the price? * two * price_str records the price string entered by the user * price records the converted price values
Think about it-is it convenient for users to enter many numbers through the console and define two variables for each number in development?
Exercise method 2-buy an improved version of Apple
When a floating-point variable is defined to receive user input, the float function is used for conversion
Price = float (input ("Please enter price:")
Benefits of the improvement:
Save space, you only need to allocate space for one variable
It is convenient to name, and there is no need to name intermediate variables.
Improved "shortcomings":
Beginners need to know that the two functions can be used in nesting, which is slightly more difficult.
Prompt
If you do not enter a number, there will be errors in the execution of the program. The advanced topic about data conversion will be discussed later!
2.5 formatted output of variables
The unit price of Apple is 9.00 yuan per jin. If you buy 5.00 jin, you need to pay 45.00 yuan.
In Python, you can use the print function to output information to the console.
If you want to output text information as well as data, you need to use the formatting operator
% is called the format operator and is specially used to deal with the format * containing% in the string, which is called the format string *% and is used in conjunction with different characters. Different types of data need to use different format characters.
Format character meaning% s string% d signed decimal integer, d represents output integer display digits, deficiency uses 0 to complete% f floating point,% .2f indicates that only two%% output% is displayed after the decimal point.
The syntax format is as follows:
Print (format string% variable 1) print (format string% (variable 1, variable 2...)) Formatting output walkthrough-basic exercise
Demand
Define string variable name, output my name is Xiaoming, please take care of me!
Define integer variable student_no, output my student number is 000001
Define decimal price, weight, money, export apple unit price 9.00 yuan / jin, buy 5.00 jin, need to pay 45.00 yuan
Define a decimal scale, the output data ratio is 10.00%
Print ("my name is% s, please take care of me!" % name) print ("my student number is d"% student_no) print ("Apple unit price% .02f / jin, purchase% .02f jin, need to pay% .02f yuan"% (price, weight, money)) print ("data ratio is% .02f%"% (scale * 100)) after-class exercises-personal business cards
Demand
Prompt the user for input in the console: name, company, position, phone number, mailbox
Output in the following format:
* * Company name (position) Tel: email: email * *
The implementation code is as follows:
"name = input (" Please enter name: ") company = input (" Please enter name: ") title = input (" Please enter position: ") phone = input (" Please enter phone: ") email = input (" Please enter email: ") print (" * "* 50) print (company) print () print ("% s (% s) "% (name) Title) print () print ("phone:% s"% phone) print ("mailbox:% s"% email) print ("*" * 50) so far I believe you have a deeper understanding of "the basic use of python variables", so you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.