Introduction to Python

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson
Download our mobile app to listen on the go
Get App

Questions and Answers

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.

False (B)

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 ______.

<p>Monty Python's Flying Circus</p>
Signup and view all the answers

Match the following applications with their relation to Python:

<p>Google's web search = Extensive use of Python YouTube = Largely written in Python ESRI's GIS products = Python used as end-user customization tool Intel, Cisco, IBM = Use Python for hardware testing</p>
Signup and view all the answers

Which of the following options is a valid way to write a comment in Python?

<h1>This is a comment (B)</h1>
Signup and view all the answers

Python variable names can start with a number.

<p>False (B)</p>
Signup and view all the answers

What is the file extension for Python source code files?

<p>.py</p>
Signup and view all the answers

The command print("Hello, world!") in Python will display ______ on the console.

<p>Hello, world!</p>
Signup and view all the answers

Match the following Python arithmetic operators with their corresponding operations:

<ul> <li>= Addition</li> </ul> <ul> <li>= Subtraction</li> </ul> <ul> <li>= Multiplication / = Division</li> </ul>
Signup and view all the answers

Why is consistent indentation important in Python?

<p>It defines code blocks. (D)</p>
Signup and view all the answers

The // operator in Python performs standard division, resulting in a float value.

<p>False (B)</p>
Signup and view all the answers

What is the purpose of the % operator in Python arithmetic?

<p>It calculates the remainder of a division operation.</p>
Signup and view all the answers

In Python, the ______ function is used to read input from the user.

<p>input()</p>
Signup and view all the answers

Match the following Python string formatting placeholders with their usage:

<p>{} = Replacement field for formatting strings %s = Placeholder for strings using the % operator %d = Placeholder for integers using the % operator f-strings = String literals that allow embedded expressions</p>
Signup and view all the answers

Which of the following statements about Python variables is correct?

<p>Python infers the data type of a variable based on the assigned value. (A)</p>
Signup and view all the answers

Python only supports integer and floating-point numbers; it cannot handle real numbers.

<p>False (B)</p>
Signup and view all the answers

Briefly explain data type casting in Python.

<p>Converting one data type into another.</p>
Signup and view all the answers

Given the expression print(3 + 12), the output will be ______.

<p>15</p>
Signup and view all the answers

Match each relational comparison operator with its meaning.

<p>&lt; = Less than</p> <blockquote> <p>= Greater Than &lt;= = Less than or Equal To = = Greater than or Equal To</p> </blockquote>
Signup and view all the answers

Given the code print(2 > 3), what will be the output?

<p>False (B)</p>
Signup and view all the answers

A Python variable name must start with an underscore.

<p>False (B)</p>
Signup and view all the answers

Explain the ceil() function's role.

<p>Rounds number UP to the nearest integer.</p>
Signup and view all the answers

The text type in python is called

<p>string</p>
Signup and view all the answers

Match the collection types with the following definitions.

<p>Lists = Ordered, mutable collections of elements enclosed in square brackets [] (e.g., [1, 2, &quot;apple&quot;, 3.4]). Tuples = Ordered, immutable collections of elements enclosed in parentheses () (e.g., (10, &quot;hello&quot;, True)). Sets = Unordered collections of unique elements enclosed in curly braces {} (e.g., {1, 2, &quot;apple&quot;, 2}).</p>
Signup and view all the answers

Which code format prints a statement stating name and food? Assume that name='Chris' and food = 'burger'.

<p>sampleText3 = 'My name is {name} i love {food} and playing {game}' sampleText3a = sampleText3.format(name='Mike', food='burger', game='volleyball') print(sampleText3a) (C)</p>
Signup and view all the answers

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

<p>False (B)</p>
Signup and view all the answers

What functions are described for `String Formatting Functions.

<p>upper(), lower(), capitalize(), title(), split(), replace(), len()</p>
Signup and view all the answers

Describe what a len function does.

<p>count characters in a string,or number of items</p>
Signup and view all the answers

Match the following collection data types with the proper statements.

<p>Variable = A named piece of memory to store a value. Assignment statement = Stores a value into a variable. Data Type = Classifications for what kind of data the variable can hold.</p>
Signup and view all the answers

What code does Input, Float, and Calculate Area perform? Assume that math is imported.

<h1>Get user input for radius (assuming valid input)\nradius = float(input(&quot;Enter the radius of the circle (positive number): &quot;))\n# Calculate area directly\narea = math.pi * radius * radius (A)</h1>
Signup and view all the answers

The correct code is print("Your age is", age) when you want to concatenate integers with string text in python.

<p>True (A)</p>
Signup and view all the answers

Name at least 3 key reasons to use Python.

<p>Easy to Learn and Use, Versatile, Large and Active Community</p>
Signup and view all the answers

_____ produces text output on the console.

<p>print</p>
Signup and view all the answers

Match this with usage for coding.

<p>Offline IDE options = Pycharm, Anaconda/Jupyter Notebook Online IDE options = onlinegdb.com, colab.google replit.com</p>
Signup and view all the answers

Which code follows most rules?

<p>num0 = 5 (C)</p>
Signup and view all the answers

One of three primary logical operators presented include for, or, not

<p>False (B)</p>
Signup and view all the answers

If "1 + 3 * 4" is entered. What number output will there be?

<p>13</p>
Signup and view all the answers

In Python, String placeholders serve as ______

<p>container for strings and numbers</p>
Signup and view all the answers

Match correct code to appropriate number output.

<p>print(3+12) = ___ = 15 print(12-3) = ___ = 9 print(4-3*2%3) = ____ = 4 print(12/3) = ____ = 4.0</p>
Signup and view all the answers

Flashcards

What is Python?

A general-purpose programming language often used for scripting, known for its readability.

What is a Program?

A sequence of instructions that a computer can execute to perform a specific task, requiring compilation.

What is a Script?

Code written in a scripting language that's interpreted to control another software application.

History of Python

Guido van Rossum invented it in the early 90s, named after Monty Python.

Signup and view all the flashcards

Why use Python?

Simplicity, readability, versatility, and ease of use.

Signup and view all the flashcards

Who Uses Python?

Google, Intel, Cisco, and YouTube.

Signup and view all the flashcards

Python Requirements

Python 3 interpreter and an IDE.

Signup and view all the flashcards

Installing Python

Download the latest version from python.org/downloads/.

Signup and view all the flashcards

Using PyCharm

Download the installer, follow the wizard, and select install options.

Signup and view all the flashcards

Create a Python project

Click 'New Project' on the welcome screen.

Signup and view all the flashcards

Create a Python file

Go to Project tool window, right-click and select File | New, then Python file.

Signup and view all the flashcards

Command Line

Type commands directly into the interpreter.

Signup and view all the flashcards

Using PyCharm

Use Run from the context menu or Ctrl+Shift+F10, or click Run inside the editor.

Signup and view all the flashcards

Python Code Execution

The transformation of Python code to byte code by PVM.

Signup and view all the flashcards

Indentation Matters

Defines code blocks instead of braces (4 spaces).

Signup and view all the flashcards

Comments in Python

Lines that are ignored by the interpreter for during execution of the program.

Signup and view all the flashcards

Keywords in Python

Words reserved that should not be used as a variable name.

Signup and view all the flashcards

print Command

Command that produces text output on the console.

Signup and view all the flashcards

Expressions

A data value or set of operations to compute a value.

Signup and view all the flashcards

Precedence

Order in which operations are computed, PEMDAS.

Signup and view all the flashcards

Real

Numeric values that may include decimal part.

Signup and view all the flashcards

Real Number Output

The comparative is between the real numbers.

Signup and view all the flashcards

Math max () command

Returns largest possible integer.

Signup and view all the flashcards

Math ceil() command

Returns rounded version of the number up.

Signup and view all the flashcards

Math sqrt() command

Returns specific square root integer.

Signup and view all the flashcards

Using *

Mathematical equation: from math import *

Signup and view all the flashcards

Direct Ref

Mathematical equation: import math

Signup and view all the flashcards

Relational expressions

Determine True and False.

Signup and view all the flashcards

Logical expressions

The combination of conditions and evaluate accordingly.

Signup and view all the flashcards

Operator Precedence

Python's defined order of operations.

Signup and view all the flashcards

Variables

A named space in memory that stores information.

Signup and view all the flashcards

Assignment

A method called to store value.

Signup and view all the flashcards

Variable Rules

Cannot start with integers and case sensitive.

Signup and view all the flashcards

Data Types

Integers whole numbers (1, 2), Floats (1.2, 4.5), string (“Hello”).

Signup and view all the flashcards

List

Collection data type with ordered format [“Apple”,“Orange”].

Signup and view all the flashcards

Use for Data Type

Function (type()) to check data within code.

Signup and view all the flashcards

Casting

Change or force the data to a data type.

Signup and view all the flashcards

Input

Code: input() to start user input.

Signup and view all the flashcards

String

Text written in code (ex. “The Sky”).

Signup and view all the flashcards

String Placeholders

Special text used to display variables, objects, and other details within string.

Signup and view all the flashcards

Method: upper()

Text is displayed in upper case.

Signup and view all the flashcards

Method: lower()

Text is displayed in lower case.

Signup and view all the flashcards

Method capitalize ()

Method to only capitalize the first word.

Signup and view all the flashcards

Method title()

Method that uses each word.

Signup and view all the flashcards

Method split()

Split phrase by parameters.

Signup and view all the flashcards

Method replace()

Replaces the set parameter.

Signup and view all the flashcards

Method: len()

Counts all text.

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
  • 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 is 7.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 True
  • or - Returns True if at least one operand is True
  • not - 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 case
  • lower() : string to lower case
  • title() : converts each word to upper case
  • captilize() : convert the first word to upper case
  • split(): : splits a string to separated at a certain separator, and returns a list
  • replace() : 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.

Quiz Team

Related Documents

Introduction to Python - Week 3

More Like This

Use Quizgecko on...
Browser
Browser