Python Variable Usage, Types, and Naming Conventions
This tutorial explains how to read user input into a variable, print it, handle type conversion for arithmetic, check variable types, convert between types, and follow proper naming rules for Python variables.
1. Using Variables: The following code reads a number the user thinks of and prints it.
<code>number = input("你想到了什么数字? ")
print("你想到的数字是:", number)</code>The first line uses input() to read console input into the variable number , and the second line prints the variable's value.
2. Variable Types: To output the square of the number, the code number * number would raise an error because input() returns a string. Converting the string to an integer with int() resolves the issue.
<code>number = input("你想到了什么数字? ")
print("你想到数字的平方是:", int(number) * int(number))</code>Common Python variable types include:
int: arbitrary-size integers
float: arbitrary-precision floating‑point numbers
str: text strings
bool: True or False
complex: complex numbers (real + imag)
3. Checking Variable Types: The type() function can be used to inspect a variable's type.
<code>var_1 = 3
var_2 = 3.1415926
var_3 = 2 + 1j
var_4 = "Hello World"
var_5 = True
print(type(var_1)) # <class 'int'>
print(type(var_2)) # <class 'float'>
print(type(var_3)) # <class 'complex'>
print(type(var_4)) # <class 'str'>
print(type(var_5)) # <class 'bool'>
</code>4. Type Conversion: Functions like int() and str() can convert values between types.
<code>var = 3.1415926
print(type(int(var)), int(var)) # <class 'int'> 3
print(type(str(var)), str(var)) # <class 'str'> 3.1415926
</code>5. Variable Naming Rules: Variable names must start with a letter or underscore and consist of letters, digits, or underscores; they cannot be Python keywords. The convention is lowercase with underscores (e.g., this_is_variable ), while global constants are uppercase.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.