Module 2_Basic Python Concepts-1 (1)
Module 2_Basic Python Concepts-1 (1)
First Steps
Welcome to the exciting world of Python programming! This course will guide you
through the fundamental concepts that form the building blocks of almost any program you'll
ever write. Get ready to think like a programmer and solve problems with code!
The Python console is an extremely useful tool for learning and testing small snippets of
Python code directly. Think of it as a conversational partner for your Python code.
Windows:
o Search for "Python" in the Start menu. You might see "Python (Python 3.x)"
or "IDLE (Python 3.x)".
o IDLE: This is Python's Integrated Development and Learning Environment. It
opens a console window where you can type Python commands.
o Command Prompt: Open cmd or PowerShell, then type python and press
Enter.
macOS:
o Open Terminal (Applications > Utilities > Terminal).
o Type python3 (or python on older systems) and press Enter.
Linux:
o Open Terminal.
o Type python3 (or python) and press Enter.
Once you open the console, you'll typically see something like this:
1
The >>> is the prompt. This indicates that the Python interpreter is ready to receive your
commands.
You can type Python code directly at the >>> prompt and press Enter. The interpreter will
immediately execute the code and show you the result.
Python
>>> 2 + 2
4
>>> "Hello" + " " + "World"
'Hello World'
>>> 10 / 3
3.3333333333333335
>>> print("Learning Python is fun!")
Learning Python is fun!
>>>
Quick Testing: Great for trying out new functions or syntax quickly.
Interactive Learning: Provides immediate feedback, helping you understand how
code works.
Debugging: Can be used to inspect variable values during development.
Every journey begins with a first step, and in programming, that step is almost always
printing "Hello World!". It's a simple tradition that helps you confirm your setup is working
and gives you a taste of writing your first line of code.
What is it?
"Hello World!" is a classic introductory program that simply displays the text "Hello,
World!" on your screen. This “Hello World” is framed by Brian Kernighan in C
programming language in 1970.
Why is it important?
Verification: It confirms that your Python interpreter is installed correctly, and you
can run a basic script.
First Code: It's your very first program – a significant milestone!
Output: It introduces the concept of producing output from your program.
2
Example Console Interaction:
Python
>>> print("Hello, World!")
Hello, World!
>>>
Explanation:
print(): This is a built-in Python function that sends whatever is inside the
parentheses to the standard output (usually your screen).
"Hello, World!": This is a "string" of text. Strings are sequences of characters
enclosed in either single quotes (') or double quotes (").
While the console is great for quick tests, for larger programs, you'll write your code in a file
(a script).
1. Open a text editor: You can use a simple one like Notepad (Windows), TextEdit
(macOS - ensure it's plain text mode), or a code editor like VS Code or PyCharm
(which we'll introduce later).
2. Type the code:
Python
# my_first_program.py
print("Hello, World!")
3. Save the file: Save it with a .py extension (e.g., hello_world.py). Choose a
memorable location like Documents/PythonPrograms.
4. Run from Command Line/Terminal:
o Open your terminal or command prompt.
o Navigate to the directory where you saved your file using the cd command
(e.g., cd Documents/PythonPrograms).
o Type python hello_world.py (or python3 hello_world.py on some
systems) and press Enter.
Hello, World!
Syntax errors are mistakes in the structure of your code that prevent Python from
understanding and running it. They are like grammatical errors in a human language. Python
will stop execution and tell you where it found the error.
Python
3
>>> print "Hello World!"
File "<stdin>", line 1
print "Hello World!"
^
SyntaxError: Missing parentheses in call to 'print'. Did you mean
print("Hello World!")?
Python
>>> print('Hello, World!")
File "<stdin>", line 1
print('Hello, World!")
^
SyntaxError: unterminated string literal (detected at line 1)
Explanation: You started the string with a single quote (') but ended it with a double quote
("). Python expects the same type of quote to close a string.
Python
>>> prit("Hello, World!")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'prit' is not defined. Did you mean: 'print'?
Explanation: You misspelled print. Python doesn't know what prit means. Notice that this
is a NameError, not a SyntaxError, because the syntax itself is valid, but the name prit
doesn't exist. Python is often smart enough to suggest the correct name.
Python uses indentation (spaces or tabs at the beginning of a line) to define code blocks.
This is crucial! We'll explore it more when we cover control flow, but even basic errors can
occur.
Python
>>> print("Hello") # Notice the leading spaces here
File "<stdin>", line 1
print("Hello")
IndentationError: unexpected indent
Explanation: Python saw an indent where it didn't expect one. When you're just writing
simple, top-level code, do not indent unless you're inside a function, loop, or conditional
statement.
4
Read the Error Message: Python's error messages are often very informative. Look
at the ErrorType (e.g., SyntaxError, NameError, IndentationError) and the
message itself.
Look at the Line Number/Caret: The error message usually tells you the file, line
number, and even points with a ^ where it detected the problem.
Check for Typos: Common culprits are misspelled function names or keywords.
Check for Mismatched Delimiters: Parentheses (), square brackets [], curly braces
{}, and quotes '' "" must always come in matching pairs.
Pay Attention to Indentation: Python is strict about it!
2.1 Operators
Console
Operator Operation Example Explanation
Output
+ Addition 5 + 3 8 Standard addition.
- Subtraction 10 - 4 6 Standard subtraction.
* Multiplication 7 * 2 14 Standard multiplication.
Floating-point division - always returns a
float (decimal number), even if the result is
/ Division 15 / 3 5.0
a whole number. This is important for
precision.
Integer division - divides and rounds down
// Floor Division 17 // 3 5 to the nearest whole number (integer). It
effectively discards the fractional part.
Remainder of division. This operator gives
you the remainder after division. It's
incredibly useful for checking if a number is
% Modulus 17 % 3 2
even/odd (num % 2 == 0) or for cyclical
operations (e.g., finding the hour on a 12-
hour clock).
base raised to the power of exponent (e.g., 2
** Exponentiation 2 ** 3 8 ** 3 means 2 multiplied by itself 3 times: 2 *
2 * 2).
Export to Sheets
Python
5
>>> 10 + 5
15
>>> 20 - 7
13
>>> 4 * 6
24
>>> 100 / 4
25.0
>>> 10 / 3
3.3333333333333335
>>> 10 // 3
3
>>> 17 % 5
2
>>> 3 ** 4 # 3 * 3 * 3 * 3
81
>>>
Python follows the standard mathematical order of operations, just like in algebra:
Python
>>> 5 + 2 * 3
11 # Explanation: Multiplication (2 * 3 = 6) happens before
addition (5 + 6 = 11)
>>> (5 + 2) * 3
21 # Explanation: Parentheses are evaluated first (5 + 2 = 7),
then multiplication (7 * 3 = 21)
>>> 10 - 4 / 2
8.0 # Explanation: Division (4 / 2 = 2.0) happens before
subtraction (10 - 2.0 = 8.0)
>>> 2 ** 3 + 1
9 # Explanation: Exponentiation (2 ** 3 = 8) happens before
addition (8 + 1 = 9)
Division by Zero: This is a mathematical impossibility and will cause an error known
as ZeroDivisionError.
6
Python
>>> 10 / 0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
Missing Operators: You can't just put numbers next to each other to imply
multiplication.
Python
>>> 5(2+3)
SyntaxError: cannot call non-function of type 'int'
You can define strings using single quotes (') or double quotes ("). It's generally good
practice to be consistent within your code.
Python
>>> 'Hello, Python!'
'Hello, Python!'
>>> "I love programming."
'I love programming.'
>>> type("Hello") # Check the data type
<class 'str'>
>>>
If your string needs to contain a quote of the other type, you don't need to escape it. This
makes your code cleaner.
Python
>>> message1 = "He said, 'Hello!'"
>>> print(message1)
7
He said, 'Hello!'
>>> message2 = 'She replied, "Hi there!"'
>>> print(message2)
She replied, "Hi there!"
>>>
For strings that span multiple lines, use triple quotes (either ''' or """). The newline
characters are preserved.
Example:
Python
>>> multiline_string = """This is a string
... that spans
... multiple lines."""
>>> print(multiline_string)
This is a string
that spans
multiple lines.
>>>
(Note: In the console, when you press Enter after the first line of a triple-quoted string, you'll
see ... which indicates Python is expecting more input for the same string until you close the
triple quotes.)
Sometimes you need to include special characters in your string, like a newline or a tab, or a
quote of the same type that you used to define the string. We use a backslash (\) followed by
a character to "escape" it, giving it a special meaning.
Escape
Meaning Console Example Output
Sequence
\n Newline print("Line 1\nLine 2") Line 1<br>Line 2
\t Tab print("Name:\tAlice") Name: Alice
print("Path: Path:
\\ Backslash C:\\Users\\Name") C:\Users\Name
\' Single Quote print('It\'s a sunny day.') It's a sunny day.
\"
Double print("He said, \"Hello!\"") He said, "Hello!"
Quote
Export to Sheets
Python
>>> print("First line.\nSecond line.")
First line.
Second line.
>>> print("Item\tPrice")
Item Price
8
>>> print("This is a backslash: \\")
This is a backslash: \
>>> print('I\'m learning Python.')
I'm learning Python.
>>>
Unterminated String Literal: Forgetting to close a string with the matching quote.
Python
Explanation: You opened the string with " but never closed it. Python reaches the
end of the line (or file) and finds an open string.
Python
Python
9
4.1 How it Works
The input() function takes an optional argument: a prompt string that is displayed to the
user. Whatever the user types is captured and returned as a string.
Example in a Script:
Let's create a file named get_name.py and run it from your terminal/command prompt:
Python
# get_name.py
print("Welcome to our program!")
name = input("What is your name? ")
print("Hello, " + name + "!")
python get_name.py
This is a crucial point for beginners. Even if the user types numbers, input() treats them as
text.
Python
>>> num_str = input("Enter a number: ")
Enter a number: 123
>>> print(type(num_str))
<class 'str'>
>>>
If you want to perform mathematical operations on the input, you need to convert it to a
numeric type (like int for integers or float for decimal numbers) using type casting
functions.
Example in a Script:
10
Let's create a file named simple_calculator.py:
Python
# simple_calculator.py
print("--- Simple Calculator ---")
ValueError when converting non-numeric input: If the user types something that
cannot be converted to an int or float (e.g., "hello" when expecting a number), your
program will crash with a ValueError.
Python
Explanation: Python tried to convert the string 'twenty' into an integer but couldn't
because it's not a valid integer representation. This is a common runtime error for
beginner programs that rely on user input. Later, you'll learn about try-except
blocks to handle such errors gracefully without crashing your program.
11
Strings are incredibly versatile! Python provides many ways to manipulate and combine
them.
Use the + operator to join two or more strings together. This is called concatenation.
Python
>>> "Hello" + "World"
'HelloWorld'
>>> "Hello" + " " + "World" # Adding a space for readability
'Hello World'
>>> first_name = "Jane"
>>> last_name = "Doe"
>>> full_name = first_name + " " + last_name
>>> print(full_name)
Jane Doe
>>>
5.2 Repetition
Python
>>> "Python" * 3
'PythonPythonPython'
>>> border = "=" * 20
>>> print(border)
====================
>>>
Python
>>> my_string = "Programming"
>>> len(my_string)
11
>>> len("Hello")
5
>>> len("") # Length of an empty string
0
>>>
Each character in a string has an index, starting from 0 for the first character.
12
Example in the Console:
Python
>>> word = "PYTHON"
>>> word[0] # First character (index 0)
'P'
>>> word[1] # Second character (index 1)
'Y'
>>> word[5] # Sixth character (index 5) - the last character
'N'
Important: Trying to access an index that doesn't exist (e.g., trying to get the 10th character
of a 5-character string) will result in an IndexError.
Python
>>> word = "ABC"
>>> word[3] # Index 3 is out of bounds for a 3-character string (valid
indices are 0, 1, 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
You can extract a portion (a "slice") of a string using the syntax: [start:end:step].
start: The index where the slice begins (inclusive). If omitted, defaults to 0 (the
beginning).
end: The index where the slice ends (exclusive - the character at this index is NOT
included). If omitted, defaults to the end of the string.
step: The step size (e.g., 2 for every second character). If omitted, defaults to 1.
Python
>>> sentence = "Hello, Python Programming!"
13
>>>
Strings have many useful built-in methods (functions that "belong to" the string object and
perform operations on it). You call them using the dot (.) operator:
string_variable.method_name().
Python
>>> text = " Hello, World! "
>>> text.upper()
' HELLO, WORLD! '
>>> text.lower()
' hello, world! '
>>> text.strip()
'Hello, World!'
>>> text.replace("World", "Python")
' Hello, Python! '
>>> "apple".find("p")
1
>>> "banana".count("a")
3
>>> "hello".find("xyz") # Substring not found
-1
>>>
Python
14
>>> "My age is " + 30
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
Explanation: You cannot directly concatenate a string and an integer using +. You
must convert the number to a string first using str(). Correct: "My age is " +
str(30)
Code snippet
Explanation: The repetition operator * only works with a string and an integer
(specifying how many times to repeat).
Strings are Immutable: You cannot change individual characters in a string using
indexing.
Python
Storage: To store data (numbers, text, True/False values, etc.) that your program will
use.
Readability: To make your code more understandable by giving meaningful names to
data (e.g., user_name instead of just "Alice"). This is crucial for larger programs.
Flexibility: To easily change values in one place, affecting multiple parts of your
code. If a value (like a tax rate or a user's age) changes, you only need to update it
15
once where it's stored in the variable, rather than searching for every instance of that
value.
You create a variable by giving it a name and assigning a value to it using the assignment
operator (=).
Python
>>> age = 30 # 'age' is an integer variable
>>> name = "Alice" # 'name' is a string variable
>>> price = 19.99 # 'price' is a float variable
>>> is_student = True # 'is_student' is a boolean variable (True/False are
special keywords)
>>> print(age)
30
>>> print(name)
Alice
>>> print(price)
19.99
>>> print(is_student)
True
Python has specific rules for naming variables. If you break these rules, you'll get a
SyntaxError or NameError.
Python
>>> myVar = 10
>>> print(myvar)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
16
NameError: name 'myvar' is not defined. Did you mean: 'myVar'?
Explanation: Python treats myVar and myvar as two completely separate variables.
Be consistent with your casing!
4. Cannot be Python keywords: You cannot use words that have special meaning in
Python (like if, for, while, print, True, False, None, etc.).
Python
>>> for = 10
SyntaxError: invalid syntax
Common Keywords (don't use these as variable names): and, as, assert, break,
class, continue, def, del, elif, else, except, False, finally, for, from,
global, if, import, in, is, lambda, None, nonlocal, not, or, pass, raise, return,
True, try, while, with, yield
While not strict rules, these are widely adopted practices that make your code readable and
maintainable, especially when working with others.
Snake Case (most common in Python): Words are lowercase and separated by
underscores.
o first_name
o total_score
o is_active_user
Descriptive names: Choose names that clearly indicate what the variable holds.
Avoid single-letter variable names unless their purpose is absolutely obvious (e.g., x,
y for coordinates in a mathematical context).
o Good: customer_address, product_price_usd
o Bad: ca, pp
You can change the value of a variable at any time. The variable will then hold the new
value, overwriting the old one.
Python
>>> score = 100
>>> print("Initial score:", score)
Initial score: 100
17
>>>
You can assign multiple variables on a single line, making your code more concise.
Python
>>> x, y, z = 10, 20, 30
>>> print(x, y, z)
10 20 30
>>> a = b = c = "Hello" # All three variables now refer to the same string
object
>>> print(a, b, c)
Hello Hello Hello
>>>
NameError: name '...' is not defined: This happens when you try to use a
variable before you've assigned a value to it, or if you've misspelled the variable
name. This is a very common error for beginners!
Python
>>> print(my_variable)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'my_variable' is not defined
Explanation: Python doesn't know what my_variable refers to because it hasn't been
created (assigned a value) yet. Always assign a value to a variable before you try to
use it.
To increment a variable, you simply add a value to it and reassign the result to the same
variable.
Python
18
>>> counter = 0
>>> print("Initial counter:", counter)
Initial counter: 0
>>> # Increment by 1
>>> counter = counter + 1
>>> print("Counter after incrementing by 1:", counter)
Counter after incrementing by 1: 1
>>> # Increment by 5
>>> counter = counter + 5
>>> print("Counter after incrementing by 5:", counter)
Counter after incrementing by 5: 6
>>>
Python
>>> lives = 3
>>> print("Initial lives:", lives)
Initial lives: 3
>>> # Decrement by 1
>>> lives = lives - 1
>>> print("Lives after decrementing by 1:", lives)
Lives after decrementing by 1: 2
Python provides convenient shorthand operators for common operations like addition,
subtraction, multiplication, and division combined with assignment. These are very
frequently used because they are more concise and often more efficient!
Equivalent Example in
Operator Result Explanation
To Console
x = 10; x +=
+= x = x + y
5 x is 15 Add y to x, then assign the new value to x.
x = 10; x -= Subtract y from x, then assign the new
-= x = x - y
2 x is 8
value to x.
x = 10; x *= Multiply x by y, then assign the new value
*= x = x * y
3 x is 30
to x.
/= x = x / y
x = 10; x /= x is Divide x by y, then assign the new value
4 2.5 to x. Returns float.
x = 10; x //= Floor divide x by y, then assign the new
//= x = x // y
4 x is 2
value to x.
x = 10; x %= Get remainder of x divided by y, then
%= x = x % y
3 x is 1
assign the new value to x.
19
x = 2; x **= Raise x to the power of y, then assign the
**= x = x ** y
3 x is 8
new value to x.
Export to Sheets
Python
>>> points = 100
>>> points += 10 # Add 10 to points
>>> print("Points after += 10:", points)
Points after += 10: 110
>>> energy = 50
>>> energy -= 5 # Subtract 5 from energy
>>> print("Energy after -= 5:", energy)
Energy after -= 5: 45
>>> price = 25
>>> price *= 1.1 # Increase price by 10% (multiply by 1.1)
>>> print("Price after *= 1.1:", price)
Price after *= 1.1: 27.5
>>> count = 7
>>> count //= 2 # Integer division of count by 2
>>> print("Count after //= 2:", count)
Count after //= 2: 3
Python
>>> x = 5
>>> x + 1 # This calculates x + 1 (which is 6) but doesn't change x
itself
6
>>> print(x) # x is still 5
5
20
Chapter 8: Intro to PyCharm - Your Development
Environment
While you can write and run Python code using a simple text editor and the command line, an
Integrated Development Environment (IDE) like PyCharm significantly enhances your
coding experience.
Source code editor: Where you write your code with helpful features like syntax
highlighting and code completion.
Build automation tools: For interpreting or compiling your code and managing
project dependencies.
Debugger: For finding and fixing errors in your code systematically.
Other features: Project management, version control integration, etc.
PyCharm is a popular and powerful IDE specifically designed for Python. It offers a wide
range of features that make coding easier, faster, and more enjoyable:
21
Project Management: PyCharm organizes your files and folders into logical
projects, keeping your code structured and easy to navigate, especially for larger
applications.
Version Control Integration: Seamlessly works with popular version control
systems like Git. This allows you to track changes to your code over time, revert to
previous versions, and collaborate effectively with other developers.
Virtual Environments: PyCharm makes it easy to set up and manage virtual
environments for your projects. This isolates project-specific libraries and
dependencies, preventing conflicts between different projects on your machine. For
example, Project A might need library_x version 1, while Project B needs
library_x version 2 – virtual environments handle this smoothly.
The PyCharm Community Edition is free and open-source, making it perfect for learning
and small projects.
22
o The output of your program will appear in the "Run" window at the bottom of
the PyCharm interface.
Goal: Create a program that converts temperatures between Celsius and Fahrenheit.
Concepts Covered:
Requirements:
1. Celsius to Fahrenheit:
o Prompt the user to enter a temperature in Celsius.
o Convert the input string to a float.
o Apply the formula: Fahrenheit = (Celsius * 9/5) + 32
o Print the result clearly.
2. Fahrenheit to Celsius:
o Prompt the user to enter a temperature in Fahrenheit.
o Convert the input string to a float.
o Apply the formula: Celsius = (Fahrenheit - 32) * 5/9
o Print the result clearly.
Python
# --- Celsius to Fahrenheit Conversion ---
23
print("\n--- Celsius to Fahrenheit Converter ---")
celsius_str = input("Enter temperature in Celsius: ")
celsius = float(celsius_str)
fahrenheit = (celsius * 9/5) + 32
print(f"Fahrenheit: {fahrenheit}°F") # Using an f-string for cleaner output
Example Interaction:
Goal: Calculate the Simple Interest (SI) given Principal, Number of years, and Rate of
interest.
Concepts Covered:
Requirements:
24
6. Convert all inputs to appropriate numeric types (float() is often safer here as
rates/principals can be decimal).
7. Calculate the Simple Interest using the formula.
8. Print the calculated Simple Interest.
Python
# --- SI CALCULATOR ---
print("\n--- Simple Interest Calculator ---")
print("Formula: SI = (P * N * R) / 100")
Example Interaction:
Returns the absolute value of a number (its distance from zero, always positive).
Python
>>> abs(-10)
10
>>> abs(5.7)
25
5.7
>>> abs(0)
0
>>>
Python
>>> round(3.14159)
3
>>> round(3.7)
4
>>> round(2.5) # Python's round() for .5 rounds to the nearest even number
2
>>> round(3.5)
4
>>> round(3.14159, 2) # Round to 2 decimal places
3.14
>>> round(123.456, 1) # Round to 1 decimal place
123.5
>>>
Returns the smallest item in an iterable (like a list or tuple) or the smallest of two or more
arguments.
Python
>>> min(10, 5, 20, 3) # With multiple arguments
3
>>> numbers = [10, 5, 20, 3]
>>> min(numbers) # With a list
3
>>> min(-1, -5, 0)
-5
>>>
Returns the largest item in an iterable or the largest of two or more arguments.
Python
>>> max(10, 5, 20, 3) # With multiple arguments
26
20
>>> numbers = [10, 5, 20, 3]
>>> max(numbers) # With a list
20
>>> max(100, 1000, 50)
1000
>>>
Python
>>> grades = [85, 90, 78, 92, 88]
>>> sum(grades)
433
>>> print(sum([1, 2, 3]))
6
>>>
Equivalent to base ** exp. Can also take an optional third argument mod (which calculates
(base ** exp) % mod).
Python
>>> pow(2, 3) # 2 to the power of 3
8
>>> pow(5, 2) # 5 squared
25
>>> pow(4, 0.5) # Square root (4 to the power of 0.5)
2.0
>>>
Returns a tuple containing the quotient and remainder of the division. This is often more
efficient than calculating // and % separately if you need both.
Python
>>> divmod(17, 3) # Returns (quotient, remainder)
(5, 2)
>>> quotient, remainder = divmod(25, 4)
>>> print("Quotient:", quotient)
Quotient: 6
>>> print("Remainder:", remainder)
Remainder: 1
>>>
27
10.8 Practical Application Example
Let's use some of these functions to calculate an average and find extreme values.
Example in a Script:
Python
# calculate_stats.py
print("--- Grade Statistics ---")
Remember to practice regularly! The more you code, the better you'll become. Experiment
with these concepts in the console and by writing small scripts. Good luck!
28