Podcast
Questions and Answers
Which of the following is NOT a characteristic of Python?
Which of the following is NOT a characteristic of Python?
- Object-oriented language
- Compiled language (correct)
- High-level programming language
- Interpreted language
In Python, indentation is purely for improving code readability and has no impact on how the code is executed.
In Python, indentation is purely for improving code readability and has no impact on how the code is executed.
False (B)
What is the primary difference between a program and a script, as discussed?
What is the primary difference between a program and a script, as discussed?
Programs are compiled before execution, whereas scripts are interpreted.
Guido van Rossum, the creator of Python, named the language after the TV show ______.
Guido van Rossum, the creator of Python, named the language after the TV show ______.
Match the following applications with their relation to Python:
Match the following applications with their relation to Python:
Which of the following options is a valid way to write a comment in Python?
Which of the following options is a valid way to write a comment in Python?
Python variable names can start with a number.
Python variable names can start with a number.
What is the file extension for Python source code files?
What is the file extension for Python source code files?
The command print("Hello, world!")
in Python will display ______ on the console.
The command print("Hello, world!")
in Python will display ______ on the console.
Match the following Python arithmetic operators with their corresponding operations:
Match the following Python arithmetic operators with their corresponding operations:
Why is consistent indentation important in Python?
Why is consistent indentation important in Python?
The //
operator in Python performs standard division, resulting in a float value.
The //
operator in Python performs standard division, resulting in a float value.
What is the purpose of the %
operator in Python arithmetic?
What is the purpose of the %
operator in Python arithmetic?
In Python, the ______ function is used to read input from the user.
In Python, the ______ function is used to read input from the user.
Match the following Python string formatting placeholders with their usage:
Match the following Python string formatting placeholders with their usage:
Which of the following statements about Python variables is correct?
Which of the following statements about Python variables is correct?
Python only supports integer and floating-point numbers; it cannot handle real numbers.
Python only supports integer and floating-point numbers; it cannot handle real numbers.
Briefly explain data type casting in Python.
Briefly explain data type casting in Python.
Given the expression print(3 + 12)
, the output will be ______.
Given the expression print(3 + 12)
, the output will be ______.
Match each relational comparison operator with its meaning.
Match each relational comparison operator with its meaning.
Given the code print(2 > 3)
, what will be the output?
Given the code print(2 > 3)
, what will be the output?
A Python variable name must start with an underscore.
A Python variable name must start with an underscore.
Explain the ceil()
function's role.
Explain the ceil()
function's role.
The text type in python is called
The text type in python is called
Match the collection types with the following definitions.
Match the collection types with the following definitions.
Which code format prints a statement stating name and food? Assume that name='Chris'
and food = 'burger'
.
Which code format prints a statement stating name and food? Assume that name='Chris'
and food = 'burger'
.
With modifiers to The percent sign (%)
placeholders, "(space): Pads numbers with spaces on the left (e.g., "% 5d" % 3 prints "3")." is a valid statement
With modifiers to The percent sign (%)
placeholders, "(space): Pads numbers with spaces on the left (e.g., "% 5d" % 3 prints "3")." is a valid statement
What functions are described for `String Formatting Functions.
What functions are described for `String Formatting Functions.
Describe what a len function does.
Describe what a len function does.
Match the following collection data types with the proper statements.
Match the following collection data types with the proper statements.
What code does Input
, Float
, and Calculate Area
perform? Assume that math
is imported.
What code does Input
, Float
, and Calculate Area
perform? Assume that math
is imported.
The correct code is print("Your age is", age)
when you want to concatenate integers with string text in python.
The correct code is print("Your age is", age)
when you want to concatenate integers with string text in python.
Name at least 3 key reasons to use Python.
Name at least 3 key reasons to use Python.
_____ produces text output on the console.
_____ produces text output on the console.
Match this with usage for coding.
Match this with usage for coding.
Which code follows most rules?
Which code follows most rules?
One of three primary logical operators presented include for, or, not
One of three primary logical operators presented include for, or, not
If "1 + 3 * 4" is entered. What number output will there be?
If "1 + 3 * 4" is entered. What number output will there be?
In Python, String placeholders
serve as ______
In Python, String placeholders
serve as ______
Match correct code to appropriate number output.
Match correct code to appropriate number output.
Flashcards
What is Python?
What is Python?
A general-purpose programming language often used for scripting, known for its readability.
What is a Program?
What is a Program?
A sequence of instructions that a computer can execute to perform a specific task, requiring compilation.
What is a Script?
What is a Script?
Code written in a scripting language that's interpreted to control another software application.
History of Python
History of Python
Signup and view all the flashcards
Why use Python?
Why use Python?
Signup and view all the flashcards
Who Uses Python?
Who Uses Python?
Signup and view all the flashcards
Python Requirements
Python Requirements
Signup and view all the flashcards
Installing Python
Installing Python
Signup and view all the flashcards
Using PyCharm
Using PyCharm
Signup and view all the flashcards
Create a Python project
Create a Python project
Signup and view all the flashcards
Create a Python file
Create a Python file
Signup and view all the flashcards
Command Line
Command Line
Signup and view all the flashcards
Using PyCharm
Using PyCharm
Signup and view all the flashcards
Python Code Execution
Python Code Execution
Signup and view all the flashcards
Indentation Matters
Indentation Matters
Signup and view all the flashcards
Comments in Python
Comments in Python
Signup and view all the flashcards
Keywords in Python
Keywords in Python
Signup and view all the flashcards
print Command
print Command
Signup and view all the flashcards
Expressions
Expressions
Signup and view all the flashcards
Precedence
Precedence
Signup and view all the flashcards
Real
Real
Signup and view all the flashcards
Real Number Output
Real Number Output
Signup and view all the flashcards
Math max () command
Math max () command
Signup and view all the flashcards
Math ceil() command
Math ceil() command
Signup and view all the flashcards
Math sqrt() command
Math sqrt() command
Signup and view all the flashcards
Using *
Using *
Signup and view all the flashcards
Direct Ref
Direct Ref
Signup and view all the flashcards
Relational expressions
Relational expressions
Signup and view all the flashcards
Logical expressions
Logical expressions
Signup and view all the flashcards
Operator Precedence
Operator Precedence
Signup and view all the flashcards
Variables
Variables
Signup and view all the flashcards
Assignment
Assignment
Signup and view all the flashcards
Variable Rules
Variable Rules
Signup and view all the flashcards
Data Types
Data Types
Signup and view all the flashcards
List
List
Signup and view all the flashcards
Use for Data Type
Use for Data Type
Signup and view all the flashcards
Casting
Casting
Signup and view all the flashcards
Input
Input
Signup and view all the flashcards
String
String
Signup and view all the flashcards
String Placeholders
String Placeholders
Signup and view all the flashcards
Method: upper()
Method: upper()
Signup and view all the flashcards
Method: lower()
Method: lower()
Signup and view all the flashcards
Method capitalize ()
Method capitalize ()
Signup and view all the flashcards
Method title()
Method title()
Signup and view all the flashcards
Method split()
Method split()
Signup and view all the flashcards
Method replace()
Method replace()
Signup and view all the flashcards
Method: len()
Method: len()
Signup and view all the flashcards
Study Notes
Introduction to Python
- Week 3 focuses on introducing the Python programming language
Learning Objectives
- Create a first Python program
- Describe what will happen when running a program which produces an error
- Declare a variable and determine value
- Apply comments in your code, both single and multiline
What is Python?
- Python is a general-purpose language often used in scripting roles
- Python is both a programming and scripting language
- Python is an interpreted, object-oriented, high-level language
Programming vs. Scripting Language
- A program is executed, the source is first compiled
- A program implements a sequence of instructions for a computer to perform a task
- A script gets interpreted
- A script is written in a scripting language
- A scripting language controls another software application
History
- Guido van Rossum invented Python in the early 90s in the Netherlands
- Python's conception occurred in the late 1980s, and its implementation started in December 1989
- Guido Van Rossum is a fan of "Monty Python's Flying Circus"
- Python got named after Monty Python
- Python has been open sourced since the beginning
A Short History Of Python
- The Conception was in the late 80s
- The implementation started in Dec 1989
- Python 0.9 was released in Feb 1991
- Python 1.0 was released in Jan 1994
- Python 2.0 was released in Oct 2000
- Python 3.0 was released in Dec 2008
- Python 3.7 was released in Jun 2018
Why Use Python?
- Simplicity, readability, and ease of use
- Python applications:
- Systems programming
- GUI programming
- Database programming
- Component integration
- Gaming
- XML
- Robotics
- Web applications
- Data science and visualization
- Machine learning
- Vulnerability testing
Five of the Many Reasons to Use Python
- Easy to Learn and Use
- Versatile
- Large and Active Community
- Cross-Platform Compatibility
- Open-source
Who Uses Python Today
- Python is applied in revenue-generating products by real companies
- Google utilizes Python extensively in its web search system
- Intel, Cisco, Hewlett-Packard, Seagate, Qualcomm, and IBM use Python for hardware testing
- ESRI uses Python as end-user customization tool for its popular GIS mapping products
- YouTube video sharing is largely written in Python
Requirements
- Python 3 Interpreter or above
- IDE Options can be offline or online
- Offline
- Pycharm
- Anacoda/Jupyter Notebook
- Online:
- onlinegdb.com
- colab.google
- replit.com
- online-python.com/online_python_compiler
Installing Python
- Download the latest version of Python from https://www.python.org/downloads/
- After the installation process starts. you will see a pop-up
- Once installed, open Python, you are prompted with >>> for single line commands
Using PyCharm
- Preferably download the community edition
- Run the installer and follow the steps
- installation options:
- 64-bit launcher: Adds a launching icon to the Desktop
- Open Folder as Project: Adds an option to the folder context menu that will allow opening the selected directory as a PyCharm project
- .py: Establishes an association with Python files to open them in PyCharm
- Add launchers dir to the PATH: Allows running this PyCharm instance from the Console without specifying the path to it
- Run PyCharm from the Windows Start menu/desktop shortcut, or from the launcher batch script/executable in the installation directory under bin.
Creating a Python Project in PyCharm
- When opening PyCharm for the first time, the Welcome Screen will appear and it's time to create your project
- The project is your central view for running and debugging code, using the Python console and system terminal, and managing tests, version control, databases, and frontends
- Create the project:
- Different project types can be created, in this case create a simple pure Python project
- Specify the project location by clicking the Browse button in the Location field
- Create a dedicated environment for each project is best practice. The Project venv will do the job on default
- Switch to Custom environment to use an existing environment or specify other environment types
- Click Create when ready
Creating a Python File in PyCharm
- Select the project root in the Project tool window, right-click, and select File | New
- Select the context menu, type the filename
Running Python
- Running Python Using Command Line
- Type in commands such as:
-
print ("Hello World")
- Printing the line will output "Hello World"
- Running in PyCharm
- Either right-click the editor and select Run
from the context menu - Press Ctrl+Shift+F10
- Since this Python script contains a main function, you can click in the gutter
- You'll see the popup menu of the available commands, and choose Run
Python Code Execution
- Source code translates to byte code
- This byte code gets run by the Python Virtual Machine
- The code is automatically compiled and then interpreted
- The file extension for source code is ".py"
- The file extension for byte code is ".pyc"
Indentation Matters
- Indentation is crucial in Python, as it defines code blocks instead of curly braces
- Consistent indentation (usually 4 spaces) is essential for proper program flow and to avoid errors
Comments in Python
- Interpreter ignores lines in Python code, these are comments
- Comments enhance the code's readability
-
Single-line comments
- """ Multiple line comments """
Keywords in Python
- Keywords in Python are reserved words that can not be used as a variable name
Print Command
- Produces text output on the console
- print("Message") prints a message
- print(Expression) prints the given text message or expression value on the console
- print(Item1, Item2, ..., ItemN) prints several messages and/or expressions on the same line. Elements separated by commas print with a space between them. A comma at the end of the statement will not print a newline character
- Print command examples:
print("Hello, world!") outputs Hello, world!
- age = 45
print("You have", 65 - age, "years until retirement") prints You have 20 years until retirement
Expressions
- An expression is a data value or set of operations to compute a value
- 1+4*3
- 42
- Arithmetic operators
+
addition-
subtraction/negation*
multiplication/
division//
floor division or integer division%
modulus a.k.a remainder**
exponentiation- Precedence sets the order in which operations are computed
/ % **
have a higher precedence than+ -
- Parentheses can be used to force a certain order of evaluation
(1 + 3) * 4
is 16
Real Numbers or Floating Point
- Python can also manipulate real numbers
- Example: 6.022, -15.9997, 42.0, 2.143e17
- The operators +, -, *, /, %, and ** all work for real numbers
- The
/
(division) operator produces an exact answer:15.0 / 2.0
is7.5
- Order of operations in real numbers is the same as for integers
- When integers and reals are mixed, the result is a real number
- Conversion occurs on a per-operator basis
Math Commands
- Python has useful, pre-built commands/functions for calculations
- abs(value) - absolute value
- ceil(value) - rounds up
- cos(value) - cosine in radians
- floor(value) - rounds down
- log(value) - logarithm, base e
- log10(value) - logarithm, base 10
- max(value1, value2) - larger of two values
- min(value1, value2) - smaller of two values
- round(value) - nearest whole number
- sin(value) - sine, in radians
- sqrt(value) - square root
- To use many math commands, include the import statement at the start:
from math import *
import math
From math import * vs import math
from math import *
- This imports all names from the module and puts them into the current namespace
- Functions/constants can be used from math without the math.file prefix prefix
import math
- Use import math for clear and safe access to functions and constants from the math module
- It provides explicit use of the math module, and improves code readability
- Helps prevent naming conflicts by separating the module from your local variables
Relational expressions
- Use of comparisons involving values
- Evaluate to a boolean value based on the condition
- Relational Operators:
==
Equal to!=
Not equal to<
Less than>
Greater than<=
Less than or equal to>=
Greater than or equal to
Logical expressions
- Expressions used to combine conditions, evaluate to True or False
- Essential for making decisions and controlling the flow of a program
- Logical Operators:
and
- Returns True only if both operands are Trueor
- Returns True if at least one operand is Truenot
- Reverses the value of an operand (True becomes False, False becomes True)
Operator Precedence
- Exponentiation ()** has highest precedence
- Multiplication (*) and Division (/), Floor Division (//) is evaluated left-to-right
- Addition (+) and Subtraction (-) evaluated left-to-right
- Comparison Operators (==, !=, <, >, <=, >=)
- Logical Operators (not, and, or) have the lowest precedence
- Parentheses override the default precedence order
Variables
- A named piece of memory that stores a value, explicit declaration of data type is not required
- Python infers the type from the value
- Usage:
- Compute an expression's result, store that result into a variable, and use that variable later in the program
- Assignment statements store a value into a variable
- Syntax: name = value
Rules for Python Variables
- Start with a letter or the underscore character
- Begin with a number
- Only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
- Case-sensitive (name, Name, and NAME are treated individually)
- Reserved words (keywords) are not allowed
Data Types
- Data types classify the kind of data a variable stores, determining the values and operations
- Python is dynamically typed. The data type of a variable is determined at runtime
- Numeric Types:
- Integers (int) represent whole numbers, positive, negative, or zero (e.g., -5, 0, 1024)
- Floats (float) represent decimal numbers (e.g., 3.14, -9.25)
- Complex Numbers (complex) represent numbers with imaginary and real components
- Text Type:
- Strings (str) represent sequences of characters enclosed in single or double quotes
- Logical Type:
- Booleans (bool) represent logical values, True or False
- Collection Types:
- Lists (list) lists of elements enclosed inside a square brackets [] can be modified
- Tuples (tuple:) list of elements enclosed in parentheses () cannot be modified
- Sets (set:) unordered collections of unique elements enclosed in curly braces {}.
- Dictionaries (dict:) unordered collections of key-value pairs enclosed in curly braces {} must be unique
Choosing the Right Data Type
- Use integers for whole numbers i.e. counting, indexing
- Use floats for decimal numbers and calculations
- Use strings for text data, addresses
- Use booleans for logical true/false statements
- Use lists a sequence of elements allowed for editing
- Use tuples for read only code
- Use set for unique elements when order does not matter
- Use dictionaries to store key-value pairs when efficient retrieval by key is needed
Casting
- Converting one data type into another
- Function:
- str() converts a value to string
- float() converts a value to float
- int() coverts to an integer
- bool() converts a value to true or false
Input
input()
reads a number from user input- Assign (store) the result of input into a variable
Strings
- Strings can be single-line, or multi-line
- Display a string literal by
print()
- String Placeholders
- {} (curly braces format)
- % (percent format)
- f (f-string format)
Strings Placeholders {}
- {} and
.format()
can replace variables in complex strings - Use {Number} for numbered index placeholders
- Use {variable} for named placeholders
Strings Placeholders %
- %d is used to format integers
- %s is used to format strings
- %.2f is used to format a float with "point 2" precision digits
The percent sign (%) placeholder
- Obsolete method of string formatting, replaced with "fstrings"
- Formatting Characters with %:
- `%d formatting integers
- `%f formatting floats.
- `%s formatting string values
- `%c Used to format Single Characters
Modifiers
- Adjusts the value to the left in assigned space
- Padding the numbers left, using spaces
- Decimal point precision in floats that are left
String Placeholders F
- Use the f tag at the start of Strings, this method is preferable to others
String Formatting Functions
upper()
: string to upper caselower()
: string to lower casetitle()
: converts each word to upper casecaptilize()
: convert the first word to upper casesplit()
: : splits a string to separated at a certain separator, and returns a listreplace()
: replaces a phrase or character with another one
String Formatting Functions
len()
: count the numbers in a char or string
NUMBER Formatting Functions
- Number data types store numeric values.
- Immutable: means that changing the value of a number data type results in a newly allocated object
Integer formating
Integer formating: this function returns a whole number of the specified number floor: method rounds a number DOWN to the power of x pow: The pow(x, y) function returns the value of x is a rounded version of the specified number.
Problem set
- Problem 1 to problem 9 are practice tasks for the use of everything learned in this lesson
Studying That Suits You
Use AI to generate personalized quizzes and flashcards to suit your learning preferences.