0% found this document useful (0 votes)
5 views

MIDTERM- PL101

The document provides an overview of Python programming, including its features, installation, and running code using various IDEs like Thonny and IDLE. It covers fundamental concepts such as keywords, identifiers, variables, data types, and operators, along with examples of syntax and usage. Additionally, it highlights the importance of indentation, comments, and the dynamic typing nature of Python.

Uploaded by

bkhianmarco
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

MIDTERM- PL101

The document provides an overview of Python programming, including its features, installation, and running code using various IDEs like Thonny and IDLE. It covers fundamental concepts such as keywords, identifiers, variables, data types, and operators, along with examples of syntax and usage. Additionally, it highlights the importance of indentation, comments, and the dynamic typing nature of Python.

Uploaded by

bkhianmarco
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Module 6 ● Python's Built-in IDE: IDLE

What is Python?
o Open IDLE to launch the
● Cross-platform language: Runs on interactive shell.
Windows, macOS, Linux, and is ported o Create a new file, save with .py
to Java/.NET virtual machines. extension (e.g., hello.py).
● Free and open-source. o Write code and run via Run >
Run Module or press F5.
● Pre-installed on Linux and macOS, but
may require updates to the latest Your First Python Program
version.
● Example: "Hello, World!"

Running Python
1. The Easiest Way: Using Thonny IDE Code: print("Hello, world!")

● Comes bundled with the latest Python Save as hello_world.py and run to see:t
version.
Output: Hello, world!
● Steps:
1. Download and install Thonny. Keywords and Identifiers
2. Go to: File > New, save the file
with .py extension (e.g.,
Keywords
hello.py).
3. Write your Python code.
4. To run, go to: Run > Run current ● Reserved words that define Python's
script or press F5. syntax and structure.
● Case-sensitive.
2. Immediate Mode
● Cannot be used as identifiers.

● Open the terminal/command line. ● Python 3.7 has 33 keywords:

● Type python to start the Python False | await | else | import | pass |
| None | break | except | in | raise |
interpreter.
| True | class | finally | is | return |
● Type code (e.g., 1 + 1) and press Enter | and | continue | for | lambda | try |
for instant results. | as | def | from | nonlocal | while |
● Use quit() to exit. | assert| del | global | not | with |
| async | elif | if | or | yield |
3. Using an IDE
Identifiers
● IDEs provide features like:
o Code hinting ● Names for variables, functions, classes,
o Syntax highlighting
etc.
o File explorers
● Rules for Naming Identifiers: ●
o Can include letters, digits, and
underscores (_), e.g., myClass, Example:
var_1. for i in range(1, 6):
o Cannot start with a digit (e.g., print(i)
1variable is invalid). if i == 3:
o Cannot use keywords (e.g., break
global = 1 is invalid).
o No special characters (e.g., a@
Inconsistent indentation causes
= 0 is invalid).
IndentationError.
o Can be of any length.

Things to Remember

● Python is case-sensitive (e.g., Variable ≠


Python Comments
variable).
● Use meaningful names (e.g., count Single-line comments: Start with #:
instead of c). # This is a comment
● Separate multiple words with print("Hello, World!")
underscores, e.g., this_is_a_variable.
Multi-line comments:
Module 7 Use multiple #
Python Statements # Line 1
# Line 2
● Definition: Instructions that Python can
Or triple quotes (''' or """):
execute (e.g., a = 1).
"""This is a
● Multi-line Statements:
multi-line comment."""
Use \ for explicit line continuation:
a=1+2+3+\ Docstrings: Used for documenting
4+5+6 functions/classes:
def double(num):
Parentheses (), brackets [], and braces {} """Returns double the input."""
implicitly allow multi-line statements: return 2 * num
a = (1 + 2 + 3 +
4 + 5 + 6) print(double.__doc__)

Multiple statements in one line use ;: Python Variables


a = 1; b = 2; c = 3
● Definition: Named locations to store
Python Indentation
data.

● Purpose: Defines blocks of code instead


of braces {}.
Dynamic Typing: Type is inferred based on the b = 100 # Decimal
value: c = 0o310 # Octal
number = 10 d = 0x12c # Hexadecimal
number = 1.1 # Changes type x = 3.14j # Complex

Multiple Assignments: 2.String Literals


a, b, c = 5, 3.2, "Hello" Enclosed in single ' or double "
x = y = z = "Same value" quotes:
strings = "Python"
multiline = """This spans
multiple lines."""
unicode = u"\u00dcnic\u00f6de"
raw = r"Raw \n string"

3. Boolean Literals
Values: True, False:
Constants x = (1 == True) # True
y = (1 == False) # False
Convention: Use ALL CAPS (e.g., PI = 3.14).
a = True + 4 #5
Example:
# In constant.py 4. Special Literals
GRAVITY = 9.8 None: Indicates the absence of a
# In main.py value:
import constant food = None
print(constant.GRAVITY) print(food) # None
Rules for Naming Variables and Constants
5. Literal Collections
Types: List, Tuple, Dictionary,
1. Use letters (a-z, A-Z), digits (0-9), or
underscores _. Set:
2. Cannot start with a digit (e.g., 1var is fruits = ["apple", "orange"] # List
invalid). numbers = (1, 2, 3) # Tuple
3. Avoid special characters (!, @, #, etc.). alphabets = {'a': 'apple'} #
4. Follow naming conventions like Dictionary
snake_case or MACRO_CASE. vowels = {'a', 'e', 'i'} # Set
Literals
Module 8
● Definition: Fixed values assigned to
variables/constants. Data Types in Python
Python is a dynamically typed language where
1. Numeric Literals the type of a variable is determined at runtime.
Below is a detailed breakdown of various data
Types: Integer, Float, Complex types and their uses.
a = 0b1010 # Binary
s = "Hello, World!"
print(s[4]) # Output: o
1. Python NumbersPython supports three main print(s[7:12]) # Output: World
types of numbers: Immutability:
s[0] = 'h' # Throws TypeError
● Integer (int): Whole numbers of
unlimited size.
3. Type Conversion
● Floating Point (float): Numbers with a
Python supports:
decimal point, precise up to 15 decimal
places.
1. Implicit Type Conversion: Python
● Complex (complex): Numbers with a automatically converts lower to higher
real and imaginary part, represented as types (e.g., int to float).
x + yj. 2. Explicit Type Conversion: Done
manually using functions like int(),
Examples: float(), and str().

a=5 Implicit Conversion Example:


print(a, "is of type", type(a)) # Output: 5 is of
type <class 'int'> a = 123
b = 1.23
b = 2.0 c=a+b
print(b, "is of type", type(b)) # Output: 2.0 is of print(type(c)) # Output: <class 'float'>
type <class 'float'> Explicit Conversion Example:
a = "123"
c = 1 + 2j
b = int(a)
print(c, "is complex number?", isinstance(c,
print(type(b)) # Output: <class 'int'>
complex)) # Output: True
Key Points:
4. Python Input and Output
● Integers: Can be arbitrarily large.
Output with print()
● Floats: May truncate beyond 15 decimal
places. The print() function can take multiple
● Complex numbers: Written as x + yj. parameters:
print(object, sep=' ', end='\n', file=sys.stdout)
Examples:
2. Python Strings
Strings in Python are sequences of Unicode print("Hello", "World", sep=', ', end='!\n') #
characters. They are immutable. Output: Hello, World!

Examples of String Creation: Input with input()


s = "This is a string"
The input() function reads input as a string by
s_multiline = '''This is
default:
a multiline string'''
String Slicing: num = input("Enter a number: ")
num = int(num) # Convert to integer

Example:
5. Python Imports
Modules allow you to reuse code. Use import to a = 7
b = 2
include modules:
print('Sum:', a + b)
import math print('Subtraction:', a - b)
print('Multiplication:', a * b)
print(math.pi) # Output: 3.141592653589793 print('Division:', a / b)
You can also import specific components: print('Modulo:', a % b)
print('Power:', a ** b)
from math import sqrt
print(sqrt(16)) # Output: 4.0
2. Assignment Operators
Custom Modules: Python searches for modules
in the directories listed in sys.path. You can add
● Assign values or perform operations
custom paths to it.
while assigning.
Module 9 ● Operators and Their Usage:
Reviewer: Python Operators
Overview Opera Operatio Exam
tor n ple
1. Arithmetic Operators
Assignme
= a=7
nt
● Perform basic mathematical operations.
a += 1
Add and
Operators and Their Usage: += (a =
assign
a+1)
Operat Examp
Operation Subtract a -= 3
or le
-= and (a = a-
5+2 assign 3)
+ Addition
=7
Multiply a *= 4
4-2= *= and (a =
- Subtraction
2 assign a*4)
2*3= Divide a /= 3
* Multiplication
6 /= and (a =
4/2= assign a/3)
/ Division
2 Power
5%2 **= and a **= 2
% Modulo assign
=1
Power/ 4 ** 2
**
Exponent = 16
Example:
a = 10 print('a < b:', a < b)
b = 5 print('a >= b:', a >= b)
a += b # a = a + b print('a <= b:', a <= b)
print(a) # Output: 15
4. Logical Operators
3. Comparison Operators
● Combine conditional statements.
● Compare two values and return a
● Operators and Their Usage:
boolean (True or False).
● Operators and Their Usage:
Opera Descripti Exam
tor on ple
Opera Examp
Meaning Returns (a >
tor le
True if b) and
and
both are (b >
== Equal to 3 == 5 False True 0)
Returns (a >
True if b) or
Not or
!= 3 != 5 True one is (b <
equal to
True 0)

Greater Inverts
> 3 > 5 False the not(a
than not
boolean > b)
value
< Less than 3 < 5 True

Greater
5. Special Topic: Rounding Numbers
>= than or 3 >= 5 False
equal to
● Round decimals to a specific number of
Less than places:
<= or equal 3 <= 5 True
a = 3.4536
to print('Using %: %.2f' % a)
# 2 decimal places
print('Using format():
{:.3f}'.format(a)) # 3 decimal
places
Example: print('Using round():', round(a, 2))
# 2 decimal places
a = 5 Notes
b = 2
print('a == b:', a == b)
print('a != b:', a != b)
print('a > b:', a > b)
1. These operators are essential for
mathematical, conditional, and logical
operations in Python.
2. Experiment with examples to
understand their behavior.

You might also like