1. Comments
- Single-line comment:
# comment - Multi-line comment:
"""comment"""or'''comment'''
2. Variables
- Purpose: A variable is a name that references the memory address where data is stored.
- Defining a variable:
- Format:
variable_name = value - Identifiers: composed of letters, digits, and underscores; cannot start with a digit; cannot use keywords; case-sensitive.
- Naming conventions:
- Meaningful names
- PascalCase: first letter of each word capitalized
- camelCase: first word lowercase, subsequent words capitalized
- snake_case: words separated by underscores (e.g.,
my_name)
- Format:
- Data types:
int,float,bool(True/False),str,list,tuple,set,dict
number1 = 1 # int
decimal1 = 1.1 # float
greeting = 'hello world' # str
flag = True # bool
list_data = [10, 20, 30] # list
tuple_data = (10, 20, 30) # tuple
set_data = {10, 20, 30} # set
dict_data = {'name': 'Amy', 'age': 18} # dict
3. Output
- Formatted output:
%s– string,%d– signed decimal integer,%f– float,%c– charcater
name = 'Amy'
age = 18
gender = 'female'
weight = 55.5
print('This year I am %d years old' % age)
print('My name is %s' % name)
print('My gender is %s' % gender)
print('This year I am %d years old, but next year I will be %d' % (age, age+1))
print('I am %s, this year I weigh %f kg, but I plan to lose 5 kg, so next year I will be %f kg' % (name, weight, weight-5))
- Formatting digits:
%06d– pad integer with zeros to at least 6 digits%.2f– show 2 decimal places
- f-strings:
f'{expression}'
print(f'My name is {name}, next year I will be {age+1} years old')
- Escape characters:
\n– newline\t– tab
print('hello\nworld')
print('hello\tworld')
Output:
hello
world
hello world
- End character: By default,
print()ends with\n. You can change it usingend=:
print('hello', end="\n")
print('world', end="\t")
print('hello', end="...")
print('Python') # default end="\n"
Output:
hello
world hello...Python
4. Input
- Syntax:
input('prompt: ') - Characteristics:
- Execution pauses until user provides input.
- Input is usually stored in a variable.
input()always returns a string.
password = input('Please enter your password: ')
print(f'Your password is {password}')
print(type(password))
5. Type Conversion
- Syntax:
new_type(variable)
number = input('Enter a number: ') # user enters 1
print(type(number)) # <class 'str'>
print(type(int(number))) # <class 'int'>
value1 = 1
value2 = '10'
print(float(value1)) # 1.0
print(float(value2)) # 10.0
- Type conversion works only if the string contains a valid representation of the target type.