Docsity

Intro to Python Programming, Cheat Sheet of Introduction to Computers

Toggle sidebar
bg1
Introduction to Python Programming
A beginner-friendly reference guide
1. Variables and Data Types
Python is dynamically typed โ€“ you do not need to declare variable types.
x = 10 # int y = 3.14 # float name = 'Alice' # str flag = True # bool nums =
[1,2,3] # list
2. Control Flow
2.1 if / elif / else
score = 75 if score >= 90: grade = 'A' elif score >= 70: grade = 'B' else: grade =
'C' print(grade) # B
2.2 Loops
# for loop for i in range(5): print(i) # 0 1 2 3 4 # while loop count = 0 while
count < 3: print(count) count += 1
pf2

Partial preview of the text

Download Intro to Python Programming and more Cheat Sheet Introduction to Computers in PDF only on Docsity!

Introduction to Python Programming

A beginner-friendly reference guide

1. Variables and Data Types

Python is dynamically typed โ€“ you do not need to declare variable types.

x = 10 # int y = 3.14 # float name = 'Alice' # str flag = True # bool nums = [1,2,3] # list

2. Control Flow

2.1 if / elif / else

score = 75 if score >= 90: grade = 'A' elif score >= 70: grade = 'B' else: grade = 'C' print(grade) # B

2.2 Loops

for loop for i in range(5): print(i) # 0 1 2 3 4 # while loop count = 0 while

count < 3: print(count) count += 1

3. Functions

def greet(name, greeting='Hello'): '''Return a personalised greeting string.''' return f'{greeting}, {name}!' print(greet('Bob')) # Hello, Bob! print(greet('Alice', 'Hi')) # Hi, Alice!

4. Data Structures

Structure Ordered Mutable Duplicates Example List Yes Yes Yes [1, 2, 3] Tuple Yes No Yes (1, 2, 3) Set No Yes No {1, 2, 3} Dictionary Yes* Yes Keys: No {'a': 1}

*Dictionaries maintain insertion order in Python 3.7+

5. File I/O

Writing to a file with open('data.txt', 'w') as f: f.write('Hello, file!\n')

Reading from a file with open('data.txt', 'r') as f: content = f.read() print(content)

6. Exception Handling

try: result = 10 / 0 except ZeroDivisionError as e: print(f'Error: {e}') finally: print('Always runs')