Installnig Packages with pip
pip install -i https://pypi.douban.com/simple package_name
Variables and Data Types
Defining Variables
In programming, variables act as containers to store data. For example, when adding two numbers, you first store them in variables and then perform the operation.
value_one = 100
value_two = 87
total = value_one + value_two
Variable Types
Python automatically determines a variable's type based on the assigned value. Use the type() function to check the type.
Identifiers and Keywords
Identifiers
Identifiers are user-defined names for variables, functions, etc. They must start with a letter or underscore and can contain letters, digits, and underscores.
Examples of valid and invalid identifiers:
fromNo12 # Valid
from#12 # Invalid (contains #)
my_Boolean # Valid
my-Boolean # Invalid (contains -)
Naming Conventions
- Use descriptive names (e.g.,
student_nameinstead ofsn) - Common styles: camelCase, PascalCase, snake_case
Keywords
Keywords are reserved words in Python. You cannot use them as identifiers.
and, as, assert, break, class, continue, def, del, elif, else, except,
exec, finally, for, from, global, if, import, in, is, lambda, not, or,
pass, print, raise, return, try, while, with, yield
Output and Formatting
Basic Output
print('Hello, world!')
print('Welcome to Python programming')
Formatted Output
Use placeholders like %s for strings and %d for integers.
name = 'Alice'
age = 25
print('Name: %s, Age: %d' % (name, age))
Common Format Specifiers
| Specifier | Usage |
|---|---|
| %s | String |
| %d | Integer |
| %f | Float |
Newline Output
print('Line one\nLine two')
User Input
In Python 3, use input() to read user input. It returns a string.
user_input = input('Enter your name: ')
print('Hello, ' + user_input)
Operators
Arithmetic Operators
a = 10
b = 3
print(a + b) # Addition
print(a - b) # Subtraction
print(a * b) # Multiplication
print(a / b) # Division
print(a // b) # Floor division
print(a % b) # Modulus
print(a ** b) # Exponentiation
Assignment Operators
x = 5
x += 3 # Equivalent to x = x + 3
Type Conversion
Convert between types using functions like int(), str(), float().
num_str = '42'
num_int = int(num_str)
print(num_int + 10) # Output: 52
Conditional Statements
if Statement
user_age = 20
if user_age >= 18:
print('Access granted')
Comparison and Logical Operators
a = 5
b = 10
if a < b and b > 0:
print('Conditions met')