Python Fundamentals: Input, Variables, and Control Structures
Print Function
The print() function displays content within parentheses:
- Without quotes: Evaluates and prints numbers/expressions
print(3 * 4) - With single/double quotes: Prints strings literally
print("Hello World") - Triple quotes: Preserves multi-line formatting
print('''Line 1\nLine 2''')
User Input
The input() function captures keyboard input:
username = input('Enter your username: ')
print(f"Welcome {username}")
Note: input() always returns string type in Python 3.
Variables and Assignment
counter = 10
message = "Processing"
print(counter, message)
Naming Conventions
- Use descriptive single words
- Only alphanumeric characters and underscores
- Cannot start with numbers
- Avoid Python keywords
Chekcing Keywords
import keyword
print(keyword.iskeyword('for')) # Returns True
print(keyword.kwlist) # Lists all Python keywords
Conditional Statements
if temperature > 30:
print("Hot day")
elif temperature > 20:
print("Pleasant weather")
else:
print("Cool day")
Data Types Overview
- str: Textual data
- int: Whole numbers
- float: Decimal numbers
- bool: True/False values
- list: Ordered mutable sequences
- dict: Key-value pairs
- tuple: Immutable sequences
Floating-Point Precision
print(0.1 + 0.2) # Output: 0.30000000000000004
Data Operations
String Formatting
name = "Alice"
age = 25
print(f"{name} is {age} years old")
Type Conversion
num_str = "123"
num_int = int(num_str)
print(type(num_int)) # <class 'int'>
List Operations
colors = ['red', 'green', 'blue']
colors.append('yellow')
print(colors[1:3]) # ['green', 'blue']
Dictionary Methods
user = {'name': 'Bob', 'age': 30}
print(user.keys()) # dict_keys(['name', 'age'])
user['email'] = 'bob@example.com'
Loop Structures
For Loops
for i in range(1, 6):
print(i ** 2)
While Loops
count = 3
while count > 0:
print(count)
count -= 1
Loop Control
for num in range(10):
if num % 2 == 0:
continue
print(num)