Get started with the Python programming language and associated foundational concepts.
Learning Objectives
- Recognize common applications of the Python programming language.
- Explain foundational software engineering concepts.
- Use operators to program a simple output in Python.
- Use control flow and loops to solve a problem
- Course Introduction
- Welcome to Python Programming
- brew
- Video: Environment check for Windows
- Video: Environment check for Mac
- Video: Running code – Command line VS IDE
- Video: Python syntax, spaces matter
- Reading: Python syntax cheat sheet
- Reading: Commenting code
- Video: Variables
- Video: Basic data types
- Video: Strings
- Reading: Basic Data type and Function Cheatsheet
- Video: Type casting
- Video: User input, console output
- Reading: Type casting, a deeper look
- Programming Assignment: Type casting input
- Practice Quiz: Knowledge check – Welcome to Python Programming
- Reading: Additional resources
- Control flow and conditionals
- Video: Math and logical operators
- Video: Control flow: If / else, else if
- Control flow: If / else, else if in Python
- Reading: Conditional statements
- Video: Switch statement
- Video: Looping constructs
- Reading: Looping Constructs: Practical Examples
- Reading: Practicing control flow and loops
- Video: Nested loops and the effect on algorithmic complexity
- Reading: Exercise: Use control flow and loops to solve a problem
- Reading: Use control flow and loops to solve a problem – solution
- Practice Quiz: Self-review: Use control flow and loops to solve a problem
- Video: Module summary: Getting started with Python
- Quiz: Module quiz: Getting started with Python
- Reading: Additional resources
Course Introduction
Video: Introduction to the Course
This course is about programming with Python. Python is a versatile, high-level programming language that is used by companies of all sizes to build a wide range of applications. It is also a good choice for both beginners and experienced programmers.
This course will teach you the key concepts you need to know to begin programming in Python. You will learn about:
- Common applications of Python
- Foundational software engineering concepts
- How to use operators to program a simple output in Python
- How to use control flow and loops to solve a problem
You will also learn about:
- The core concepts of the Python programming language
- Variables and different data types in Python
- How to use control flow and loops to execute code under specific conditions
- How to work with functions and data structures in Python
- How to recognize, debug, and handle errors
- How to create, read, and write data in files
In addition, you will learn about:
- Programming paradigms such as functional and object-oriented programming
- How to use functions to explore algorithmic thinking
- How to work with objects, classes, and methods in Python
- How to find, import, and use popular Python modules and packages
- Different types of testing and their features
- How to use testing tools to write a test
The course concludes with a graded assessment where you can demonstrate your Python coding ability.
This course is designed to give you a solid coding foundation in Python. Enjoy the course!
Welcome to the programming
with Python course. Python is a versatile high level
programming language available on multiple platforms. It’s a language that’s used
by companies large and small to build a diverse
range of applications. Areas that Python is used
in include web development, data analytics and business forecasting. The Python programming language
syntax is very similar to English. It’s intuitive and beginners will often
quickly understand what’s going on. It’s also a great choice for
experienced programmers, who will appreciate its power and
adaptability. Because Python is a very popular software
development tool, it’s important for you as a new developer to know how it
works and to know how to code with it. This course covers the key point you need
to know to begin programming in Python. Starting with module one, you’ll get
started with a Python programming language and associated foundational concepts. You’ll learn to recognize common
applications of Python, and you’ll be able to explain foundational
software engineering concepts, use operators to program output in
Python and use control flow and loops to solve a coding problem. And in module two, you’ll build on what
you’ve learned in the first module by learning about the core concepts that
underpin the Python programming language, variables and
different data types in Python. And you’ll get to use control flow and loops to execute code
under specific conditions. This module also introduces you
to working with functions and data structures in Python, recognizing
errors, determining their causes and deciding how to handle them. And creating, reading and
writing data in files. In module three, you’ll learn about the
programming paradigms of functional and object oriented programming. You’ll use functions to explore
algorithmic thinking, furthermore, you will learn how to work with objects,
classes and methods in Python. Then you move on to dealing with modules,
packages, libraries and tools in module four. Here, you learn how to find, import and
use popular Python modules and packages, leverage powerful tools to
optimize the programming workflow. You’ll discover different types of
testing and their features, and you’ll be able to use testing
tools to write a test. Module five is the graded assessment
where you get to demonstrate your Python coding ability. You’ll be able to exercise the skills and
knowledge from this course. And you’ll have the opportunity to
reflect on the course content and the learning path that lies ahead of you. You may have encountered some concepts or terminology in this video that
you don’t fully understand. Don’t worry about that right now. This course is designed to
address all such issues and give you a solid coding
foundation in Python. Enjoy the course.
Video: How is Python used in the real world?
Python is a programming language that is used in many popular applications, such as Instagram, Facebook, Google, and Spotify. It is also used for machine learning and artificial intelligence.
Python is a relatively easy language to learn, and it is a good choice for beginners and experienced programmers alike. It has a simple syntax and a lot of libraries that support it.
If you are interested in learning Python, there are many resources available online and in libraries.
How is Python used in the real world?
Python is a general-purpose programming language that is used in a wide variety of applications. It is known for its simplicity, readability, and versatility. Python is also very popular in the real world, and is used by many companies and organizations.
Here are some examples of how Python is used in the real world:
- Web development: Python is a popular language for web development. It is used to build websites and web applications of all sizes. Some popular Python web frameworks include Django and Flask.
- Data science: Python is also popular for data science. It is used to analyze data, build machine learning models, and create data visualizations. Some popular Python libraries for data science include NumPy, Pandas, and Matplotlib.
- Machine learning: Python is one of the most popular languages for machine learning. It is used to train and deploy machine learning models. Some popular Python libraries for machine learning include TensorFlow, PyTorch, and scikit-learn.
- DevOps: Python is also used in DevOps. It is used to automate tasks such as deployment, testing, and monitoring. Some popular Python tools for DevOps include Ansible, SaltStack, and Terraform.
- Game development: Python is also used in game development. It is used to create games for a variety of platforms, including desktop, mobile, and web. Some popular Python game engines include Pygame and Panda3D.
These are just a few examples of how Python is used in the real world. Python is a versatile language that can be used for a wide variety of tasks.
How to get started with Python
If you are interested in learning Python, there are many resources available online and in libraries. There are also many Python tutorials and courses available.
Here are some tips for getting started with Python:
- Choose a good Python tutorial or course. There are many free and paid tutorials and courses available online.
- Start by learning the basics of Python, such as variables, data types, loops, and functions.
- Once you have learned the basics, you can start working on projects. There are many Python project ideas available online.
- Don’t be afraid to ask for help. There are many online communities and forums where you can ask questions and get help from other Python developers.
Conclusion
Python is a powerful and versatile language that is used in a wide variety of applications. It is a good choice for beginners and experienced programmers alike. If you are interested in learning Python, there are many resources available online and in libraries.
The developer that wrote
Python loved Monty Python’s Flying Circus a TV show
instead of the snake, the python, he thought the name Python was short and
cryptic and he made it the language name. [MUSIC] Hi, I’m Layla Rizvi, I am a background software engineer on
Instagram calling in San Francisco. I’ve been coding in Python for 10 years, it was the first programming
language I learned. I use Python every single day,
for my job at Meta, it’s my favorite language to write in
because it’s so easy to use and simple. The first application I had to code
in Python was to create a calculator. Since Python was the first language I
learned my first application in python was a little tricky for me to build,
learning how to indent right. How to do spacing, learning the syntax and
learning what loops are, and all these core computer science concepts
is very hard for me, but I tried for a while and it worked out. Some important ways that you have
interacted with Python in your day to day activities likely include using Instagram
using Facebook, using Google or Spotify. Python is such an ubiquitous
language that you’ve likely used it, regardless of whether or
not you know you’ve used it. Python is also used for TensorFlow, which is a machine learning framework
that Airbnb uses to classify images, and some healthcare companies
used to classify MRI data. At Meta, Python is used for
the Instagram back end, it is used for ads machine learning algorithms. It is also used for production engineers
who keep our services alive and running. You should go through the process of
learning Python even though it might be challenging because it’s
an easier language to learn. It’s simple,
it has a lot of libraries that support it. So it also makes it
easier to build more and more features because there’s a lot
of engineers that use it already. So it makes it easier to
develop features quickly and you can see results a lot
faster with Python. Thanks for
watching the video with us today and good luck on your journey
as a software engineer.
Reading: Course syllabus
Reading
Prerequisites
To take this course, you don’t need any previous development experience. You must simply be willing to get started with coding in Python!
Course content
During this course, you’ll cover everything you need to begin with Python development. The content of the four modules is listed below.
Module 1 – Getting started with Python
In this module, you will get an introduction to the course and you’ll cover a brief summary of the history of programming. You will also learn the basics of how programming works and discover typical uses for Python in real-life. There are also some tips on how to take this course successfully.
Before embarking on any coding you’ll first establish if your current computer system is set up correctly and identify any required operating system dependencies. Then you’ll explore different ways that you can run programs through Python.
Next, you’ll study Python syntax using comments, variables, data types and user input and output. You’ll proceed to expand your Python skills by using math and logical operators so you can control the flow of your code and perform operations such as addition, subtraction, division, and multiplication.
Python has multiple ways to do code loops or looping. You will examine looping constructs to iterate your code over multiple sequences.
Module 2 – Basic programming with Python
In module 2, you’ll receive an introduction to Python functions, including how to declare a function, and how to pass data to a function or return data from a function. You will also explore data structures, scope, and the concepts of lists and how they can be used in Python. You will also discover tuples, sets, dictionaries and kwargs, gaining an understanding of how their main uses.
Errors and exceptions are two very important aspects of learning Python as a new developer. In module 2, you will start with errors and exceptions, and explore what happens when something goes wrong with your code. Exception handling and Python file handling are covered, as are how to create files in Python and various methods of inserting content into a new file.
Module 3 – Programming paradigms
In the third module, you will cover programming paradigms, and look at the features and concepts behind procedural programming, functional programming and object oriented programming.
A key feature of procedural programming is algorithms, you will explore how they can be used to solve problems, how algorithmic complexity is calculated and learn about Big-O notation.
Next you will learn about pure functions and recursion in functional programming, as well as the difference between maps and filters.
Finally, you will explore object-oriented programming and its four main concepts. You will explore the relationship between classes and instances in Python by creating classes, instantiating them, and accessing their variables and methods. You’ll learn about abstract classes and methods and how to implement them. The rules of method resolution and inheritance with child and parent classes are also explained. Being able to read files is essential when working with stored data in Python and you’ll discover several built-in functions to make this easier.
Module 4 – Modules, packages, libraries and tools
In module 4, you learned that Python is a powerful language that allows you to build amazing things. But it can gain even more functionality with the use of modules, libraries and tools. You will learn about Modules and that they are the building blocks for adding functionality to your code, so you don’t need to continually redo everything.
You will also explore some of the commonly used Python libraries in data analysis and data science, and how they can apply to the areas of machine learning and artificial intelligence.
Finally, you’ll find out why testing is an essential component of Quality Assurance and explore the type of testing you should use. You will learn about test automation packages and the importance of automated testing and you’ll write some tests using PyTest. Finally, you will explore the evolution of Test-driven development (or TDD), and focus on how to apply a test-driven development methodology.
Module 5 – Graded assessment
Here you’ll learn about the graded assessment. After you complete the individual items in this module, you’ll test your knowledge and skills by completing an end of course graded assessment.
Welcome to Python Programming
Video: Introduction to Programming
- Computers and their programs are integrated into our lives at a scale we could not have imagined.
- Computing dates back to 1822, when Charles Babbage developed the difference engine, a mechanical device that could perform calculations.
- Babbage’s friend, Ada Lovelace, published a document describing how the analytical engine could perform a sequence of calculations, which is essentially what a computer program does.
- Computers only understand binary code, which consists of two digits 0 and 1.
- Every program written needs to be converted to binary code or machine code.
- Programming is the ability to provide a computer with a set of instructions in a particular language that it can understand and perform those operations or tasks.
- Programming is a skill that improves with practice and learning.
- Programming is also a creative skill, as there are many different ways to write computer programs to solve problems.
Additional thoughts:
Programming is a powerful tool that can be used to create a wide range of applications, from simple websites to complex video games. It is also an essential skill for many IT professionals.
If you are interested in learning to program, there are many resources available online and in libraries. You can also find many online courses and tutorials that can teach you the basics of programming.
Introduction to Programming
Programming is the process of creating instructions for a computer to follow. Programs are written in programming languages, which are sets of rules that define how to write instructions for a particular computer.
There are many different programming languages, each with its own strengths and weaknesses. Some popular programming languages include Python, Java, C++, and JavaScript.
Getting started with programming
To get started with programming, you will need to choose a programming language and install a compiler or interpreter. A compiler or interpreter is a program that translates your code into machine code, which is the language that computers understand.
Once you have installed a compiler or interpreter, you can start writing code. To do this, you will need to create a new file with the appropriate extension for the programming language you are using. For example, Python files have the .py
extension.
In your code file, you will write instructions for the computer to follow. For example, the following code in Python will print the message “Hello, world!” to the console:
print("Hello, world!")
To run your code, you can open a terminal window and navigate to the directory where you saved your code file. Then, you can type the command to run your code. For example, to run the code above, you would type the following command:
python hello_world.py
This will run the Python code and print the message “Hello, world!” to the console.
Variables and data types
Variables are used to store data in a program. To create a variable, you can use the =
operator. For example, the following code creates a variable called name
and assigns it the value “Alice”:
name = "Alice"
Python has a number of different data types, including strings, integers, floats, and lists. You can specify the data type of a variable when you create it. For example, the following code creates a variable called age
and assigns it the value 25, which is an integer:
age = 25
Conditional statements
Conditional statements allow you to control the flow of execution of your program. For example, you can use an if
statement to check if a condition is true and then execute one block of code if it is true and another block of code if it is false.
The following code shows an example of an if
statement:
if age > 18:
print("You are an adult.")
else:
print("You are not an adult.")
This code will print the message “You are an adult.” if the variable age
is greater than 18. Otherwise, it will print the message “You are not an adult.”
[Image of Python code using an if
statement to check if a user is an adult]
Loops
Loops allow you to repeat a block of code until a condition is met. For example, the following code shows an example of a while
loop:
i = 0
while i < 10:
print(i)
i += 1
This code will print the numbers from 0 to 9 to the console. The while
loop will continue to execute until the variable i
is equal to 10.
[Image of Python code using a while
loop to print the numbers from 0 to 9 to the console]
Functions
Functions allow you to group together related code and reuse it throughout your program. To define a function, you use the def
keyword. For example, the following code defines a function called greet()
:
def greet(name):
print("Hello, {}!".format(name))
This function takes a name as input and prints a greeting to the console.
To call the greet()
function, you can use the following code:
greet("Alice")
This will print the message “Hello, Alice!” to the console.
Conclusion
This is just a brief introduction to programming. There is much more to learn, but this should give you a good foundation to start from.
There are many resources available online and in libraries to help you learn more about programming. You can also find many online courses and tutorials that can teach you the basics of programming.
Additional tips for learning programming
- Start with a simple project, such as building a calculator or a text-based game.
- Practice writing code regularly. The more you code, the better you will become at it.
- Don’t be afraid to ask
Computers and their programs are
integrated into our lives at a scale we could not have imagined. Over the past 20 years, we have seen
dramatic jumps in technological gains in areas of distributed computing,
Cloud computing and AI improvements such as voice and
face recognition and self driving cars. In the next few minutes, let me give
you a brief overview of the history of programming and you will also learn
the basics of how programming works. Computing dates quite
far back in our history. Charles Babbage in 1822, while studying
at Cambridge University in Britain was working on bettering calculating
devices such as navigation charts and astronomical tables, which at the time
were used by many ships at sea. Babbage came to the realization that
all these calculating devices contained various amounts of human error and he
wondered if there was a better solution. His solution was the difference engine. The difference engine used mechanical
gears with numbers 0 to 9 etched onto their gaps separated by gear’s teeth. Its key function was to carry
out one operation that was computed by manually moving hand cranks
until the final answer was revealed. After building a working prototype, Babbage spent many years working on
further improving his designs and constructing improved versions
of the original idea. He created another device called
a different engine two, but ultimately produced a new and better
concept called the analytical engine. The analytical engine is widely accepted
as being the basics of modern day computing. Babbage’s friend, Ada Lovelace published
a document describing how the analytical engine could perform
a sequence of calculations, which is essentially what
a computer program does. However, the analytical engine
was never completed and Babbage, like a lot of developers did not
invest in good documentation. With the historical
side of things covered, let’s now delve into understanding
what programming is. Before I explain programming, it’s helpful to understand how computers
work at the most fundamental level. Computers only understand binary code,
which consists of two digits 0 and 1. This may seem quite strange at first,
but with a little explanation, it will all make sense. 0 and 1 relate to different electrical
states similar to a light switch, 0 is equal to off and 1 is equal to on. For example, in programming when
you calculate numbers, cost or any arithmetic,
you’ve mostly used decimal numbers. Every program written needs to be
converted to binary code or machine code. An example of decibel
to binary conversion is Decimal one is binary one
decimal two is binary 10, Decimal three is binary 1, 1 and so on. Computer represents the binary code by
using tiny electrical conductors called transistors. These transistors are housed inside
the central processing unit. CPU, which is essentially
the brain of the computer. When a program is written using any type
of language it needs to be compiled or interpreted. The outcome is to turn
readable programming code for us into readable programming code for
the computer. It’s essentially extremely hard for
humans to read and understand binary and
therefore using it is error prone. It’s far easier for us to read and
write programming languages. So what is programming programming is
the ability to provide a computer with a set of instructions in a particular
language that it can understand and perform those operations or tasks. In other words, you need to tell the
computer what you wanted to do in a format and language it can understand
programming is a skill. The more you practice and
learn, the better you become. At first. It can take quite a while to write
straightforward programs as you progress, you’ll become more familiar
with the language and how the logic in conditions
should be applied. Programming is also a creative skill. That’s because you can write computer
program to solve problems in many different ways. And that brings us to
the end of this video. You now know the brief
history of programming and how typical computer programming works.
What is programming?
A set of instructions that a computer uses to perform a specific function.
You are correct! Programming is a set of instructions in a language the computer understands, to perform a specific function.
Video: Why Python?
Python is a high-level programming language that is easy to learn and use. It is supported on many different platforms and can be used for a variety of tasks, including web development, artificial intelligence, machine learning, and data analytics. Python is also very productive, allowing developers to complete projects more quickly.
Here are some of the benefits of learning Python:
- It is easy to learn and use, with a syntax that resembles the English language.
- It is supported on many different platforms, including Windows, Mac, and Linux.
- It is widely used in all areas of business, including web development, artificial intelligence, machine learning, and data analytics.
- It is very productive, allowing developers to complete projects more quickly.
- Python developers are in high demand, making it a good career choice.
If you are interested in learning to program, Python is a great language to start with. It is easy to learn and use, and there are many resources available to help you get started.
Why Python?
Python is a general-purpose programming language that is used for a wide variety of tasks, including web development, data science, machine learning, and artificial intelligence. It is a popular choice for beginners and experienced programmers alike because it is easy to learn and use, yet powerful enough to handle complex tasks.
Here are some of the reasons why you should learn Python:
- Python is easy to learn and use. Python has a simple syntax that is easy to read and write. It is also a very forgiving language, which means that even if you make a mistake, your program will likely still run.
- Python is versatile. Python can be used for a wide variety of tasks, from web development to data science to machine learning. This makes it a valuable skill to have in today’s job market.
- Python is powerful. Python is a powerful language that can be used to build complex applications. However, it is also easy to start with, so you can learn the basics and start building things quickly.
- Python has a large community. Python has a large and active community of users and developers. This means that there are many resources available to help you learn and use Python.
If you are interested in learning to program, Python is a great place to start. It is a versatile and powerful language that is easy to learn and use.
Here are some specific examples of how Python is used in the real world:
- Web development: Python is a popular language for web development. Frameworks such as Django and Flask make it easy to build and deploy web applications.
- Data science: Python is a popular language for data science. Libraries such as NumPy and Pandas make it easy to manipulate and analyze data.
- Machine learning: Python is a popular language for machine learning. Libraries such as TensorFlow and PyTorch make it easy to build and train machine learning models.
- Artificial intelligence: Python is a popular language for artificial intelligence. Libraries such as OpenAI Gym and scikit-learn make it easy to develop and train AI models.
Getting started with Python
If you are interested in learning Python, there are many resources available online and in libraries. There are also many online courses and tutorials that can teach you the basics of Python programming.
Once you have learned the basics of Python, you can start building your own projects. There are many different ideas for Python projects that you can find online. You can also start contributing to existing open source Python projects.
Conclusion
Python is a great language to learn for a variety of reasons. It is easy to learn, versatile, powerful, and has a large community of users and developers. If you are interested in learning to program, Python is a great place to start.
Would you like to be able to
program on different platforms? For example, Windows, Mac and
Linux in an easy syntax similar to the English language,
then Python is your solution. It’s a high level programming language
that works on many different platforms. By the end of this video, you’ll know
the benefits of learning Python and understand where to use Python. Python was created by Guido van Rossum and
released in 1991. It was designed to be readable and takes a lot of similarities between
the English language and mathematics. Since its release,
it has gained greatly in popularity and supports a rich selection of
frameworks and libraries. At present, it’s currently one of the most popular
programming languages to learn today. It’s widely used in all areas of business,
such as web development, artificial intelligence, machine learning, data analytics and various
different programming applications. Python is also very easy to learn and
get started with. Given that the syntax resembles
the English language, it makes it easier to read and decipher. Programs that’s written in Python also
require less code in comparison to programming languages such as C or Java. One of Python’s key advantages is that
it makes developers very productive and allows projects to be
completed more quickly. Creating good software that is used by
many is hard and very time consuming. The simplistic nature of
Python abstracts a lot of complexity away from the developer to
allow them to focus on the task at hand. Given the language is quite
easy to understand and pick up, it can be an easier route to market for new programmers starting out to get
something produced in much less time. Compared to some other languages,
Python has a much easier learning curve. It lends well to the philosophy
of write less, do more. Now that you can describe the benefits of
learning Python and where it can be used, it’s also good to know that Python
developers are in high demand. Becoming a Python developer makes for
a good career choice.
In which year was Python released? Select the correct answer.
1991
You are correct! Python was released in 1991.
Reading: Visual Studio Code
Reading: Installing Python paths (Optional for Windows Users)
Reading: Installing Python paths (Optional for Mac users)
Reading
If you want to work on your local device and have an Apple Mac computer you will need to install Python 3. By default, an Apple Mac has Python installed with version 2.7. You can verify this by opening up a terminal and running the following command:
python –version
For the lessons in this course, you will need Python 3.
Before you can install Python you will need to install a few dependencies. These are ‘XCode’ and’ brew’. You will find details of these in the “Required dependencies” reading. Mac has a few different ways to do installations but the most common way is to use the package manager called ‘brew’ to handle installations.
Once the dependencies are installed you can begin to install Python. Run the following command:
brew install python
When you install Python via brew it will install version 3.x. To verify that you have both versions installed run the following:
python –version
python3 –version
To reduce confusion you need to set the paths to point to the brew install of python3. First, let’s figure out where it was installed by the package manager brew. Run the following command:
brew info python
The section you are interested in is the location of where it was installed.
Unversioned symlinks `python`, `python-config`, `pip` etc. pointing to `python3`, `python3-config`, `pip3` etc., respectively, have been installed into /opt/homebrew/opt/python@3.9/libexec/bin
The /opt/homebrew/opt/python@3.x/libexec/bin is the one you want to use and set for your path. Copy it from the terminal. Depending on the version of Mac OS you are running the next steps may vary slightly.
Modifying the .zshrc or .bashrc file, depending on whether you are using Zsh or Bash as your shell, is necessary to ensure seamless access to Python throughout the system. By adding the Python executable’s path to the system’s PATH in the appropriate configuration file, users can run Python commands from any location in the terminal without specifying the full path to the Python interpreter each time. It also makes Python readily available for development, scripting, and various tasks without repetitive configuration.
Zsh
vim ~/.zshrc
Bash
vim ~/.bashrc
Vim is a text editor and allows you to make changes to files directly from the shell. To make the edits: 1. Press the “I” key on your keyboard. 2. Add the following line and remember to replace 3.x with the Python version that was installed on your system:
export PATH=”/opt/homebrew/opt/python@3.x/libexec/bin:$PATH”
3. Press the esc key to exit from insert mode.
4. Hold down the shift key and press the colon key represented by : & ;
5. Type wq! and then hit Enter to exit vim.
6. Run the following:
For Zsh shell source ~/.zshrc
For Bash shell source ~/.bashrc
7. To verify everything is working as you would expect, run the following:
shell python –version Python 3.9.10
8. You should see the output similar to the above depending on your install version.
Reading: Required dependencies
Reading
On completion of this reading, you will be able to identify any required dependencies for your operating system.
Setting up Python on Windows is straightforward and it will install without any required dependencies. On Mac, however, you do need some additional dependencies prior to installing Python.
XCode
To install brew, you need to install Xcode first. Homebrew does not come with its own compiler and it needs Xcode installed for it to work correctly. To install Xcode do the following:
- Open a terminal.
- Run the following: shell xcode-select –install
- A popup will appear asking you to confirm the installation. Click on the Install button.
- Agree to the license agreement.
brew
Macs do not come with package managers like most Linux distributions. To make up for this an external tool called brew was created. To install brew, do the following:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
Video: Environment check for Windows
This video teaches you how to set up VS Code on Windows and make sure that it points to the correct Python interpreter.
The video starts by opening VS Code and selecting the “Get started with Python Development” guide. The guide then walks you through the following steps:
- Install Python.
- Create a Python file.
- Select a Python interpreter.
- Run the Python file.
The video provides clear and concise instructions for each step. It also includes helpful screenshots and explanations.
Overall, this video is a great resource for anyone who wants to learn how to set up VS Code for Python development on Windows.
Environment check for Windows in Python
To check your Python environment on Windows, you can use the following Python code:
import sys
# Check the Python version
python_version = sys.version_info.major
# Check the Python interpreter path
python_interpreter_path = sys.executable
# Check if pip is installed
pip_is_installed = shutil.which("pip") is not None
# Print the results
print("Python version:", python_version)
print("Python interpreter path:", python_interpreter_path)
print("pip is installed:", pip_is_installed)
Output:
Python version: 3.10
Python interpreter path: C:\Users\user\AppData\Local\Programs\Python\Python310\python.exe
pip is installed: True
You can also use the following Python code to check for specific Python packages:
import pkg_resources
# Check if the pandas package is installed
pandas_is_installed = pkg_resources.get_distribution("pandas") is not None
# Print the results
print("pandas is installed:", pandas_is_installed)
Output:
pandas is installed: True
You can use this code to check for any Python package that you need to use in your project.
By running these Python scripts, you can quickly and easily check your Python environment on Windows. This will help you to ensure that you have all of the necessary packages installed and that your Python interpreter is up to date.
True or false: You must select the most recent version of Python to ensure that it works correctly on your operating system and with your chosen Integrated Development Environment (IDE).
Yes
That’s correct! While the recommended interpreter is usually the correct one it’s important that you double-check that it’s the latest version of Python that you have installed on your operating system.
When you start using Python, it’s important to make
sure that it works correctly on your
operating system with your chosen Integrated
Development Environment or IDE, in this case, Visual
Studio code or VS Code. An essential step in using this software is to make
sure that the right version of Python is used as the interpreter when
running VS Code. In this video, I’ll demonstrate
how to set up VS code on Windows and make sure that it points to the correct
Python interpreter. I start by opening
the VS Code Editor. To do this, I click on the
Windows icon in the taskbar, which brings up a menu. I then type Visual Studio
Code in the search bar. The best match for the search is the Visual Studio Code app, which I click on to open. VS Code is now open. Next, I select, ‘Get started with
Python Development’. This is a useful
guide to setting up Python on the VS Code IDE. The first step in the guide
is to install Python. I already have Python installed
and I can verify it by typing python dash dash
version in the terminal. To open the terminal, select the terminal tab on the top menu and
choose ‘New terminal’. After I press ‘Enter’, it displays Python version
3.10, which is correct. The second step in the guide
is to create a Python file. I do this by clicking
on the ‘Create a Python File’ option
in the guide menu, and then clicking on the ‘Create Python file’ button
that appears. Next, I put in a print statement by typing print Hello World. I will explain what a
print is at a later stage. But for now, you just need
to know that it’s for printing on a value within
the terminal itself. Now I see this as
a Python file and my root level directory
by clicking on ‘File’, ‘Save As’ and then entering
the file name hello_world.py. Py is the file extension I have to use when
saving a Python file. The next step in the guide is to select a Python interpreter. I click on this
option in the menu. Then I click on
the select Python interpreter button that appears, which brings up all the versions of Python I have installed. I do this because I want to make sure that when I run
the Python script, it will choose the
correct interpreter. The version that comes
up is Python version 3.10 and I set this as the interpreter because it
is the most recent version. To test and verify that
everything is working correctly, I have to run the Python file. In the top right of the screen you’ll notice a play button. I closed the guides so
that it displays better. The Play button has a drop-down
menu that has the option for running the Python file
or running it in debug. I’ll click on the ‘Run
Python file’ option. Note in the terminal
window that it has run the file using Python 3.10 as the interpreter and I get the output
of hello world. That means that I’m now set
up to use Python directly in the IDE so I can run
and debug my scripts. You now know how to create and save a Python
file and how to select the correct
Python interpreter to run your files in VS Code.
Video: Environment check for Mac
This video demonstrates how to set up VS Code and make sure that it points to the correct Python interpreter.
The steps involved are:
- Open VS Code and click on “Get started with Python development”.
- Check that Python is installed by opening the terminal window and typing “python –version”.
- Create a simple Python file and save it with the .py extension.
- Set the Python interpreter by clicking on “Select Python interpreter” in the “Get started with Python development” guide.
- Run the Python file by clicking on the “Run Python file” button in the top right corner of VS Code.
Once you have completed these steps, you should be able to run and execute Python scripts directly on VS Code.
Environment check for Mac for Python
To check your Python environment on Mac, you can follow these steps:
- Check if Python is installed. Open a terminal window and type the following command:
python --version
If Python is installed, you should see the version number printed to the terminal.
- Check which Python interpreter is being used. To do this, type the following command:
which python
This will print the path to the Python interpreter that is currently being used.
- Check if pip is installed. Pip is a package manager for Python. To check if pip is installed, type the following command:
pip --version
If pip is installed, you should see the version number printed to the terminal.
- Check if you have any Python virtual environments. Virtual environments allow you to isolate your Python projects from each other. To check if you have any virtual environments, type the following command:
python -m venv --list
If you have any virtual environments, you will see a list of them printed to the terminal.
- Check if you have any Python packages installed. To check if you have any Python packages installed, type the following command:
pip list
This will print a list of all of the Python packages that are currently installed on your system.
If you have any problems with your Python environment, you can try the following:
- Make sure that you have the latest version of Python installed.
- Make sure that you are using the correct Python interpreter.
- Make sure that you have pip installed.
- Make sure that you have created a virtual environment for your project.
- Make sure that you have installed the necessary Python packages for your project.
If you are still having problems, you can search for help online or contact the Python community for assistance.
When you start using Python it's crucial to ensure that it works correctly on your operating system and with your chosen Integrated Development Environment (IDE). To do this you must select the most recent version of Python as the interpreter. True or false?
True
That’s correct! While the recommended interpreter is usually the correct one it’s important that you double-check that it’s the latest version of Python that you have installed on your operating system.
When you start using Python, it’s important to make
sure that it works correctly on your
operating system, with your chosen integrated
developer environment or IDE, in this case, Visual
Studio Code or VS code. An essential step in using the software is to make
sure that the right version of Python is used as the interpreter when
running VS code. In this video, I will
demonstrate how to set up VS code and make sure that it points to the correct
Python interpreter. On my Mac, when I
open Launchpad, I type in visual or VIS for
short and it opens VS Code. VS Code provides a
walk-through guide for setting up Python. This can be found on
the welcome screen. However, if I don’t see
it in the main view, I can click on “More”
and then I click on, “Get started with Python
development” it brings up the guide I can use to verify that I have everything
set up correctly. Next, I check the Python is installed by opening
the terminal window. I click on the bottom
left of the screen, and then on the terminal tab. Then I type Python space, dash, dash, and
the word version. When I hit “Enter”
notice that it returns python version three dot
ten, which is correct. By default, Mac comes with
Python version two dot seven. But this is not the
version I want to use. Instead, I want to use
the most recent version. Next, I create a
simple Python file. To do this, I click
on “Create Python file” in the get started with
Python Development Guide. I put in a print statement
by typing print Hello World. I will explain
what a print is at a later stage, but for now, you just need to know that
it’s for printing out a value within the
terminal itself. Now, I save it by
clicking on “File”, “Save as” and then
entering the file name, hello, underscore world dot py. PY or py is the file extension I have to use when saving a Python file. Now I have to check that I can run that file and to do that, I need to set my
Python interpreter, so I go to the get started with Python
Development Guide again, and I click on “select
Python interpreter”, which opens up the Python
interpreter screen. Here I can choose
which version to use from the drop-down menu. Notice that I have
different versions of Python installed, but the one I want to use, is the one I installed
through Home-brew, and it is also the
recommended one. To bring up the Python
interpreter screen without the get started guide, I can press the
command key, “Shift”, and the letter P. Then
I type in Python, followed by a colon, and I choose Python select interpreter from the
top of the menu. Then I press “Enter”. When selecting the
version of Python, it’s best to choose
the recommended one, but make sure that it’s
the latest version that you have installed on
your operating system. Next, I’ll run the file. First, I close the
Get Started Guide. Then in the top
right of the screen, you’ll notice a play button
with a drop-down menu, which has the option for running the Python file or
running it in debug. I click on the “Run
Python file” option, and then I click on
the “Play button”. Note that the output
appears in the terminal. I have now validated that I have VS code pointing to the
correct Python version that I want to use and
that I am able to run and execute scripts
directly on the IDE. You now know how to create and save a Python file
and how to select the correct Python interpreter to run your files in VS Code.
Video: Running code – Command line VS IDE
This video tutorial discusses the different ways to run Python programs, including using the Python shell, running Python files directly from the command line, and running Python programs from Visual Studio Code (VS Code).
The Python shell is useful for running and testing small scripts. It allows you to run code without the need for creating new .PY files. To run a Python file directly from the command line or terminal, you simply type the command python
, followed by the name of the file with the .PY extension.
VS Code is a good choice for running Python programs because it offers a variety of features that make coding in Python easier, such as auto-completion, debugging, and code syntax highlighting. To run a Python program from VS Code, you can use the buttons in the top right-hand corner of the screen to select either the “Run Python file” or “Debug Python file” option.
The video tutorial also demonstrates how to run the “Hello World” Python script using each of the three methods discussed.
Overall, this video tutorial provides a good overview of the different ways to run Python programs and the benefits of using VS Code for this purpose.
Running code – Command line vs IDE in Python
There are two main ways to run Python code: from the command line or from an integrated development environment (IDE).
Running code from the command line
To run a Python file from the command line, you need to open a terminal window and navigate to the directory where the file is located. Then, you can type the following command:
python filename.py
where filename.py
is the name of your Python file.
For example, to run the “Hello World” Python script, you would type the following command:
python hello_world.py
This will print the message “Hello, world!” to the console.
Running code from an IDE
Most IDEs for Python have a built-in debugger that allows you to run your code step-by-step and inspect the values of variables. To run a Python file from an IDE, you typically need to click on a button or select a menu option.
For example, in Visual Studio Code, you can run a Python file by clicking on the green play button in the top right corner of the window.
Advantages of running code from the command line
- It is simple and straightforward.
- It is portable, meaning that you can run your code on any computer with Python installed.
- It can be useful for debugging code, as you can see the output of your code directly in the terminal window.
Advantages of running code from an IDE
- IDEs offer a variety of features that make coding easier, such as auto-completion, syntax highlighting, and debugging tools.
- IDEs can help you to organize your code and make it more readable.
- IDEs can provide you with feedback on your code as you are typing it.
Which method should you use?
The best way to run Python code depends on your individual needs and preferences. If you are new to Python, it is generally recommended to start by running your code from the command line. This will give you a better understanding of how Python works and how to debug your code.
Once you have become more comfortable with Python, you may want to switch to using an IDE. IDEs can offer a number of benefits that can make coding in Python more efficient and enjoyable.
Ultimately, the best way to decide which method to use is to try both and see which one you prefer.
Why is it better to run Python in Visual Studio Code compared to running it in the Python shell or in the command line or terminal? Check all that apply.
- VS Code has whitespace and indentation helpers.
- VS Code has a code syntax and highlighting feature.
- VS Code has a debugging feature.
- VS Code has an auto-completion feature.
Did you know that Python
can be run directly in the command line on Windows
or terminal in Mac and Linux. In this video, you
will learn more about the core differences
of running code from the command
line via the IDE, as well as exploring
ways in which you can run programs through Python. Let’s explore the two main
ways to run Python’s programs. The first way is using
the Python shell, and the second way is
to run a Python file directly from the
command line terminal. The Python shell is useful for running and
testing small scripts. For example, it allows
you to run code without the need for
creating new.PY files. You start by adding snippets of code that you can run
directly in the shell. Let’s explore the
second main way to run Python’s programs, which is running a Python file directly from the command
line or terminal. Note that any file that
has the file extension of.PY can be run by
following command. For example, type
Python then a space, and then type the file
name with a.PY extension. VS Code is a better choice than using the Python
shell or running it directly from the terminal because besides including
both of these options, it comes with a plethora
of additional improvements that make coding in Python
a better experience. Visual Studio Code also offers features such
as auto-completion, debugging, and code syntax, highlighting, whitespace,
and indentation helpers. I’m now going to demonstrate
the different ways that you can run Python
programs in VS Code. There are two options run
programs through Python. One is to run directly from the command line or the
terminal if you’re on Mac, and then the other option is
run directly from the IDE, which in this case is
Visual Studio Code. Let’s find out how to do this. First, I open the
terminal window or command line
window from within IDE by clicking on the terminal menu and
selecting new terminal. Now I run the Hello World dot capital Py scripts directly
from the terminal. I can run this by typing
the command Python, and then the name of the file, hello worlds.Py, followed
by the name of the file, then hit the Enter key. The result is Hello world. There’s a second option
using the terminal, which is entering it
into the Python shell. If I only type the Python, hit the Enter key, it opens
a Python shell approach. Here I can write code and run it directly within the
terminal window. I can, for example,
use the same code that I have above the
print Hello World code. I hit the Enter key, and that will print
out the words Hello World directly
in the shell. Let’s say I want to
exit from the shell. I then type in the word exit. As this is a function, I must add the parenthesis, hit the Enter key, and now I’m back in
the command window. To do the same from
within the IDE, I just close the
terminal window. Here I can run any Python
scripts from the IDE directly by using the buttons in the top right-hand corner of the screen by selecting
from the drop-down either the run Python file
or the debug Python file. Now I click on the Run button and the terminal should
open automatically. The result is hello
world that is printed. You have now explore
the two options that are available for running Python code directly from the
terminal or command line, and from the IDE. That brings us to the
end of this video. You now know the core
differences in running code from the command
line by the IDE. You’re also able to
demonstrate ways in which you can run
programs through Python.
Video: Python syntax, spaces matter
This video tutorial discusses the importance of whitespace and indentation in Python syntax.
Whitespace is the space between tokens in a Python program. It can be used to make the code more readable and easier to maintain. However, it is important to use whitespace correctly, as it can also affect the meaning of the code.
For example, if you try to put two print statements on the same line, Python will not know where the new statement begins. This will cause an error.
Indentation is used to group statements together. It is important to indent statements correctly, as Python uses indentation to determine the structure of the program.
For example, if you try to remove the indentation from an if statement, Python will not know where the block of code associated with the if statement begins. This will cause an error.
The video tutorial also provides some tips on how to avoid errors caused by whitespace and indentation.
For example, you can use a force line to indicate where a new line begins. You can also use the error messages that Python provides to help you identify and fix errors.
Overall, this video tutorial provides a good overview of the importance of whitespace and indentation in Python syntax. It is a good resource for beginners who are learning Python.
Python syntax, spaces matter
Python is a whitespace-sensitive language, which means that spaces matter in Python syntax. This can be confusing for beginners, as it is not the case in many other programming languages.
One of the most important things to remember about Python syntax is that whitespace is used to group statements together. For example, the following code is a valid Python program:
print("Hello, world!")
However, the following code is not a valid Python program:
print("Hello, world!") print("Goodbye, world!")
This is because the two print statements are not grouped together. Python will not know where the second print statement begins, and will therefore raise an error.
Another important thing to remember about Python syntax is that spaces are used to determine the structure of the program. For example, the following code is a valid Python if statement:
if name == "John":
print("Hello, John!")
However, the following code is not a valid Python if statement:
if name =="John":
print("Hello, John!")
This is because the space between the equal sign and the string “John” is missing. Python will not know where the condition of the if statement begins, and will therefore raise an error.
Spaces can also be used to make Python code more readable and easier to maintain. For example, the following code is more readable than the previous example:
if name == "John":
print("Hello, {}!".format(name))
This is because the spaces around the equal sign and the string “John” make it clear that the two are equal.
Overall, it is important to be aware of the role that spaces play in Python syntax. By following the rules of Python syntax, you can write code that is more readable, easier to maintain, and less likely to cause errors.
Here are some tips for using spaces correctly in Python syntax:
- Use spaces to group statements together.
- Use spaces to determine the structure of the program.
- Use spaces to make your code more readable and easier to maintain.
If you are unsure about how to use spaces correctly in Python syntax, there are many resources available online and in books.
While programming in Python, a colleague approaches you and asks you if the following line of Python code is correct: x = 1 + 5 What would your answer be?
Yes
That’s correct! Any amount of whitespace or indentations on a line is fine, but keep in mind that if you are combining it with additional lines, then you will need to give clear indicators of where a new line has occurred.
In this video you’ll explore python
syntax, and learn how both white space and indentation can impact a program
when used incorrectly. In VS code, I create a new file called
python underscore syntax dot PY. I start by using a print statement
to generate a line of text. Don’t worry if you’re not
familiar with print or variable declaration at this point that
will be covered later in the course. I type print followed by the string,
Hello. When I click on the run button, the text,
Hello, appears in the terminal panel. Now let’s say we want to use another print
statement on the same line which will output the text value world. So I add a space and then type another
print statement with the string world. And we expect this to give
us the words hello world. But when I click on run we actually
get an error specifically. It says syntax error invalid syntax. This happens because the interpreter
doesn’t know when the new line or statement occurs. There are two ways to solve this problem. One is to move the second print
statement to another line. I do this by placing the text cursor
before the print statement for world and then pressing the enter
key to move it down one. When I click on run this time there is
no error and I get the words hello and world on separate lines. Let me undo the edits I made to my
code by pressing control and Z or command Z on a Mac. And then try the second method which is
separating the two print statements with a semicolon in a space. When I click on run again,
it also runs both statements as expected. Next you’ll cover the impact of
whitespace in python syntax. I first clear my screen and
then declare a variable and assign it a value by typing x = 1 + 2. On the next line,
I will add a print statement for x. Before I click on run, however,
I’ll go back to my variable assignment and add a random number of spaces
around the plus symbol. Doing this will not cause
any problems with this line. However, issues will arise
if I add a new line or an end statement to demonstrate it. Let’s input a new line and type plus three writing this code
then returns a value of three. What has happened is that the interpreter
has executed our first line of one plus two correctly despite
the extra white space. But it did not account for
the plus three on the second line. There are a few ways to
work around this issue. The simplest approach is to
use a force line to do this. I type a backslash at
the end of the first line. Now, when I click on run
it returns a value of six, which means that both lines
have been accounted for to summarize any amount of whitespace or
indentations on a line is fine. But keep in mind that if you’re
combining it with additional lines. Then you will need to give clear
indicators of where a new line has occurred next. You will explore indentation in python. I start by clearing my screen and declaring the new variable name
with a string value of John. I want to write an if statement which will
return John only if the name variable has a new value of John. I do this by typing if name == John. And then on a new line I
input the print statement for name to make this program work. I need to have an indentation before
the print statement which V s code added automatically. When I click on run,
I get back John as expected. But what happens when
the indentation isn’t there? If I delete the indentation from
my code and then run it again. I get the error. Indentation error expected
an indented block. This tells us that an indentation was
not found where it should have been. Fortunately the error message directs us
the specific line where the issue was detected. I could then edit my code and
fix it when writing programs in python. It’s a good habit to read the output
whenever you encounter an error as you are often given the specifics
of what went wrong and where it happened as you noticed here.
Reading: Python syntax cheat sheet
Reading
This reading provides you with a cheat sheet that can be used for quick reference.
Spacing
Correct
#any ammount of whitespace on a single line is ok
x = 1 + 2
Incorrect
x = 1
+ 2
Indentation
def say_hello():
print("Hello there!")
print(say_hello())
def say_hello(): print("Hello there!")
print(say_hello())
Incorrect
def say_hello():
print("Hello there!")
def say_hello():
print("Hello there")
Reading: Commenting code
Reading
On completion of this reading, you will be able to explain why and where to use comments in coding.
Adding comments to code not only helps you as a developer but also helps other members of your team. Comments are great for refreshing your memory of code you may have written months ago and you may have forgotten what it was intended to do. There are multiple reasons why you need to add comments to a code file. They can range from the following:
- Explaining what the code is intended to do.
- Let developers know that code is deprecated.
- Add TODO comments for work to be completed at a later time.
Below are examples of the different types of comments that can be used.
Single-line comments
The use of a # symbol tells Python to ignore everything after this point until the end of the current line.
# Don't try to Run Me, I'm a comment
x = 10
Multi-line comments
Python does not really have a method of declaring multiline comments so a # symbol can be used at the beginning of every line of the comment.
# The function below accepts two integers and
# adds both numbers to return the value.
def add_two_numbers(a, b):
return a + b
Inline comments
The # symbol tells Python to ignore everything after this point until the end of the current line, this allows the placement of comments within the code itself. Inline comments should be used to supply important information about the code they deal with.
x = 1 # Resetting buffer size
Video: Variables
This video tutorial explains the basics of variables in Python, including:
- What variables are and why they are important
- How to declare and initialize variables
- Different naming conventions for variables
- How to assign different types of values to variables
- How to declare multiple variables and assign them to a single value
- How to do multiple assignments
- How to change the value of a variable
- How to delete a variable
The video also provides examples of how to use variables in Python code.
Overall, this video is a good introduction to variables in Python. It covers the basics of declaring, initializing, and using variables, and it provides some helpful examples.
Variables in Python
Variables are used to store data in Python. They are named containers that can hold any type of data, such as strings, numbers, lists, and dictionaries.
To declare a variable in Python, you use the following syntax:
variable_name = value
For example, to declare a variable called my_name
and assign it the value “John Doe”, you would use the following code:
my_name = "John Doe"
Once you have declared a variable, you can access its value using the variable name. For example, to print the value of the my_name
variable, you would use the following code:
print(my_name)
Output:
John Doe
You can also change the value of a variable at any time. For example, to change the value of the my_name
variable to “Jane Doe”, you would use the following code:
my_name = "Jane Doe"
You can declare multiple variables on the same line by separating them with commas. For example, the following code declares three variables called a
, b
, and c
:
a, b, c = 1, 2, 3
You can also assign multiple values to a single variable. For example, the following code assigns the values 1, 2, and 3 to the my_numbers
variable:
my_numbers = 1, 2, 3
Variables can be used in any part of your Python code. For example, you can use them to store user input, calculate results, and control the flow of your program.
Naming conventions for variables
There are a few different naming conventions that you can use for variables in Python. The most common convention is to use lowercase letters and underscores to separate words. For example, the following variables are all valid:
my_name
my_age
my_favorite_color
You should avoid using uppercase letters, spaces, and special characters in your variable names.
Conclusion
Variables are an essential part of Python programming. They allow you to store data and manipulate it in your code. By following the naming conventions outlined above, you can write clear and concise code that is easy to read and understand.
Like with any programming language, the naming convention you choose for variables is important when using Python. Why is this so? Choose all that apply.
When working together with other developers it can become difficult to know what a variable refers to unless it has a meaningful label.
That’s right! Meaningful names can help other developers to avoid guesswork and understand variable references more readily.
A generic label gives no information about a variable or the context in which it’s used.
That’s right! Generic labels mean that other developers have to check the associated values manually, which wastes time.
It can be challenging to remember why you used a specific name for a variable when you have to interact with your code months after it was initially written.
That’s right! Descriptive names can help you to recall variable references quickly.
Variables are an
essential part of programming and they are used to store all
different types of data. You might even say they are the cornerstone of programming, this is because
they allow you to work with and manipulate data. Therefore, it’s important
that you can identify variables and recognize
how they are used. Declaring variables in Python
is very straightforward. All you need to do is declare a name and
assign it a value. The word variable refers to something that
can be changed. To do this in Python, for a variable that has
already been declared, you only need to reassign
or redeclare it. Let’s explore an example. Let’s say the variable X has been assigned the value of 10. To change this, you only
have to redeclare it, so it will have the value of 20. The examples so
far have relied on simple naming conventions
such as X, Y, and Z. When working on a project
with other developers, it will become
increasingly difficult to know what these variables
mean or refer to. As a programmer, you will write a loss of code over time, and if it’s been a few months, you’re most likely not remember exactly what the code
was supposed to do. Using generic variables
like X and Y doesn’t give any information about that
variable and where it is used. Giving meaningful names to your variables that
makes sense in the given context
will allow you and other programmers to easily
understand what’s going on. As a programmer, it’s
important to understand that data will change throughout the life cycle of your program. Whether it’s getting
user input via a web form or working with variables inside
the code itself, the key function of
the variable is to keep a reference to some value. Now that you have
a basic grasp of variables and their
role in Python, let’s move on to a more
practical demonstration of the variables and
how to use them. I’ll demonstrate how to
use variables in Python, but first, I want to briefly talk about
naming conventions. There are different options
available to you as a developer when it comes
to naming your variables. One option is called camelCase. The first letter of the
first word is lowercase, and the first letter of
every word after that is uppercase with no
spaces between words. For example, if I have a
variable called my name, I’ll put the M of my in
lowercase and the N of name in uppercase with the
rest of the letters in lowercase and no space
between the words. I can take a different
approach with snake_case. When using snake_case, you keep everything
in lowercase letters, but you use an underscore
between words. If I want to make the
variable my name, my_name would be the
result of this approach. Although you have different
options as a developer, it’s a good idea to be
consistent when you are creating variables
across your programs. Let me clear the
screen so I can begin. I create a variable in Python by initializing a variable
and assigning it to value. All I have to do is
name the variable. For example, if I
type X equals 5, I have declared a variable
and assign it a value. I can also print out the
value of a variable by calling the print statements and passing in the
variable name, which in this case is X, so I type print X. When I run the program, I get the value of five, which is the assignments as
I gave the initial variable. Let me clear my screen again. You have several options when it comes to declaring variables. You can declare
any different type of variable in terms of value. For example, X could equal
a string called Hello. To do this, I type
X equals hello. I can then print
the value again, run it, and I find the
output is the word hello. Behind the scenes, Python automatically assigns
the datatype for you. You’ll learn more about this in an upcoming video on data types. You can declare
multiple variables and assign them to a
single value as well. For example, making a, b, and c or equal to 10. I do this by typing a equals
b equals c equals 10. I print all three
values separately. When I click on the
“Run” button again, I find that all three of those assignments have
10 as their value. Again, I clear my screen before I move on to the next example. Yet another option you have is to do multiple assignments. For instance, I type a, b, c, separated by commas equals, 1, 2, 3 also separated by commas. In this way, I have
assigned each of those values to the
corresponding letter. A equals 1, b equals 2, c equals 3. To test this out, I can print all three variables. Click “Run”, and I’ll
find that the values 1, 2, 3 correspond to the
declaration above. Another important point that
you should be aware of is variable assignments and
how you can change it. A variable is subject to change. Throughout the life
cycle of your program, you will make changes
to the value or the assignment of
the variable itself, so you need to know
how to do that. Let’s explore another example. I type a equal to 10, and I print that value. After this, I change
the value of a to five, and I print that value too. When I click the “Run” button, a prints out as 10en on
the first line and is five on the line below
because value is reassigned. Finally, you need to know
how to delete a variable. My variable, it’s value is 10, and I’ve printed it out, and then on a new line, I type the delete command, or del for short, followed by a space
and a letter a, which represents my variable. I then print the variable by
using the print function, and then I click
the “Run” button. The value is first given us 10 because the variable
still existed, but after the deletion, it shows an error saying
that a is not defined. You just covered variable
naming conventions. Now you know how to declare a variable and assign its value, and you know how to declare any different type of
variable in terms of value. You can declare
multiple variables and assign them as single value, and you can do
multiple assignments. Finally, you also learned
how to delete a variable. That brings us to the
end of this video. You can now identify variables and recognize how to
use them in Python.
Video: Basic data types
This video discusses the different data types in Python, including numeric, sequence, dictionary, Boolean, and set.
- Numeric data types:
- Integer: non-fractional numbers, such as 10 or -10
- Float: numbers that contain decimal places, such as 10.5 or 6.7
- Complex: numbers that are made up of both real and imaginary numbers, such as a = 10 + 10j
- Sequence data types:
- Strings: a sequence of characters enclosed in either single or double quotes
- Lists: a sequence of one or more different or similar types, held inside square brackets
- Tuples: similar to lists, but immutable, meaning the values inside the tuple cannot be modified
- Dictionary data types:
- Store data in a key-value object structure
- Each value can be accessed directly by its key
- Can store any data type
- Boolean data types:
- Represented as true or false
- Used to check whether a condition is true or false
- Set data types:
- Unordered and non-indexed collection of non-repeated values
When you declare a variable in Python, the data type is automatically assigned based on the value of that variable. For example, the variable a
is assigned the data type float
because it contains a decimal place.
You can use the type()
function to check the data type of a variable. For example, the following code will print the data type of the variable a
:
type(a)
Output:
float
Experimenting with different data types in your practice code is a great way to learn more about how they work.
Basic data types in Python
Python has five basic data types:
- Numeric: Integers, floats, and complex numbers
- Sequence: Strings, lists, and tuples
- Dictionary: Key-value pairs
- Boolean: True or false
- Set: Unordered collection of unique values
Numeric data types
Numeric data types are used to store numbers. There are three types of numeric data types in Python:
- Integers: Non-fractional numbers, such as 10 or -10
- Floats: Numbers that contain decimal places, such as 10.5 or 6.7
- Complex numbers: Numbers that are made up of both real and imaginary parts, such as a = 10 + 10j
Sequence data types
Sequence data types are used to store collections of data. There are three types of sequence data types in Python:
- Strings: Sequences of characters enclosed in either single or double quotes
- Lists: Sequences of any type of data, held inside square brackets
- Tuples: Similar to lists, but immutable, meaning the values inside the tuple cannot be modified
Dictionary data type
Dictionary data types are used to store key-value pairs. Keys are unique identifiers, and values can be of any type.
Boolean data type
Boolean data types are used to store true or false values.
Set data type
Set data types are used to store unordered collections of unique values.
Examples
# Numeric data types
integer = 10
float = 10.5
complex_number = 10 + 10j
# Sequence data types
string = "Hello, world!"
list = [1, 2, 3, 4, 5]
tuple = (1, 2, 3, 4, 5)
# Dictionary data type
dictionary = {"name": "Bard", "age": 1}
# Boolean data type
boolean = True
# Set data type
set = {1, 2, 3, 4, 5}
Using the type() function
You can use the type()
function to check the data type of a variable. For example, the following code will print the data type of the variable integer
:
type(integer)
Output:
int
Conclusion
Basic data types are the foundation of Python programming. By understanding the different types of data and how to use them, you can write more efficient and effective code.
Which of the following are sequence data types? Check all that apply.
List, Tuples, String
Strings, lists, and tuples are all sequence data types. Floats and integers are numeric data types.
Computer systems needs to interpret the
different data values. In programming, data can
come in different types. By the end of this video, you’ll be able to describe the different data types in Python. A data type is an attribute
associated with a piece of data that tells a
computer system how to interpret its value. Knowing what data types
to use ensures that data is collected in
the preferred format. It also ensures that the value of each
property is as expected. Python offers raw
data types to allow data to be assigned to
variables or constants. The five main types
which are classed as literals consist of numeric, sequence, dictionary,
Boolean, and set. Some of these data
types can be extended. For example, the numeric data
type can consist of types, integer, float, and
complex number. For now, let’s just
discuss data types in more detail,
starting with numeric. In programming,
you need to decide on what type will
suit your needs. For example, when
working with currency, you’re most likely going
to use the numeric type of float as it allows decimal
places to be counted. To determine a type of variable, Python also provides a
function names type, which will provide
the class type based on the variable
being passed. Python offers three different
kinds of numeric types, which are integers, floats,
and complex numbers. The integer class represents
any non-fractional number, that is whole numbers
with no decimal places. These numbers can be
positive or negative, for example, 10 or minus 10. Floats are numbers that contain decimal places and are
represented by the floats class, examples are 10.5 or 6.7. The complex class is
used to represent complex numbers
which are made up of both real and imaginary numbers, a equals 10 plus 10j. Next, let’s explore the
sequence data types. Sequence types of clusters
container types that contain one or more of the
same type in an ordered list. They can also be accessed based on the index in the sequence. Python has three
different sequence types, namely strings,
lists, and tuples. Let’s explore each
of these briefly, now starting with strings. A string is a sequence
of characters that is enclosed in either a
single or double quotes. Strings are represented by the string class
or str for short. Lists are a sequence of one or more different
or similar types. They are essentially
an array and hold any type inside square brackets. Each item can be
accessed by its index. Tuples are similar to
lists in many ways. They contain an ordered
sequence of one or more types, but the main difference is
that they are immutable. This means that
the values inside the tuple cannot be
modified or changed. Tuples are represented
by the tuple class and hold datatypes
wrapped in parentheses. The next data type
is dictionary. Dictionary store data in a
key value object structure. Each value can be accessed
directly by its key. Dictionaries can also
store any data type. For example, suppose you declare a variable named ed and
assign a dictionary to it, the dictionary contains a
grouping of key value pairs. The first pair is a: 22, where a is the key
and 22 is a value. The second pair is b: 44.4, where b is a key and
44.4 is the value. You can then output the value of 22 by accessing its
key, which is a. Next, let’s explore
Boolean data types which are simply represented
as true or false. Combined with logical operators, Booleans are used to check whether a condition
is true or false. In this example, I’m checking the underlying data type of
the values true and false. The class bool is returned, meaning it is Boolean. The last data type is set, which is an unordered and
non-indexed collection of non-repeated values. Let me demonstrate an
example of this data type. Suppose I assign a set of four items to the variable
named example set. I then check the type of the value stored
in the example set variable by passing it
to the type function. Python reports that the
underlying data type that the example set variable
holds is a set. In programming, data type
is an important concept. Variables can store data of different types and
different types of data can do different things. Let’s explore these
in further detail. Whenever you declare
a variable in Python, the datatype is
automatically assigned for you based on the
value of that variable. Let me demonstrate this
by typing a variable called a and assigning
it to a value of 10. To check the data type that
has been assigned by Python, I select Print and use
the type function. I then pass in the variable a as the parameter and
click on “Run”. From the output on the terminal, I can see a class of floats was assigned because there
was a decimal place. Here is another example. I’m using the variable b and I sign it a decimal value of 2.3. To check the data type
assigned by Python, I print out type b
and click on “Run”. From the output on the terminal, I can see a class of floats was assigned because there
was a decimal place. This is a different assignment
than the standard integer. These are the numeric data
types offered in Python. To declare a variable
as a string, I wrapped a text with
single or double quotes. Again, I run the
print statement to the function type and pass the variable c as the perimeter. When I click on “Run”, the outputs and the terminal now displays the classes int, float, and str for string. This sequence is also
applicable for other datatypes. For example, I can create
a list of numbers by using the variable d and
assigning it the numbers 1, 2, 3, 4. When I run the print
statement with a function type and pass the variable d
as the parameter, the class list displays
after I click “Run”. Each time I assign a value
to a particular variable, Python behind the
scenes is automatically assigning the correct data
type of that variable. In this video, you learned about the different data
types in Python. I encourage you to start experimenting with these data types in your practice code.
Video: Strings
In this video, you learned about strings in Python. Strings are sequences of characters enclosed in either single or double quotes. They can be declared in single line or multi-line format. Strings are considered collections of characters, which means that you can access individual characters based on an index and check the length of a string using the len function.
Strings in Python
Strings are a sequence of characters enclosed in either single or double quotes. They are one of the most basic data types in Python and can be used to store text data.
Declaring strings
Strings can be declared in single line or multi-line format. To declare a single line string, simply enclose the characters in single or double quotes. For example:
my_string = "Hello, world!"
To declare a multi-line string, use the backslash character (\
) to indicate the end of each line. For example:
my_multi_line_string = """This is a multi-line string.
It can be used to store long pieces of text.
"""
Accessing individual characters
Strings are considered collections of characters, which means that you can access individual characters based on their index. The index of the first character in a string is 0, and the index of the last character is one less than the length of the string.
To access an individual character in a string, use square brackets ([]
) to specify the index of the character you want to access. For example:
my_string = "Hello, world!"
# Access the first character in the string.
first_character = my_string[0]
# Print the first character.
print(first_character)
Output:
H
Checking the length of a string
To check the length of a string, use the len()
function. The len()
function returns the number of characters in a string.
my_string = "Hello, world!"
# Check the length of the string.
string_length = len(my_string)
# Print the string length.
print(string_length)
Output:
13
String concatenation
String concatenation is the process of joining two or more strings together. To concatenate strings, use the addition (+) operator.
my_string1 = "Hello"
my_string2 = ", world!"
# Concatenate the two strings.
concatenated_string = my_string1 + my_string2
# Print the concatenated string.
print(concatenated_string)
Output:
Hello, world!
String methods
Python provides a number of built-in methods for working with strings. Some common string methods include:
upper()
: Converts a string to uppercase.lower()
: Converts a string to lowercase.strip()
: Removes whitespace from the beginning and end of a string.replace()
: Replaces all occurrences of a substring in a string with another substring.split()
: Splits a string into a list of strings based on a delimiter.
For more information on string methods, please refer to the Python documentation.
Conclusion
Strings are a versatile data type that can be used to store and manipulate text data. By understanding the basics of strings, you can write more powerful and efficient Python code.
You have the following variables with string values:
a = “my favorite food is ”
b = “mashed potatoes”
You then print these strings together with this line:
print(a + b)
What is this an example of?
Concatenation
That’s right! Concatenation is the joining of two separate strings.
You may recall that Python can work with several
types of data. In this video,
you’ll learn how to declare and use strings in Python. You’ll also gain a
general understanding of sequences and how to access individual
items in a sequence. In Python, a string
is a sequence of characters enclosed in either
single or double-quotes. As you may know, computers
only understand binary code, which consists of
ones and zeros. This means that characters
need to be converted to a form that computers
can interpret, a process known as encoding. Python uses a type
of encoding called Unicode to communicate
with computers. Strings in Python can be
declared in several ways. For example, for a single line, you can type the variable
name followed by an equal sign and then the
character encased in quotes. If your string is too
long for one line, you can add a backslash
at the end of each line to create a
multi-line declaration. When you run print
on your variable, all those strings
will be combined and appear on one line. If needed, you can reassign
the value of a string. Say, for example,
the variable name has a string value of John, but you want to change
the value to Paul, this can be done simply by
typing name equals Paul. Now, when you run print on name, this update should be reflected. It’s important to
know that a string is just a sequence of characters, which in turn means it
is essentially an array. Each character in
the sequence can be accessed based on its index. For example, Python
strings use zero-indexing. You can access the
first character with a Number 0 in square brackets, or the Number 2 to
access the third one. If you need to check
the length of a string, python has functionality
to assist you. You can apply the len function to a variable with
a string value. This will then
return a number that represents how many
characters are in the string. Now that you’ve learned
what strings are in Python, let’s explore some code
examples of strings in action. First, let me demonstrate the two ways to
declare a string. The first method is by placing the characters inside
of single quotes. I type a equals and then
‘hello’ in the quotes. On the next line, when I type print followed by a in parentheses and then
click the “Run” button, my code returns the string
hello as the output. The second method is similar, but uses double quotes. I would enter it as b equals
hello with double-quotes. When I run the print
function again, it also returns
the string hello. Both quotation types are equally valid
declaration methods. The choice is a matter
of personal preference, but it’s best to pick one option and use it consistently
throughout your code. In addition to the
quotation types, you can declare single line
or multi-line strings. An example of a single
line string can be a equals this
is a single line. I asked to print
out the value of a. When I run it, the value is
printed out as I declared it. However, there may
be cases in which a string is very long, and you want to break it up into segments to make
it more readable. To do that, I can use the Backslash key to create
a multi-line string. To declare a multi-line string, I type b equals followed by
the string, this is a multi. Before continuing, I add a backslash at the
end of this line. On the next line, I type
the continuation of my string, line string example. Note the signs
were spaced before the word line so that it’s separated from the last word of the string on the previous line. Now, when I run print on b, the backslash has the
effect of joining both segments so that the outputs appear
as a single string. Another thing you can do with
strings is concatenation, which is the joining
of separate strings. To demonstrate this, I first
create two new variables, a equals hello, with a space at the end
and b equals there. When I run print this time,
within the parentheses, I type a plus b and get back both
strings joined together. The plus symbol is usually used as an arithmetic operator, but when applied on strings, it combines them instead. One more thing to know
about strings is that they are considered
collections of characters. What this means is that, much like an array, you can access individual
characters based on an index, and you can also check
the length of a string using the L-E-N or len function. To give you an example, I
tried to name variable, with a string value, John. Now, I want to print only the first character of the string. To do so, I run print on name followed by the
character index number inside square brackets. Strings in Python
are zero-indexed, meaning that the sequence
count begins from zero, so zero is a number that
I place in the brackets. When I click on “Run” I
get back the letter J. If I change the number to
three and run it again, I get back the letter n, the fourth character
in the string John. Next, let’s check
how many characters are in this string by
using the len function. I start a print
function and in it, I type len followed by name
inside of parentheses. When I run it, it returns
four, as the length. In this video, you’ve learned
about strings in Python. Specifically, you’d now know how to declare and use them and understand that they
are sequences of characters. See you
in the next video.
Reading: Basic Data type and Function Cheatsheet
Reading
Here’s a quick reference for data types in Python.
Data types
Data type | Meaning | Example |
---|---|---|
string | Text | ‘Hello’, ‘Testing 123’ |
integer | Numbers | -5, 4, 3, 2, 0 |
float | Decimals | 2.4, 5.2, 1000.00 |
Flow Control
Comparison operators
Operator | Meaning | Example |
---|---|---|
== | Equals | a == b |
!= | Not Equal | a != b |
< | Less than | a < b |
> | Greater than | a > b |
<= | Less than or Equal to | a <= b |
>= | Greater than or Equal to | a >= b |
Comments
Single-line comments
Placing a # symbol in front of the text you want to be a comment causes Python to ignore everything from that point until the end of the current line.
# Single Line comment
Multi-line comments
Python does not really have a method for multi line comments, so a # symbol can be used on every line.
# This is a multiline comment
# which can be used for long comments
Inline/code comments
The # symbol will cause Python to ignore everything from that point until the end of the current line, so inline comments can be created in this way.
x = 1 # assigns value of 1 to x
Built-in Functions
print()
This function looks for the default output device, your terminal, and displays the value passed to it.
print("Hello")
input()
This function looks for the default input device, your keyboard, and captures the value. This value can then be assigned or used.
print("Where do you live?")
location = input()
print("So you live in " + location)
len()
This function returns the length or the count of the elements contained within the structure it is applied on. This may be a string, array, list, tuple, dictionary or any sequence.
len("Hello")
5
str()
This function can be used to convert the provided value into a String
str(55)
'55'
int()
This function can be used to convert the provided value into an int
int('75')
75
float()
This function can be used to convert the provided value into a float
some_int = 10
float(some_int)
10.0
Creating Functions
Functions in Python require a keyword to define them : def followed by an identifier (a name) this forms the function signature. The body of the function contains the code to run when the function is called.
def say_hello():
return "Hello there!"
# With parameters
def say_hello(you):
return "Hello " + you
Video: Type casting
Typecasting in Python is the process of converting one data type to another. There are two types of typecasting: implicit and explicit.
Implicit typecasting is performed automatically by Python’s compiler to prevent data loss. For example, if you try to add an integer to a float, Python will automatically convert the integer to a float.
Explicit typecasting is performed by the programmer using Python functions. For example, to convert a string to an integer, you would use the int()
function.
Here are some examples of typecasting in Python:
Python
# Implicit typecasting
str_value = "10"
int_value = 5
# Python will automatically convert the string to an integer
sum = str_value + int_value
# Explicit typecasting
str_value = "10.5"
float_value = float(str_value)
# Python will convert the string to a float
sum = float_value + int_value
# Output: 15.5
Typecasting can be useful for a variety of tasks, such as:
- Converting user input to a different data type
- Performing calculations with different data types
- Storing data in a database
- Sending data over a network
It is important to note that typecasting can sometimes lead to data loss. For example, if you try to convert a string that contains non-numeric characters to an integer, Python will throw an error.
To avoid data loss, it is important to use typecasting carefully and to always check the data type of a variable before using it.
Python Type Casting Tutorial
Typecasting in Python is the process of converting one data type to another. There are two types of typecasting: implicit and explicit.
Implicit typecasting is performed automatically by Python’s compiler to prevent data loss. For example, if you try to add an integer to a float, Python will automatically convert the integer to a float.
Explicit typecasting is performed by the programmer using Python functions. For example, to convert a string to an integer, you would use the int()
function.
Here are some examples of typecasting in Python:
# Implicit typecasting
str_value = "10"
int_value = 5
# Python will automatically convert the string to an integer
sum = str_value + int_value
# Explicit typecasting
str_value = "10.5"
float_value = float(str_value)
# Python will convert the string to a float
sum = float_value + int_value
# Output: 15.5
When to use typecasting
Typecasting can be useful for a variety of tasks, such as:
- Converting user input to a different data type
- Performing calculations with different data types
- Storing data in a database
- Sending data over a network
How to use typecasting
To typecast a variable in Python, you can use the following syntax:
new_variable_type = old_variable_type(variable)
For example, to convert a string to an integer, you would use the following code:
int_value = int(str_value)
To convert an integer to a string, you would use the following code:
str_value = str(int_value)
There are also Python functions for converting other data types, such as floats, lists, and dictionaries. You can find a list of all of the Python typecasting functions in the Python documentation.
Important things to keep in mind when using typecasting
- Typecasting can sometimes lead to data loss. For example, if you try to convert a string that contains non-numeric characters to an integer, Python will throw an error.
- It is important to use typecasting carefully and to always check the data type of a variable before using it.
- You can use the
type()
function to check the data type of a variable.
Example
The following code shows how to use typecasting to convert user input to a different data type:
user_input = input("Enter a number: ")
# Convert the user input to an integer
number = int(user_input)
# Print the number
print(number)
If the user enters the string “10”, the code will print the following output:
10
Conclusion
Typecasting is a powerful tool that can be used to convert data between different types. However, it is important to use typecasting carefully and to always check the data type of a variable before using it.
A company wants to determine the general age of its customers. You help them by writing a program that uses a customer's ID number (7512171283423) to determine his or her age. But the data set that you are provided with has the ID numbers saved as strings. What typecasting function can you use to solve the problem?
int('7512171283423')
You are correct! You will use the integer function as it will output whole numbers with no decimal places.
Python uses different datatypes of processing, use
information effectively. Sometimes you need to
change the data type of a variable after you’ve
collected values for it. Let’s say for example, a user submits a
form on our website. One of the fields
was an integer, but the data was
passed as a string. This is a problem because the only way to perform
calculations with the numbers saved
as a string is to convert it to an
integer datatype. To do this, you can use
typecasting in Python. In this video, you’ll learn about two different type
casting methods in Python. You will also learn to apply typecasting using the
provided Python functions. What is typecasting?
Typecasting is the process of converting
one data type to another. Python has two
different types of conversions; implicit
and explicit. Let’s explore each now in a little more detail,
starting with implicit. Implicit data type
conversion is performed automatically by Python’s
compiler to prevent data loss. It will convert, for example, an int to a float if it picks up that the inserted
value is a decimal. It’s important to note that
Python will only be able to convert values if the data
types are compatible. int and float are compatible
but Strings and int are not. If data types are
not compatible, Python will throw a type error. Alternatively,
developers can perform typecasting with the explicit
data type conversion. You do this by using the
provided Python functions. There are many functions
but some of the most common are string,
integer and float. Let me take you through some of these functions and
how to use them. First is the string
cost function. This is used to convert
any datatype into a string datatype. To
use this function. You type str followed by the value that you want to
convert between parentheses. Next is the int type
casting function. To use this type int followed by the value that you want to
convert between parentheses. The float function is another common type
of costing function. Once again, you type
the word float and add the value that you
want to convert in-between parentheses. Python has many more
typecasting functions and they also have a
similar structure. They are all ord, which returns an integer representing the underlying
unicode character. The hex function, which converts a given integer to a
hexadecimal string. An oct which takes
an integer and returns a string representing
an oct to a number. There are also tuple, set, list, and dict, which you will learn more
about later in the lesson. In this video, you learned
about typecasting in Python. It’s important to remember that datatypes are not unchangeable. You can convert datatypes using the provided Python
functions if you need to.
Video: User input, console output
- Inputs: The input function allows you to get data from a source of inputs, such as the user’s keyboard. To use the input function, you simply call it with a prompt, and the user will be prompted to enter data. The input function will then return the user’s input as a string.
- Outputs: The print function allows you to print data to the console. To use the print function, you simply call it with one or more arguments. The print function will then print the arguments to the console, separated by commas. You can also use the print function to format your output using format strings.
Here are some examples of how to use the input and print functions in Python:
# Get the user's name as input.
name = input("What is your name? ")
# Print a greeting to the user.
print(f"Hello, {name}!")
# Get two numbers from the user as input.
num1 = input("Enter the first number: ")
num2 = input("Enter the second number: ")
# Convert the input strings to integers.
num1_int = int(num1)
num2_int = int(num2)
# Add the two numbers together and print the result.
print(f"The sum of {num1} and {num2} is {num1_int + num2_int}.")
You can also use the input and print functions to create more complex programs, such as calculators and games.
User input, console output in Python
Python has two built-in functions for user input and console output: input()
and print()
.
User input
The input()
function prompts the user for input and returns the user’s input as a string.
# Prompt the user for their name.
name = input("What is your name? ")
# Print a greeting to the user.
print(f"Hello, {name}!")
You can also use the input()
function to get other types of input, such as numbers or dates. To do this, you need to convert the input string to the desired type.
# Prompt the user for a number.
number = input("Enter a number: ")
# Convert the input string to an integer.
number_int = int(number)
# Print the number.
print(number_int)
Console output
The print()
function prints the given arguments to the console. You can pass any number of arguments to the print()
function, and they will be printed to the console, separated by spaces.
# Print a string to the console.
print("Hello, world!")
# Print two numbers to the console.
print(1, 2)
# Print a list of numbers to the console.
print([1, 2, 3])
You can also use the print()
function to format your output using format strings. Format strings allow you to control how your output is displayed, such as the number of digits after the decimal point or the alignment of the output.
# Print a number with two digits after the decimal point.
print("{:.2f}".format(3.14159))
# Print a string centered on the console.
print("{:^20s}".format("Hello, world!"))
Putting it together
Here is a simple example of a Python program that uses user input and console output:
# Prompt the user for their name.
name = input("What is your name? ")
# Print a greeting to the user.
print(f"Hello, {name}!")
# Prompt the user for two numbers.
num1 = input("Enter the first number: ")
num2 = input("Enter the second number: ")
# Convert the input strings to integers.
num1_int = int(num1)
num2_int = int(num2)
# Add the two numbers together and print the result.
print(f"The sum of {num1} and {num2} is {num1_int + num2_int}.")
This program will prompt the user for their name and two numbers. It will then convert the input strings to integers, add the two numbers together, and print the result to the console.
Conclusion
The input()
and print()
functions are powerful tools that can be used to create a wide variety of Python programs. By learning how to use these functions, you can start to build interactive and powerful applications.
Python's print function can output:
Values of all data types.
You are correct!. Python’s print function can output values of all data types.
Like other programming
languages, Python focuses on
taking inputs from users or other services
and providing output. Python has many
helper functions that make it easy to perform
both of these actions. You may recall that you use the print function to output
variables and other values. In this video, you
will learn more about the print function
and how to use another new function
called inputs. The input function
is designed to get data from a source of inputs, and it can be used
in different ways. For example, one of it’s
most basic uses is when you use the input function to get data that the user
types in the keyboard. This input can then be
printed to the screen. In many cases, you want to get input directly from a user. For example, when you ask
for user’s email address, let’s say you want to use the input function to
prompt the user to enter their email address
and then save that input to a
variable called e-mail. If you run this code, the user will be presented with a prompt to enter their email. The email variable will then
contain the e-mail address. Let’s switch back to
the print function, which is used for
outputs in Python. It can be used to print
all different types of data and it allows for
more complex formatting. The print function
itself accepts any number of arguments. For example, comma separated to print numbers in sequence. Arithmetic to print the
output of an equation, and string concatenation to join or concatenate
two strings together. Python’s print function
also has reserved keywords that can be parsed
as additional arguments. These include objects,
that is values that are printed onscreen, sep, which defines how
the objects being printed or separated and end, which defines what gets
printed at the end. There’s also a file which specifies where values
get printed to, and by default it is STD out. Lastly, flush, a Boolean expressions
to flush the buffer, which essentially just
moves the data from a temporary storage to the computers permanent
memory storage. For example, suppose you can pass three parameters
to the print function, the word hello,
which is a string, the word you, which is
another string, and sep, which is a built-in
parameter whose value is set to a string containing
a comma and a space. This will be used as a separator between the hello
and you strings, and the output is hello you. Often while programming,
you need to know the value of a variable and outputs
it onto the screen. Python allows for
direct formatting inside the print statement. You can also control
the order by specifying the numbers
inside the curly brackets. For example, if you print
the same statements twice, but with a number switched, the outputs will differ. Let’s move on to
a more practical application of what you’ve just learned using
some code examples of inputs and outputs. I’ll demonstrate how to use
inputs and outputs in Python. I’ll begin by demonstrating
the input function. I start by typing input, opening parenthesis and
closing parenthesis. I then click on the Run command. You’ll notice that it
runs the input function. I’m provided with a console where I can actually
type an input. I type Hello there
and I press Enter. Nothing happens because I’m
not actually collecting data. I’m just triggering
the input function. By default, it will
open up access to the command line or the console and allow me to input data. I can also add a prompt
to the input function. For example, I can ask a
question to the users such as, Please enter a numbe,. so I type, please
enter a number in between the parentheses
after the word input. First I clear the console and then I’ll click
on Run, again, you’ll notice that the outputs now asks me to enter a number. I type five and press Enter. Again nothing shows up from
an output perspective. This is because I
haven’t actually done anything with
the input value. I’m just demonstrating how
the input function works. If I want to get the
value of the input, I need to assign a variable. I type in num equals input. Please enter a number. I claim my console screen again and I click
on the Run button. It asks me for a number in the console and I entered
the number six this time. Now the num, or number value
will contain the number six. But in order to see that, I have to output that
variable to the screen. I can do this by using another function called
the print function. In this case, I print the
number after the input itself by typing print
opening parenthesis, the abbreviation num, and
a closing parenthesis. I clear my screen again
and click on Run. This time I type
the number seven. When asked to enter a number, I press Enter and you’ll notice that the
output prints seven. Now I want to show
you that you can collect more than one inputs as part of the input because inputs work in a
sequential manner. I call this variable num one, and I enter another variable called num two on the next line. The input for this variable is please enter a second number. I just changed the first
variables inputs to please enter a number so that the instructions
are clearer. I print out the value
of num one, num two. The print statement accepts both variables because they
are separated by a comma, and it’ll print out
each one in that order. Again, I clear my
console and I click Run. I type four as the first number. I press Enter and type
five is the second number, followed by the enter key again, you’ll notice 4 and
5 are printed out. You can also do arithmetic
within the print statement. In other words, you
can do addition, subtraction, standard
multiplication, and division. Instead of using commas
in the print statement, I type num one plus num two. I cleared the screen once
more and I click Run. I enter the numbers
5 and4 again, and I get back 54. Now, this isn’t exactly
what I intended to do, and the reason is because
both variables are strings. This goes back to what you’ve learned previously
with datatypes. If I want to do the
arithmetic calculation, I’ll need to convert each
variable into an integer first. I can use the integer
function on num one, num two. I click on the Run
button once more and I enter the same two
numbers, 5 and 4. But now what I get back is nine. If I want to see what
type the input is, I can check the data type
by using the type function. To do this, I type print
opening parenthesis, the word type
opening parenthesis, num one, followed by two
closing parentheses. Let me just clear the screen. I click on Run and enter the numbers 5 and 4
again in the console. It says that the class is
string and not integer, which is the type I actually
want to do arithmetic. Just be mindful
when you’re using inputs that you
will get a string. You’ll most likely need to
use the explicit data type casting to convert it to
the datatype that you need. The print statements can also
be used for concatenation. Instead of num one, I changed it to STR
one or string 1 and I do the same with num two
by changing it to STR two. Then I immense the
input to read, please enter your first
name for string one, and please enter your
second name for string two. After that, I print out hello. Then use concatenation
so that the user can be greeted by their
first, and second name. Now I want to run this program, I’ll just clear the terminal quickly and then I click on run. In the console, I type Tom for the first name and Jones
for the second name. The result is the outputs
of hello Tom Jones. Concatenation can be used with
a print statement as well. Finally, you can also change
how you assign variables. You don’t have to
use concatenation, you can just use
string replacement. I’m going to use
a function within Python called formats for this. Based on the order
of the brackets, you can pass in the variables that you want it to
be replaced with. In this case, string 1 and 2. Once more, I click run and I enter the username of Tom Jones. Hello, Tom Jones gets printed. In this video, you’ve
expanded your knowledge by learning about the inputs and
output function in Python.
Reading: Type casting, a deeper look
Reading
There are some scenarios in which a given value’s data type needs to be changed to some other data type.
This process is known as type casting.
Another, more informal way to refer to it is “data type conversion”.
The simplest example of converting data could be the following comparison:
print(10 == 10)
In the above piece of code, I’m asking Python if the number 10 is equal to the number 10, and I’ll get the boolean value of True printed, confirming that indeed, they are the same.
What if I do this?
print(10 == 10.00)
Again, the boolean value of True is output on the screen.
Now, you might complain that, well, 10 is not technically equal to 10.0 – because, one might argue, the first number is an integer, and the second number is a float. You would be right – although these are the same numbers, they are not the same data types.
However, Python here perfoms what’s known as “implicit type conversion”.
To understand how this works, I’ll slightly tweak the previous example. Instead of asking Python to compare the two numbers and return if they are the same or not, I’ll ask Python to print the result of adding these two numbers together.
print(10 + 10.0)
The printed result is 20.0.
This output allows me to conclude that when Python runs operations involving integers and floats, it implicitly converts the integers type to a float, and then completes the operation.
To really drive this point home, I can extend my previous example, using the type() function:
print(type(10 + 10.0))
The output is <class ‘float’>, so this confirms my conclusion.
Let me know show you a small program in Python, working with numbers:
user_num_1 = input('First number is: ')
user_num_2 = input('Second number is: ')
user_sum = user_num_1 + user_num_2
print(user_sum)
When I run this program, I could, for example, provide the first number’s value as 5, and the second number’s value also as 5, expecting that the printed user_sum value will be 10.
However, when I do exactly that, the number 55 gets printed instead.
Why was this not working?
Well, the answer is pretty simple: everything that a user types in, is converted, by Python, to the string data type.
This means that, although I typed numbers into these two inputs, what was saved in user_num_1 and user_num_2 were actually strings.
Effectively, it’s exactly the same as if I just did this:
user_num_1 = "5"
user_num_2 = "5"
user_sum = user_num_1 + user_num_2
print(user_sum)
This time, the output of printing user_sum is still “55”, but this comes at no surprise.
In order to have my Python code work as I intended, I need to perform explicit type conversion.
In other words, I have to convert the value of “5” to the value of 5.
Here’s my updated code:
user_num_1 = input('First number is: ')
user_num_2 = input('Second number is: ')
user_sum = float(user_num_1) + float(user_num_2)
print(user_sum)
What I’m doing here is, I’m making sure that my program can handle even accepting floats as inputs, and still work correctly.
In other words, I’m making sure that if a user provided, say, the float value of 5.5 as both the first and second numbers when running the above code, the output would not throw an error. Instead, it will be the expected 11.0.
What if I decide to output some words to the user, telling them what happened?
Here’s an attempt at doing that:
num_1 = input('First number is: ')
num_2 = input('Second number is: ')
user_sum = float(num_1) + float(num_2)
print("The sum of: " + num_1 + " and " + num_2 + " is " + user_sum)
If I run the above code, it will throw the following error:
Traceback (most recent call last): File “<string>”, line 4, in <module> TypeError: can only concatenate str (not “float”) to str
What this means is, I cannot concatenate a string and a float like that. In other words, although Python’s implicit type conversion works when I use the + operator on strings and integers, it does not work on strings and floats.
The solution to this is to perform explicit type conversion, as follows.
n1 = input('First number is: ')
n2 = input('Second number is: ')
user_sum = float(n1) + float(n2)
print("The sum of " + str(n1) + " and " + str(n2) + " is " + str(user_sum))
This time, the output is: The sum of 5.5 and 5.5 is 11.0.
In Python, it’s easy to perform explicit conversions, and sometimes they are very useful. You’ll learn more about how this works as you get more experience in Python.
Programming Assignment: Type casting input
Reading
Lab Instructions: Type Casting Input
In this lab you will be presented with three exercises to demonstrate how explicit type casting can be.
used to solve data being inputted from an end user. Each exercise will ask you to solve a particular problem relating to types.
Tips: Before you Begin
To view your code and instructions side-by-side, select the following in your VSCode toolbar:
- View -> Editor Layout -> Two Columns
- To view this file in Preview mode, right click on this README.md file and
Open Preview
- Select your code file in the code tree, which will open it up in a new VSCode tab.
- Drag your assessment code files over to the second column.
- Great work! You can now see instructions and code at the same time.
- Questions about using VSCode? Please see our support resources here.
To run your Python code
- Select your Python file in the Visual Studio Code file tree
- You can right click the file and select “Run Python File in Terminal” or run the file using the smaller
play button in the upper right-hand corner of VSCode.
(Select “Run Python File in Terminal” in the provided button dropdown) - Alternatively, you can follow lab instructions which use python3 commands to run your code in terminal.
There are two exercises and objectives of this activity:
- Exercise 1: Use explicit casting to apply the correct cast type
- Exercise 2: Fix the script so it correctly outputs the bill total
Exercise 1:
In this exercise, you’ll use explicit casting to apply the correct cast type.
Instructions
- Open the script exercise1.py present inside the project folder
- To run the script, open terminal and execute the following command:
python3 exercise1.py
- Step 3: Fix the script so the variables have the correct type.
Exercise 2:
Your goal of this exercise is to fix the script so that each variable has the correct type.
Instructions
- Open the script exercise2.py present inside the project folder
- To run the script, open terminal and execute the following command. You will be prompted to enter some values.
python3 exercise2.py
- Fix the script so it outputs the correct bill total based on the data being entered.
Final Step: Let’s submit your code!
Nice work! To complete this assessment:
- Save your file through File -> Save
- Select “Submit Assignment” in your Lab toolbar.
Your code will be autograded and return feedback shortly on the “Grades” tab.
You can also see your score in your Programming Assignment “My Submission” tab.
exercise1.py
# Using explicit type conversion, change the following
# inputs so the types match with the following below
#
# name = type string
# age = type int
# height = type float
# loyalty = type boolean
# Modify the line below
name = input(str('What is your name? '))
print(f"Type of name variable is: {type(name)}. It should be <class 'str'>")
# Modify the line below
age = int(input('What is your age? '))
print(f"Type of age variable is: {type(age)}. It should be <class 'int'>")
# Modify the line below
height = float(input('What is your height in meters? '))
print(f"Type of height variable is: {type(height)}. It should be <class 'float'>")
# Modify the line below
loyalty = bool(input('Are you part of our loyalty program? '))
print(f"Type of loyalty variable is: {type(loyalty)}. It should be <class 'bool'>")
exercise2.py
# The below script will ask for 3 inputs. Each input will be based
# on the price of the items - the price is determined by you. The output
# should print the total of the 3 inputs rounded to 2 decimal places e.g
#
# 1 coffee @ $ 2.00
# 1 sandwich @ $ 4.99
# 1 cake @ $ 2.75
#
# Your total bill is $ 9.74
# Modify the line below
coffee = float(input('1 coffee @: $ '))
# Modify the line below
sandwich = float(input('1 sandwich @: $ '))
# Modify the line below
cake = float(input('1 cake @: $ '))
bill_total = coffee + sandwich + cake
print('Your total bill is $', bill_total)
Practice Quiz: Knowledge check – Welcome to Python Programming
Is a string in Python a sequence?
Yes
Correct! A string in Python is a sequence of characters.
In Python, what symbol is used for comments in code?
#
Correct! The hash symbol is used for adding comments in code.
What type will be assigned to the following variable: x = 4?
int – Integer
Correct! The variable will be assigned the type Integer.
Python allows for both implicit and explicit data type conversions?
True
Correct! Python allows for both implicit and explicit data types.
A variable called name is assigned the value of “Testing”. What will the output of the following equal – print(len(name));
7
Correct! The output will be 7. The len function will get the length of the string Testing which is equal to 7 characters.
Reading: Additional resources
Reading
Python allows you to do quite a lot with very little code. Compared to other languages such as Java or C#, Python has a much easier learning curve. It lends itself well to the “write less, do more philosophy”. Python developers are also in high demand and learning how to program in Python makes for a good career choice.
You can access the links below to learn more about programming in Python.
Check out the Python website to find out more about built-in functions: Python
Check out W3 Schools to learn more about coding and web development: W3Schools
Check out HackerRank to practice your new acquired Python skills: HackerRank
Control flow and conditionals
Video: Math and logical operators
Math operators
- Addition (+)
- Subtraction (-)
- Division (/)
- Multiplication (*)
Logical operators
- And (and)
- Or (or)
- Not (not)
Examples:
# Math operators
print(2 + 2) # 4
print(3 - 2) # 1
print(35 / 5) # 7.0
print(25 * 5) # 125
# Logical operators
a = True
b = True
# And operator
if a and b:
print("All true")
# Or operator
if a or b:
print("All true")
# Not operator
if not a or b:
print("All true")
Output:
4
1
7.0
125
All true
All true
All true
Math and logical operators in Python
Math operators
Math operators in Python are used to perform basic arithmetic operations, such as addition, subtraction, multiplication, and division. They can be used on integers, floats, and complex numbers.
The following table shows the different math operators in Python:
Operator | Description |
---|---|
+ | Addition |
- | Subtraction |
* | Multiplication |
/ | Division |
// | Floor division |
% | Modulus (remainder) |
** | Exponentiation |
Here are some examples of how to use math operators in Python:
# Addition
print(2 + 2) # 4
# Subtraction
print(3 - 2) # 1
# Multiplication
print(35 * 5) # 175
# Division
print(35 / 5) # 7.0
# Floor division
print(35 // 5) # 7
# Modulus
print(35 % 5) # 0
# Exponentiation
print(2 ** 3) # 8
Logical operators
Logical operators in Python are used to combine two or more Boolean expressions to create a single Boolean expression. They are typically used in conditional statements and loops.
The following table shows the different logical operators in Python:
Operator | Description |
---|---|
and | Returns True if both operands are True, False otherwise. |
or | Returns True if either operand is True, False otherwise. |
not | Negates the operand. |
Here are some examples of how to use logical operators in Python:
# And operator
a = True
b = False
if a and b:
print("Both are True")
else:
print("At least one is False")
# Or operator
if a or b:
print("At least one is True")
else:
print("Both are False")
# Not operator
if not a:
print("a is False")
else:
print("a is True")
Output:
At least one is False
At least one is True
a is True
Combining math and logical operators
Math and logical operators can be combined to create more complex expressions. For example, the following expression checks if a number is even:
number = 10
if number % 2 == 0:
print("The number is even")
else:
print("The number is odd")
Output:
The number is even
The expression number % 2 == 0
uses the modulus operator to calculate the remainder of dividing the number by 2. If the remainder is 0, then the number is even. Otherwise, the number is odd.
Conclusion
Math and logical operators are essential tools for Python programmers. By understanding how to use them, you can write more concise and efficient code.
Which of the following are examples of logical operators? Check all that apply.
not, or, and
That’s correct, And, OR and NOT are all logical operators.
An operator is a
symbol that tells Python to perform a
certain operation. You can think of them like
road signs in real life. For example, suppose
you’re driving on a dangerous road and you spot an alert sign
to reduce speed, then you encounter a stop sign, and finally, assign
instructing you to turn right. You may not have realized that you were on a dangerous road. These symbols help
keep you safe by instructing you to perform
a specific operation. Similarly, when Python comes across an operator that
you place in your code, it will also perform
that specific operation. These operations can be mathematical, logical,
and comparison. In this video, you
will learn about Math and logical
operators in Python. Most of the time, operators
work on two values. Math operators are used for simple and complex calculations. It’s essentially all
the same options as the calculator would have. Let me explain
this with examples of Math and logical operators. The first operator
I want you to know about is the addition
or plus operator. The plus sign is
a symbol that you must use when adding
numbers together. For example, 2 plus 3. To subtract numbers
from each other, you use the subtraction
or minus operator. Use the minus sign
to subtract numbers. An example of this is 3 minus 2. The division operator is next, and the symbol you use for
it is a forward slash. Division is an
operation in which one number is
divided by another. For example, 35 divided by 5. The last operator
you need to know about is the
multiplication operator. The symbol we use for that
is the star or asterisk key. Use this to multiply
numbers with each other. For example, 7 multiplied by 4. Now let’s explore
logical operators. Logical operators are
used in Python on conditional statements
to determine a true or false outcome. Let’s explore some of these now. The 1st logical
operator is named and. This operator checks for
all conditions to be true. For example, a is greater
than 5 and a is less than 10. The 2nd logical
operator is named or. This operator checks for at least one of the
conditions to be true. For example, a is
greater than 5, or b is greater than 10. The final operator is named not. This operator returns
a false value if the result is true. For example, a is
not greater than 5. Operators are usually combined with conditional statements to control the flow of a program that meets specific criteria. For example, let’s say
a restaurant gives discounts based on the
following two conditions. Is the customer part of
the loyalty program, and did they spend over $100? To determine this, you can write code using logical operators to check if a customer is in the loyalty program and
if they spent over $100. You’ll learn more
about conditional statements in a later lesson. Now, let me
demonstrate how to use Python Math logical operators. Math operators
basically give you the same functionality as what you have on a
standard calculator, so you can perform
operations like addition, subtraction,
division, multiplication. I start with a simple
addition example. I’m using the print statements so the output displays
on my console. I type Print and in the
parentheses I add 2 plus 2. The value I expect back is 4. When I run this statement, the value of 4 displays
in the terminal. For subtraction, I change the
plus sign to a minus sign. I click on the Run button and
the value displayed is 0. If I subtract 2 minus 2, the answer is 0. For division, I changed the minus sign to
a forward slash. I type 35 forward slash
5 in the parentheses, I click the Run button and the result is the value of 7.0. Just to note on this, the value returned is a float
instead of an integer. Now let’s cover multiplication. I changed the forward slash to a star sign that
represents multiplication. I type 25 asterisk 5. I click on the Run button and
get back the value of 175. That was a short introduction
to the math operators. Next, you’ll explore
logical operators. Logical operators are used to control the flow of
your application. The logical operators are; and, or, and not. Let’s cover the different
combinations of each. In this example, I
declare two variables, a equals true and b
also equals true. From these variables, I use an if statement. I type if a and b colon,
and on the next line, I type print, and in
parentheses and double-quotes, I type, all true. You’ll learn about the
if statement shortly. But for now, just know
that this print statement will only be executed if
both a and b are true. The print statement of all true is displayed
in the terminal. If I change the value of b to false and I run the
statement again, nothing gets printed out. The reason for it is that the and statement as a condition is both a and b to be true so that it will
print out the statement. Now let’s cover the OR operator. I’m changing and to or, and I click on the Run button. The all true value has
been printed out again. The reason for it is that
with the OR operator, if either a or b is true, the if statement is true. If I set the values
of both variables to false and click on
the Run button, nothing gets printed out. This is because a is
false and b is false so the condition in the if
statement has not been met. In this last example, I’m going to demonstrate
the NOT operator. I’ll keep the OR operator. Before or, I type if
not a in parentheses, then or cannot be
in parentheses, followed by a colon. I click on the Run button and the value returned is all true. What that’s doing, is it’s looking for a
negation against a. So not a, is not
false, which is true. The negation of B, which results in
true B or condition, checks to see if either is true. Now I change the a
and the b to be true. I click on Run and
nothing gets printed out. The reason for that is that it’s checking again for if not a, essentially, if a is not true. In this case, a is true
and its negation is false, so it’s not going to
meet that condition. Or not b also results
in false and does not meet that condition
as well because both are the negation of true. This is still not going to print out any value because again, none of the conditions
are being met. That’s a brief
introduction to using both Math and Logical
Operators in Python. Congratulations. In this video, you learned about Math
and logical operators. Great job. If you’d like to learn more about Math
operators in Python, there’s an additional reading
at the end of this lesson.
Video: Control flow: If / else, else if
Control flow in programming refers to the order in which the instructions in a program are executed. Conditional statements are used to control flow by making decisions based on certain conditions.
There are three types of conditional statements in Python:
- if: The if statement executes a block of code if a condition is true.
- else: The else statement executes a block of code if a condition is false.
- elif: The elif statement executes a block of code if a condition is true, but only if all previous conditions were false.
Example of a conditional statement in Python:
bill_total = 114
if bill_total > 100:
discount = 10
bill_total -= discount
print("Total bill is", bill_total)
else:
print("Total bill is", bill_total)
Output:
Total bill is 104
Example of a conditional statement with elif in Python:
bill_total = 210
if bill_total > 100 and bill_total < 200:
discount = 10
bill_total -= discount
print("Total bill is", bill_total)
elif bill_total > 200:
discount = 20
bill_total -= discount
print("Total bill is", bill_total)
else:
print("Total bill is", bill_total)
Output:
Total bill is 190
Conditional statements are an essential part of programming and can be used to control the flow of your program in many different ways.
Control flow: If / else, else if in Python
Introduction
Control flow in programming refers to the order in which instructions are executed. It allows us to make decisions and change the flow of our program based on certain conditions.
If statement
The if statement is the most basic control flow statement in Python. It allows us to execute a block of code if a condition is true.
Syntax:
if condition:
# code to be executed if condition is true
Example:
age = 18
if age >= 18:
print("You are an adult.")
else:
print("You are not an adult.")
Output:
You are an adult.
Else statement
The else statement is used to execute a block of code if the condition in the if statement is false.
Syntax:
if condition:
# code to be executed if condition is true
else:
# code to be executed if condition is false
Example:
age = 15
if age >= 18:
print("You are an adult.")
else:
print("You are not an adult.")
Output:
You are not an adult.
Elif statement
The elif statement is used to check multiple conditions. It is similar to the if statement, but it allows us to check multiple conditions sequentially.
Syntax:
if condition1:
# code to be executed if condition1 is true
elif condition2:
# code to be executed if condition1 is false and condition2 is true
elif condition3:
# code to be executed if condition1 and condition2 are false and condition3 is true
...
else:
# code to be executed if all conditions are false
Example:
age = 15
if age >= 18:
print("You are an adult.")
elif age >= 13:
print("You are a teenager.")
else:
print("You are a child.")
Output:
You are a teenager.
Nested conditional statements
We can also nest conditional statements to check multiple conditions in a more complex way.
Example:
Python
age = 15
is_male = True
if age >= 18:
if is_male:
print("You are an adult male.")
else:
print("You are an adult female.")
else:
if is_male:
print("You are a teenage boy.")
else:
print("You are a teenage girl.")
Output:
You are a teenage boy.
Conclusion
Conditional statements are a powerful tool for controlling the flow of our programs. By using conditional statements, we can make our programs more dynamic and responsive to user input.
Here are some additional tips for using conditional statements in Python:
- Use descriptive variable names and comments to make your code more readable and maintainable.
- Use indentation to make your code more visually appealing and easier to read.
- Test your code thoroughly to make sure that it works as expected for all possible conditions.
Which of the following are examples of conditional flow controls? Check all that apply.
elif (else if), else, if
Yes! The If, else and elif (else if) statements are conditional flow controls.
In programming, it’s important
to understand how to control the order in which
your code is executed. For example, suppose you’re
invited to an event, you have to consider
whether you need to dress formally or informally. Another example
of a control flow is to consider a light switch. The flow is represented
by the electrical current and the control
is the switch itself, with the two states
of on and off. The order in which you
make decisions matters, and the same applies to
writing effective programs. In this video, you
will learn how to use conditional statements to control flow in Python programs. What is control flow? Control flow refers
to the order in which the instructions in a
program are executed. All programs have decisions
that need to be made. As a result of this, the program will take different
actions or directions. In Python, there are two
types of control flows. First, you can use conditional
statements such as if, else, and elif or else if. Second, you can use loops such as the for loop and
the while loop. Let’s explore these a
little further now. The if keyword states that if the condition proves to be true, a function is performed. The else keyword
catches anything which isn’t caught by the
preceding conditions. The elif or else if
keyword is Python’s way of saying if the previous
conditions were not true, then try this condition. The for loop checks for
specific conditions and then repeatedly executes a block of code as long as those
conditions are met. The while loop repeats
a specific block of code an unknown number of times
until a condition is met. Let’s explore conditional
statements in more detail with some practical
examples using the if, else, and elif. I’ll now write some code for
a restaurant that wants to apply different discounts based on the amount its
customer spend. To start off, I define a variable for the
customer’s bill. I’ll call it bill_total and
assign a value of 114 to it. Now, I apply condition
with an if statement. If bill_total is
greater than 100, print the statement bill
is greater than 100. Next, to apply a
discount to bill_total, I need to create a
second variable. I’ll do this above the
if statement in my code, call it discount1 and
assign a value of 10 to it. The condition also
has to change. Inside the if statement, I add bill_total equals
bill_total minus discount1. At the very end of
the code snippet, outside the if statement, I’m going to print out what the value of the total bill is. To do this, I type a
print statement that says total bill and
then a plus sign. To add the value of
bill_total here, I need to convert the
integer to a string. I use the str typecasting
function to do this. Let’s click on “Run”, great. In the terminal, two
strings are printed, bill is greater than 100
and the total bill is 104. But what happens if the
bill is less than 100? I change the value of bill_total
to 95 and press “Run”. Notice that this time because the if
condition is not met, it only prints the
statement total bill is 95. But I’d like to print
a statement that says the bill is less than 100. To do this, I add an else statement below
the if statement. I type else: and in
the next line I print the statement bill is less
than 100. Let’s run the code. The output in the
terminal now says bill is less than 100 and
total bill is 95. Up to this point, you’ve
learned how to use the if and else
statements to control the order in which values
are assigned and printed. You’re now ready to take
program flow one step further. Say this restaurant wants to add another discount
for bills over 200. How would you do
that? Once again, I first need to create a new variable above
the conditions that I name discount2
which I set equal to 20. If I run the code now, it will still print
out the same output because I haven’t changed any of the conditions or values yet. Let’s change the
value of bill total to 210 and click “Run”. Notice that both statements are printed but discount1
is still applied. It’s clear that the if
statement is still executed. Since the value is 210, the condition is still met. To change the program
flow for values over 200, I need to add an and condition
to the if statement. I change the statement to
if a bill total is greater than 100 and bill total
is less than 200. Let’s run the code
and see what happens. Now, the discount
wasn’t applied. The output just says
bill total is 210. Why? Because the
condition is not met. Now, this is where it
gets really interesting. To add a second condition
for bills above 200, I’ll use an else if statement. In between the if
and else statements, I type elif which
stands for else if, and then bill total
is greater than 200. Print the statement bill
is greater than 200. In the next line, I
apply the new discount. I type bill total equal to
bill total minus discount2. First, let me clear my screen so you can focus
just on the results. Now I press “Run”. Notice how the program
flow has changed. The first condition was not met, so the code went to the
second condition where the value of bill total
was compared to 200. Since it was greater than 200, the statement bill is greater
than 200 was printed. The code then proceeded past the else condition because the previous elif
condition was true. Remember the else condition only execute if none of the
preceding conditions are true. Finally, it printed
the statements at the end of the code snippets, namely total bill is 190. This proves that
discount2 was applied. Congratulations, you now know how to control
program flow with if, else, and else if. Once you become proficient in using conditional statements, programming becomes
a lots of fun. I encourage you to test it out. In this video, you
learned how to use conditional
statements in Python. Writing conditional statements
is an essential part of programming and I encourage you to practice
them in your code. The next time you need
to make a decision, think about the conditions
involved and how they can be represented if you
were to code them in Python.
Reading: Conditional statements
Reading
This reading introduces you to the conditional statements of if, else and elif.
If
In keeping with the light switch example, the state of the switch can be stored with a Boolean value of True or False.
- On = True
- Off = False
#Light is currently off
current = False
if current:
current = False
print('Turning light off')
if not current:
current = True
print('Turning light on')
The code snippet above has a variable called current which keeps track of the state of the light – on or off. The first if statement will check if the light is on and if it is, the flow will go inside the condition and set the current variable to False – turning the light off. In the above code snippet, the value of the current variable is initially set to False, so this condition is not met.
The second if statement will check if the light is off and if it is, the flow will go inside the condition and will set the current varaible to True – turning the light on.
If else
The above code works fine but it can be rewritten more effectively by using another condition called else. The following code is an example:
current = False
if current:
current = False
print('Turning light off')
else:
current = True
print('Turning light on')
The else statement has made your code a bit easier to read and given that the flow relates to the same condition, it makes more sense to combine them as part of a single unit.
elif
Python also has another condition called elif which helps when you have multiple conditions to satisfy. The light switch example is pretty straightforward in that you only have to check for the state of on or off – True or False. In certain conditions, it may not be that easy. Thankfully elif is here to help.
Let’s say you want to give a certain discount to customers if they spend over $100. You will also provide an extra discount if that customer is part of a loyalty program. If the customer is not part of the loyalty program and did not spend over a $100, a service charge of 5% is applied.
loyalty_customer = True
total_bill = 124
if loyalty_customer and total_bill > 100:
#give 20% discount
total_bill = total_bill - (float(total_bill)/ 100) * 20
elif total_bill > 100:
#give 10% discount
total_bill = total_bill - (float(total_bill)/ 100) * 10
else:
#sorry no discount, 5% service charge applied.
print('Sorry, no discount ...')
print('Total Bill: ', float(total_bill))
The above code snippet first checks to see if the customer is part of the loyalty program and if they are spending over $100. If both conditions are met, a discount of 20% is applied to the bill. The elif statement will only be executed if the first if condition is not met. The elif statement will only check if the bill is over $100 and if it is, it will apply a discount of 10% to the bill.
The final else statement is only executed if neither of the other two conditions are met. In this case, a charge of 5% is applied to the bill.
Video: Switch statement
The match statement is a new feature in Python 3.10 that allows you to test a variable against many possible values in a more concise and readable way than using if-else statements.
To use the match statement, you first type the keyword match
and then the variable that you want to test. On the next line, you type case
followed by the value that you want to compare the variable to. If the variable matches the value, the code below the case
statement will be executed.
You can also use the or
operator to combine multiple conditions in a single case
statement. For example, the following code will print the message “Success” if the variable http_status
is equal to 200 or 201:
http_status = 201
match http_status:
case 200 | 201:
print("Success")
If none of the case
statements match the variable, the code below the default
statement will be executed.
Here is an example of how to use the match statement to test the value of the variable http_status
and print the appropriate error message:
http_status = 500
match http_status:
case 200:
print("Success")
case 400:
print("Bad request")
case 500:
print("Server error")
default:
print("Unknown error")
The match statement is a powerful tool that can make your code more concise and readable. It is especially useful for testing variables against many possible values.
Switch statement in Python
Python does not have a built-in switch statement, but there are a few ways to implement one. The most common way is to use a dictionary.
To create a switch statement using a dictionary, you first create a dictionary that maps the possible values of the variable to the code that you want to execute. Then, you use a get() method to retrieve the code for the given value. If the value is not in the dictionary, the default code will be executed.
Here is an example of a switch statement using a dictionary:
def switch_statement(variable, cases):
"""Executes the code for the given value in the dictionary.
Args:
variable: The variable to test.
cases: A dictionary mapping values to code.
Returns:
The result of executing the code for the given value.
"""
code = cases.get(variable, lambda: None)
return code()
# Example usage:
cases = {
"a": lambda: print("You chose a."),
"b": lambda: print("You chose b."),
"c": lambda: print("You chose c.")
}
variable = "b"
result = switch_statement(variable, cases)
# Output:
# You chose b.
Another way to implement a switch statement in Python is to use a nested if-else statement. However, this can quickly become messy and difficult to maintain, especially if you have many cases.
Using the match statement
Python 3.10 introduced the match statement, which provides a more concise and readable way to implement a switch statement.
To use the match statement, you first type the keyword match
followed by the variable that you want to test. On the next line, you type case
followed by the value that you want to compare the variable to. If the variable matches the value, the code below the case
statement will be executed.
You can also use the or
operator to combine multiple conditions in a single case
statement. For example, the following code will print the message “Success” if the variable http_status
is equal to 200 or 201:
http_status = 201
match http_status:
case 200 | 201:
print("Success")
If none of the case
statements match the variable, the code below the default
statement will be executed.
Here is an example of how to use the match statement to test the value of the variable http_status
and print the appropriate error message:
http_status = 500
match http_status:
case 200:
print("Success")
case 400:
print("Bad request")
case 500:
print("Server error")
default:
print("Unknown error")
The match statement is a powerful tool that can make your code more concise and readable. It is especially useful for testing variables against many possible values.
Conclusion
There are a few different ways to implement a switch statement in Python. The most common way is to use a dictionary, but the match statement is a newer and more concise option.
Which method you choose will depend on your personal preference and the specific needs of your code.
A match statement compares a value to several different conditions until one is met. True or false?
True
That’s right! A match statement compares a value to several different conditions until one is met.
You may recall how to use the if else and else if statements to test
a variable against a few conditions. But on some occasions you will have
to test a variable against many conditions to deal with this. You can use something called a match
case statement in this video you’ll learn how to use a match statement as
an alternative to an if statement. Now let’s consider an example to compare
the match statement to the if statement say you want to write code to print http
error messages according to error codes. To do this with the if statement,
you would have to write the if condition, all the alternative if else conditions and
finally an else condition conditional statements like if and else work well
over a small number of conditions but over a large number of conditions. Your code can get large complex and
messy fortunately there is a cleaner way to achieve the same result
using the match statement. The match statement In Python was
introduced in version 3.10 using the match statement you can achieve
cleaner more readable code that allows all the same functionality as
the if controlled statement. When using match statements, there are a
few things to remember you can combine several conditions by using the or
operator in the conditional statement. The default is essentially the final
outcome if nothing is found in the case checks it’s the equivalent to the else
in the if blocks let me demonstrate this example ow using V S code. Okay, so I’ve written a simple
if statement that checks for an http status code if the value of
the variable http status Matches one of the conditions,
it will print out the equivalent message. I’m now going to add a match
statement below the if statement for a clear comparison I will test the same
variable against the same values I type match and then the variable http
status and a colon on the next line. I type case which is
the equivalent of the word if and the value of 200 on another line I repeat
the action using the if statement for 200 which is to print the word of success. So in other words the variable is
matched against the value of 200 and the if values are equal it will
print out the word success. Notice that the value of HTTP status is
indeed 200 at the moment so let’s run the code to test how the if and match
statements are processed in the terminal. The word success is printed twice because
the value of http status is matched twice in my code run once for the if statement
and once for the match statement. Now let’s change the value of http
status to 201 and run the code again in this case success is only printed
once why do you think that happens? Because there is an all condition for
the value of 201 in the if statement but none in the match statement to do
the equivalent in the match statement. You use the or operator so
I place my cursor in between 200 and the colon and add an all character and
the value of 200 and one I clean my screen by using C L S and
then click on run again. Now success is printed twice again so in the match statement the pipe
command is shorthand for if or the great thing is that you can add many
case statements in a match statement. But what if none of the values
match the variables value now let’s change the value of HTTP status
to the value of say 550 and explore what happens, click on run and
this time the word unknown is printed. You may be wondering why that is because
the L statement is like a catch all if the value does not match anything
within the if or the L if statements. The default will be the else statement
which in this case has a print function for the word unknown. Well the match statement
also has a default class and you add it by typing the word case
underscore colon and on the next line. Print unknown let’s run
the code again great the output is unknown which means that
the default statement in both the if as well as the match
statement was action. My match statement is coming along well
but it still needs a few tweaks to make it act exactly like the given
if statement to do that. I’ll add a few more case
statements that will test for the same values as the L if statements,
type case 400 colon and then I add a print command
with the words bad request, I add another case and the value of 500. And I also need to test for
501 like in the L if statement above so once again I add an all character and
type 501 on the next line I add the error message that I want
to print which is server error. The match saves a bit of space by
combining the your statement so you don’t have to do a comparison
against a variable each time. Like in the if statement let’s
change the value of http status one more time to 500 and
one I just clear the screen again and click on run and server error
is printed for both statements. Now you know that there are some
differences between the two but the match statement does exactly
the same as the statement in summary. The match statement compares a value to
several different conditions until one of these conditions is met. So you now know how to use the match
statement as an alternative to the if statement to test a variable
against many possible values. The match statement Is relatively
new to Python prior to version 3.10, developers had to get creative and code
to their own solutions you’ll learn more about those alternative
methods later in this lesson.
Video: Looping constructs
Python has two looping constructs for iterating over sequences: the For loop and the While loop.
For loop:
The For loop is used to iterate through a sequence and access each item inside the sequence. The syntax of a For loop is as follows:
for item in sequence:
# code to be executed
The item
variable is a placeholder that will store the current item in the sequence.
While loop:
The While loop is used to execute a block of code repeatedly while a condition is true. The syntax of a While loop is as follows:
while condition:
# code to be executed
The condition
is evaluated before each iteration of the loop. If the condition is true, the code block will be executed. The loop will continue to iterate until the condition becomes false.
Examples:
Here are some examples of how to use For loops and While loops in Python:
# For loop example
my_list = ["apple", "banana", "cherry"]
for fruit in my_list:
print(fruit)
# Output:
# apple
# banana
# cherry
# While loop example
count = 0
while count < 10:
print(count)
count += 1
# Output:
# 0
# 1
# 2
# ...
# 9
Conclusion:
For loops and While loops are powerful tools that can be used to automate repetitive tasks in Python. By understanding how to use these loops, you can write more efficient and effective Python code.
Tutorial on Looping constructs in Python
Looping constructs in Python allow you to execute a block of code repeatedly until a certain condition is met. This can be very useful for automating tasks, such as iterating over a list of items or processing data from a file.
There are two main types of looping constructs in Python:
- For loops: For loops are used to iterate over a sequence of items, such as a list, tuple, or string.
- While loops: While loops are used to execute a block of code repeatedly while a condition is true.
For loops
The syntax for a for loop is as follows:
for item in sequence:
# code to be executed
The item
variable is a placeholder for the current item in the sequence. The loop will iterate over the sequence and execute the code block for each item.
Here is an example of a for loop:
my_list = [1, 2, 3, 4, 5]
for number in my_list:
print(number)
Output:
1
2
3
4
5
While loops
The syntax for a while loop is as follows:
while condition:
# code to be executed
The condition
is evaluated before each iteration of the loop. If the condition is true, the code block will be executed. The loop will continue to iterate until the condition becomes false.
Here is an example of a while loop:
count = 0
while count < 10:
print(count)
count += 1
Output:
0
1
2
3
4
5
6
7
8
9
Nested loops
You can also nest loops, which means putting one loop inside of another loop. This can be useful for performing complex tasks, such as iterating over a list of lists or processing data from a multidimensional array.
Here is an example of a nested for loop:
my_list = [[1, 2, 3], [4, 5, 6]]
for inner_list in my_list:
for number in inner_list:
print(number)
Output:
1
2
3
4
5
6
Conclusion
Looping constructs are a powerful tool in Python that can help you to automate tasks and write more efficient code. By understanding how to use for loops and while loops, you can improve your Python programming skills.
Looping is used to iterate through the sequence and access each item inside the sequence. True or false?
True
That’s right! Looping is used to iterate through the sequence and access each item inside the sequence.
Have you ever come across
a song that you like so much you want to listen to it again and
again? You select the loop option so
that you can listen to it repeatedly. This action of repetition is known as
looping, and also exists in Python. In this video you’ll learn to use
looping constructs when the same set of steps must be carried out many times. Python has two different types
of looping constructs for iterating over sequences,
the For loop and the While loop. Looping is used to iterate
through the sequence and access each item inside the sequence. Let’s start with a basic example
of looping using a string. First, you declare a variable called str,
which is of type string, recall that a string in
Python is a sequence, which means you can iterate over
each character in the string. A sequence is just an ordered set. Now, let’s break apart the for
loop and discover how it works. The variable item is a placeholder
that will store the current letter in the sequence. You may also recall that you
can access any character in the sequence by its index. The For
loop is accessing it in the same way and assigning the current value
to the item variable. This allows us to access the current
character to print it for output. When the code has run, the output will
be the letters of the word, looping, each letter on its own line. Now that you know about looping constructs
in Python, let me demonstrate how these work further using some code examples
to output an array of tasty desserts. Python offers us multiple
ways to do loops or looping. You’ll now cover the For
loop as well as the While loop. Let’s start with the basics
of a simple For loop. To declare a For loop,
I used the for key word. I now need a variable
to put the value into. In this case I am using i, I also use the in keyword to
specify where I want to loop over. I add a new function called range to
specify the number of items in a range. In this case, I’m using 10 as an example. Next, I do a simple print statement
by pressing the enter key to move to a new line. I select the print function,
and within the brackets, I enter the name looping and the value
of i, then I click on the run button. The output indicates the iteration
loop through the range of 0 to 9. It’s important to note
the three main points. The iteration starts 0 based on
the index of the item itself. Every for loop usually starts with 0. Most arrays starts at 0. The reason for that is that it’s
the first item in an array or the first item in the index. In this case, the last item in
the array or index will be 9. Now, I want to change what I look through. As an example, I will enter a simple
array above and call it favorites. To do this, I start by removing
the hash sign in front of favorites. Next, I replaced the range
function in the current for loop with favorites to look through. The i that I declared as part of the for
loop can change to any value, and in this case I’m using item. I now change my print statements
to include item in my print loop. I also changed the text,
I like this dessert. I click on the run button
to print the value stream. In this case, item calls each of
the five dessert titles in turn and our print statement combines
them into a sentence. The next looping option I’m
discussing is the While loop. The While loop differs
Slightly from the For loop. To demonstrate this type of loop, I first
comment out the for loop on my screen. Let’s start by using the while keyword. As in the for loop, I need to specify
a condition to make the loop over n times, depending on the value itself. First, I need to declare a counter. I do this by typing count = 0
above my looping statement. Next, I enter count after the while
keyword followed by the < sign and the word favorites. Now I insert the function len to
provide the length of favorites. This means the loop will run while
the count is less than the length of favorites. In other words,
while it is less than five. To print the value of
the looping statement, I press the enter key
to move to a new line. Then I select the print function, and
within brackets I enter the text, I like this dessert. The key difference here is that I need to
use the index to access the items within the favorite array. To do this, I type favorites and
add count to represent the index. It’s important that I
now increment count so that it will essentially
match the loop statement. If I do not increment count, I’ll end up
with what is called an infinite loop. This means it will just keep looping and looping until the compiler stops
it from running out of memory. To increment the count, I press enter to
move to a new line and add count += 1. I clear my screen and
click the run button. I get the same print output as the for
loop. It’s important to note that
In a standard for loop, I don’t have access to the index, but I
can use the enumerate function to do that. So I changed my current for
loop statement by adding idx, and it becomes for idx Item in. Then I call the enumerate function
with favorites in parenthesis. On the next line, to print the output,
I replace the text, I like this dessert with idx and
click the run button. The results display the index and
the value of the item within the array. Congratulations, in this video you learned
about looping constructs in Python using the For loop.
Reading: Looping Constructs: Practical Examples
Reading
This reading introduces you to the different looping constructs in Python.
For loop
Looping through data is a fairly common task in any programming language. The for loop makes it easy to work with any type of sequence in Python. Let’s run through some examples of for loops and the different ways you can use them.
favorites = ['Creme Brulee', 'Apple Pie', 'Churros', 'Tiramisú', 'Chocolate Cake']
for dessert in favorites:
print('One of my favorite desserts is', dessert)
In the code snippet above, the for loop iterates over the contents of the favorites list and prints out a sentence with the dessert name for each item in the list.
The for loop is based on the size or length of the elements to iterate over.
While loop
On the other hand, a while loop is based upon a condition being true. Once the condition is no longer true the loop stops. The amount of times the while loop is executed is not known ahead of time as it is with the for loop.
If you take the above for loop example and convert that to the while loop alternative, you will end up with something like this:
favorites = ['Creme Brulee', 'Apple Pie', 'Churros', 'Tiramisú', 'Chocolate Cake']
count = 0
while count < len(favorites):
print('One of my favorite desserts is', favorites[count]);
count += 1
Note that you needed to declare a counter variable. The counter variable is then compared to the length of the favorites list. As you loop through the data the counter is incremented. Once the condition count < len(favorites) is no longer true the loop will stop.
Reading: Practicing control flow and loops
Reading
Controlling loops
So far, you have only looped over sequences based on the length of the data you wanted to iterate over. In many cases, this is not necessary and depending on the amount of the data it can also be quite costly. You’ll now examine how you can control the flow of the loop and exit out when a specific condition is met. You will also look at control statements such as break, continue and pass.
If else
In many cases, you may need to search for a particular item in a list. Once the item is found, there is no need to continue looping over the other results. Using the same example as before, let’s assume you only need to check if the dessert “Churros” is in the list and if it is, print a single statement.
#Starter Code
favorites = ['Creme Brulee', 'Apple Pie', 'Churros', 'Tiramisú', 'Chocolate Cake']
for dessert in favorites:
if dessert == 'Churros':
print('Yes! One of my favorite desserts is', dessert)
Running the above code will output the following:
Yes! One of my favorite desserts is Churros
But what happens if you look for a dessert and that dessert is not on the list? The code above is currently not set up to handle this. Let’s look for the dessert “Pudding” which is not on the list, and also add an else statement to handle the case of when it’s not found. If the dessert is not part of the list, you will print a new statement.
#Starter Code
favorites = ['Creme Brulee', 'Apple Pie', 'Churros', 'Tiramisú', 'Chocolate Cake']
for dessert in favorites:
if dessert == 'Pudding':
print('Yes one of my favorite desserts is', dessert)
else:
print('No sorry, that dessert is not on my list')
Running the above code will result in the following output:
No sorry, that dessert is not on my list
Loop control statements
Break
The code works as intended but you may notice one flaw. If you change the search term to something that is on the list like “Churros” and run it again you will get the following output:
Yes one of my favorite desserts is Churros No sorry, not a dessert on my list
This is not what you want! The dessert is on the list but it still printed out the else condition. To fix it, you need to use a control statement called break.
Add the following:
#Starter Code
favorites = ['Creme Brulee', 'Apple Pie', 'Churros', 'Tiramisú', 'Chocolate Cake']
for dessert in favorites:
if dessert == 'Pudding':
print('Yes one of my favorite desserts is', dessert)
break
else:
print('No sorry, not a dessert on my list')
Running the above code will resolve the issue. The break statement is used to stop the loop, which in turn also stops the else condition. Without the break the loop will continue even after the if condition is satisfied.
Continue
Similar to break, continue can be used to control the iteration of the loop. The key difference is that it can allow you to skip over a section of the loop but then continue on with the rest. If you change your code to this, you will notice the outcome will print everything except the Churros dessert.
#Starter Code
favorites = ['Creme Brulee', 'Apple Pie', 'Churros', 'Tiramisú', 'Chocolate Cake']
for dessert in favorites:
if dessert == 'Churros':
continue
print('Other desserts I like are', dessert)
Pass
The pass statement allows you to run through the loop in its entirety and effectively ignore that the if condition has been satisfied.
#Starter Code
favorites = ['Creme Brulee', 'Apple Pie', 'Churros', 'Tiramisú', 'Chocolate Cake']
for dessert in favorites:
if dessert == 'Churros':
pass
print('Other desserts I like are', dessert)
Video: Nested loops and the effect on algorithmic complexity
Python nested loops can be used to solve more complex problems. They work by iterating over two or more lists or ranges. The outer loop iterates over the first list or range, and the inner loop iterates over the second list or range. This process continues until all of the elements in the lists or ranges have been iterated over.
Here is an example of a nested loop in Python:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
for i in list1:
for j in list2:
print(i, j)
Output:
1 4
1 5
1 6
2 4
2 5
2 6
3 4
3 5
3 6
Nested loops can be used to solve a variety of problems, such as finding the maximum or minimum value in a list, or finding all of the pairs of numbers in two lists that add up to a certain number.
It is important to be aware of the time complexity of nested loops. The time complexity of a nested loop is the product of the time complexity of the outer loop and the time complexity of the inner loop. For example, the time complexity of the nested loop in the example above is O(n^2), where n is the number of elements in each list. This means that the time it takes to run the loop will grow quadratically with the size of the lists.
When using nested loops, it is important to choose the right data structures and algorithms to minimize the time complexity of the loop. For example, if you are trying to find the maximum value in a list, you can use a heap data structure to reduce the time complexity to O(n log n).
Here are some tips for optimizing nested loops:
- Use the appropriate data structures and algorithms.
- Avoid unnecessary iterations.
- Use early returns.
- Parallelize the loops.
Tutorial on “Nested loops and the effect on algorithmic complexity in Python”
What are nested loops?
Nested loops are a type of control flow statement that allow you to iterate over multiple sequences of data. A nested loop is a loop that contains another loop inside of it. The outer loop iterates over the first sequence of data, and the inner loop iterates over the second sequence of data.
How do nested loops work?
Nested loops work by iterating over the outer loop first. Once the outer loop has finished iterating, the inner loop begins iterating. The inner loop will continue to iterate until it has finished iterating over the second sequence of data. Then, the outer loop will move on to the next iteration.
Example of a nested loop in Python:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
for i in list1:
for j in list2:
print(i, j)
Output:
1 4
1 5
1 6
2 4
2 5
2 6
3 4
3 5
3 6
Algorithmic complexity of nested loops
The algorithmic complexity of a nested loop is the product of the algorithmic complexity of the outer loop and the algorithmic complexity of the inner loop. For example, the algorithmic complexity of the nested loop in the example above is O(n^2), where n is the number of elements in each list. This means that the time it takes to run the loop will grow quadratically with the size of the lists.
How to optimize nested loops
There are a number of ways to optimize nested loops:
- Use the appropriate data structures and algorithms. For example, if you are trying to find the maximum value in a list, you can use a heap data structure to reduce the algorithmic complexity to O(n log n).
- Avoid unnecessary iterations. For example, if you are iterating over a list and you find the element you are looking for, you can break out of the loop early.
- Use early returns. For example, if you are iterating over a list and you find that the current element does not meet your criteria, you can return from the function early.
- Parallelize the loops. If you are running a nested loop on a multi-core system, you can parallelize the loops to improve performance.
Conclusion
Nested loops are a powerful tool that can be used to solve a variety of problems. However, it is important to be aware of the algorithmic complexity of nested loops and to take steps to optimize them.
True or false: The inner loop performs the first iteration during the nested loop process.
False
Yes, it’s the outer loop that performs the first iteration during the nested loop process.
Python nested loops can be used to solve more
complex problems. For example, the
nested for-loop is written by indentation
inside the outer loop. Let’s explore this
further now and break down how a
nested loop works. First, the outer loop and start and then step
into the inner loop. Then the inner loop
will run until its range limit is
met, 10 in this case. Once the inner loop completes, it will come back to
the outer loop for the next iteration and then step into the
inner loop again. This will happen
into the outer loop has reached its limits. Now, let’s explore
an example using nested loops to iterate
over two lists. For example, suppose you
have two lists of integers from one to nine and a count variable that is set to zero. You again have two loops. The outer loop, which
will iterate over list 1, and the inner loop, which
iterates over list 2. If you run this code, it gives an output of 90. Let me break it down for you. The outer loop runs a
total of nine times. The inner loop runs a total
of 9 multiplied by 9, which is 81 times and 9 plus
81 gives a total of 90. To help visualize
how this would look, you can make some
minor changes to the loop to output
what it looks like. You now know that the
number of times the loop is run is based on
the size of the list. Now that you’ve learned
about nested loops, let me demonstrate some code
examples of nested loops. I have VS Code open. First, let me start with a simple example and
write a for-loop. I type for i and I use
the range function. I have in range 10. Above the loop, I label it
with a comment outer loop. This first for loop is
considered an outer loop. Inside I will have
an inner loop. I write a comment inner loop right under the first for loop. Now I type for j in. Then I use the range
function again. I pass in a 10 and
end with a colon. The 10 indicates the number of times the loop will
iterate or repeat. In this example,
I print out zero, and then I use end
equals and a string with space in double quotes to ensure it prints out in an even manner. Lastly, I’m going to
print out an empty line so that it goes to a new
line in each iteration. If I run the for loop, the system prints
out a 2D array grid. This is just the demonstrates
how the for loop works. If I want to print
out a single line, I can change the
outer loop to one. I play my screen, run it again, and this time a single
line of zeros is printed out because the outer
loop only iterated once. This is all based on the outer
loop only. It runs once. But when it goes to the
inner loop that it runs 10 times and prints out a zero for each item
on the same line. Every time the
outer loop starts, it will go into the inner loop. The inner loop must
finish before it comes back to the outer
loop to start on two, three, four, and so on. I can showcase that by simply changing the outer loop range 2. In this case, only two
lines are printed. The first when i equals 0, it comes into the inner loop
and prints out 10 times. When that’s finished, it
comes back to the outer loop. Then i is incremented
again to one. Then it will be printed out from j’s inner loop and
another 10 zeros again. The other issues
to consider with nested loops is the complexity, or what is commonly known
as time complexity. The larger the
array, the more time is going to take to run my code. Let me showcase
this by running a for loop for a larger range, but also putting a
timestamp on it. I import the time module to put a timestamp and
what’s printed out. I close it as the start
time equals time dot time, which is the function
that I want to call. The start time is initialized the moment I run the script. I also want to print out
how long it took to finish. I do that by putting a print statement
outside the for loop. I then calculate the time
as in the time it took to finish and then subtract that
from the start time above. This is going to print
out many decimal places. I use another
function named round, which rounds numbers to
a decimal by choice. In this case, I round it
off to two decimal points. Let me clear my
screen one more time. I click on ”Run,”
and it outputs the time of zero
dot zero seconds. This makes sense
because the time my code takes to run
is really short. Let me increase the range
in the outer loop to a 100. I also increase the range and
the inside loop to a 100. I click on ”Run”
one more time. The time now goes up 0.01. In this case, it’s
not a big difference. But when you’re dealing
with large datasets, this will have a huge effect on the running time of my code. This time, let’s
say, for example, that I keep the
outer loop to a 100, but I increase the
inner loop to 1,000. I clear the screen
and click on ”Run.” The time increases to 0.04. If I increase the inner
loop one more time to 10,000 and I clear the
screen and click ”Run.” Now the time goes up to 0.45. The larger the array or
the larger the range, in this case, the more time it’s going to take for
a program to complete. It’s always important
to remember how you can optimize code to make it
run more efficiently. Consider the amount of time
your code will take to run. You just covered
nested for loops and learned about the issue
of time complexity. In this video, you learned about nested loops and how they work.
Reading: Exercise: Use control flow and loops to solve a problem
Reading
Introduction
In this exercise, you will practice control flow with loops to solve problems. You will be given a list of integers and you will have to add some code to find a specific number in a list and return it.
Instructions
1. Under the num_list create a new for loop and print out each value on the list in sequential order.
2. Inside the for loop, create a condition that will look for all numbers that are greater than 45 and print out only numbers that meet that condition
3. Change the print statement to “Over 45” and add an else condition with a print statement of “Under 45”.
4. Update the for loop to use the enumerate function so you can get and use the index. Alter the condition to look for number 36 and print out the following: ‘Number found at position: ‘, index number
5. Next, create a new variable called count and assign it a value of 0 and place it outside the for loop.
6. Inside the for loop increment the counter by 1.
7. Add a print statement outside the for loop to print the value of the count variable.
8. Finally, add a break statement directly after the print statement inside the if condition for finding the number.
Reading: Use control flow and loops to solve a problem – solution
Reading
Solution Code
Step 1
num_list = [33,42,5,66,77,22,16,79,36,62,78,43,88,39,53,67,89,11]
for num in num_list:
print(num)
Step 2
num_list = [33,42,5,66,77,22,16,79,36,62,78,43,88,39,53,67,89,11]
for num in num_list:
if num > 45:
print(num)
Step 3
num_list = [33,42,5,66,77,22,16,79,36,62,78,43,88,39,53,67,89,11]
for num in num_list:
if num > 45:
print('Over 45')
else:
print('Under 45')
Step 4
num_list = [33,42,5,66,77,22,16,79,36,62,78,43,88,39,53,67,89,11]
for x,num in enumerate(num_list):
if num == 36:
print('Number found at ', x)
Step 5,6,7
num_list = [33,42,5,66,77,22,16,79,36,62,78,43,88,39,53,67,89,11]
count = 0
for x,num in enumerate(num_list):
count += 1
if num == 36:
print('Number found at ', x)
print(count)
Step 8
num_list = [33,42,5,66,77,22,16,79,36,62,78,43,88,39,53,67,89,11]
count = 0
for x,num in enumerate(num_list):
count += 1
if num == 36:
print('Number found at ', x)
break
print(count)
Practice Quiz: Self-review: Use control flow and loops to solve a problem
Python for loops work on any type of sequence data type including strings.
True
Correct! Python for loops work on any type of sequence data type including strings.
The enumerate function is used to provide the index of current iteration of a for loop.
True
Correct! An enumerate function is used to provide the index of current iteration of a for loop.
A break statement can be used to exit out of a for loop based on a certain condition being satisified.
True
Correct! A break statement is used to exit out of a for loop based on a certain condition being satisified.
Video: Module summary: Getting started with Python
In this module, you learned:
- The history of programming and how it works in a general sense.
- The benefits of Python and where it’s used.
- How to evaluate if your system is set up correctly for Python development.
- The differences of running code from the command line via the IDE.
- The importance of syntax and space in Python.
- What variables are and how they are used.
- How to identify data types in Python.
- How to declare and use strings.
- The two types of casting and how to apply them.
- The basics of user inputs and console outputs.
- Math and logical operators in Python.
- How to use conditional statements to control the flow of programs.
- How to use match case statements as an alternative to if statements.
- What looping constructs are and how to use them.
- What nested loops are and how they work.
You have now learned the basics of Python programming, including control flows and conditionals. This will allow you to write more complex and powerful Python programs.
Quiz: Module quiz: Getting started with Python
Python is a dynamically typed language. What does this mean?
Python does not require a type for a variable declaration. It automatically assigns the data type at run time.
Correct! When variables are declared in Python they are automatically assigned a data type.
AI assistant
The correct answer is: Python does not require a type for a variable declaration. It automatically assigns the data type at run time.
Python is a dynamically typed language, which means that the data type of a variable is determined at runtime, rather than at compile time. This means that you do not need to explicitly declare the data type of a variable before assigning it a value. For example, the following code is valid Python code:
name = "Bard"
age = 1
In this code, the variable name
is assigned a string value and the variable age
is assigned an integer value. The data types of these variables are automatically assigned by Python at runtime.
There are several advantages to using a dynamically typed language. One advantage is that it can make your code more concise and readable. For example, in the code above, you do not need to explicitly declare the data types of the variables name
and age
. This makes the code more concise and easier to read.
Another advantage of dynamic typing is that it can make your code more flexible. For example, you can change the data type of a variable at runtime. This can be useful in situations where you need to process data from different sources.
However, there are also some disadvantages to using a dynamically typed language. One disadvantage is that it can lead to runtime errors. For example, if you try to add a string and an integer, Python will raise a runtime error.
Another disadvantage of dynamic typing is that it can make it more difficult to debug your code. For example, if you get an error message, it can be difficult to track down the source of the error because Python does not keep track of the data types of variables at compile time.
Overall, dynamic typing is a powerful feature that can make your code more concise, readable, and flexible. However, it is important to be aware of the disadvantages of dynamic typing and to take steps to avoid runtime errors and debugging problems.
How do you create a block in Python?
A block is created using a colon following by a new line and indentation
Correct – A block of code created by using a colon, new line and indentation.
AI assistant
A block in Python is created using a colon (:
) followed by a new line and indentation. All code that is indented at the same level is considered to be part of the same block.
For example, the following code creates a block:
def greet(name):
"""Greets the given name."""
print(f"Hello, {name}!")
# This is outside of the block.
if __name__ == "__main__":
greet("Bard")
In this code, the function greet()
is defined within a block. The body of the function is indented, which means that it is part of the block. The code outside of the function is not part of the block.
Blocks are used to group code together and to control the flow of execution of a program. For example, blocks can be used to implement if statements, loops, and functions.
Here is an example of a block used in an if statement:
if name == "Bard":
print("Hello, Bard!")
In this code, the print()
statement is only executed if the name
variable is equal to “Bard”. This is because the print()
statement is indented, which means that it is part of the if statement block.
Blocks are a fundamental part of Python programming. By understanding how to use blocks, you can write more complex and powerful Python programs.
When declaring variable in Python, can a variable name contain white space?
No
Correct! A variable must not contain white space.
AI assistant
No, a variable name in Python cannot contain white space.
Variable names in Python must consist only of letters, numbers, and underscores. They cannot start with a number, and they cannot contain white space.
If you try to declare a variable with a white space in its name, Python will raise a syntax error. For example, the following code will raise a syntax error:
my variable name = "Bard"
To avoid this error, you must use underscores instead of white space in your variable names. For example, the following code is valid Python code:
my_variable_name = "Bard"
It is important to note that variable names in Python are case-sensitive. This means that the variables my_variable_name
and My_Variable_Name
are two different variables.
Here are some tips for choosing good variable names in Python:
- Use descriptive names that are easy to understand.
- Avoid using abbreviations unless they are well-known and widely used.
- Use underscores to separate words in variable names.
- Avoid using keywords as variable names.
By following these tips, you can choose good variable names that will make your code more readable and maintainable.
How can a variable be deleted in python?
The del keyword
Correct! The del keyword is used to delete a variable by typing del variable name.
AI assistant
The del
keyword is used to delete variables in Python. When you use the del
keyword, Python will remove the variable from memory.
For example, the following code deletes the variable name
:
name = "Bard"
del name
After the del
statement is executed, the variable name
no longer exists. You cannot access it or assign a new value to it.
It is important to note that the del
keyword can also be used to delete other objects, such as lists, dictionaries, and functions.
Here is an example of using the del
keyword to delete a list:
my_list = [1, 2, 3, 4, 5]
del my_list
After the del
statement is executed, the list my_list
no longer exists. You cannot access it or add new elements to it.
It is important to use the del
keyword carefully, because it is permanent. Once you delete a variable or object, you cannot get it back.
Here are some tips for using the del
keyword safely:
- Make sure that you really want to delete the variable or object before you use the
del
keyword. - Avoid using the
del
keyword on variables or objects that are being used by other parts of your program. - Use the
del
keyword with caution when debugging your code.
By following these tips, you can use the del
keyword safely and effectively.
In Python, how can you convert a number to a string?
str()
Correct! To convert a number to a string you need to use the str() function. This will change an int like 8 to “8”.
AI assistant
To convert a number to a string in Python, you can use the str()
function. The str()
function takes any object as input and returns a string representation of that object.
For example, the following code converts the integer 123
to the string "123"
:
number = 123
string = str(number)
print(string)
Output:
123
You can also use the str()
function to convert floating-point numbers to strings. For example, the following code converts the floating-point number 3.14
to the string "3.14"
:
number = 3.14
string = str(number)
print(string)
Output:
3.14
The str()
function is a very useful function in Python, and it is used in a variety of different ways. For example, you can use the str()
function to format strings, to create log messages, and to send data over a network.
Here are some tips for using the str()
function:
- If you are converting a floating-point number to a string, you can use the
format()
method to specify the number of decimal places to include in the string. - If you are converting a list or dictionary to a string, you can use the
join()
method to join the elements of the list or dictionary together with a separator string. - If you are converting a function to a string, you can use the
__repr__()
method to get a string representation of the function.
By following these tips, you can use the str()
function effectively to convert numbers and other objects to strings.
An Integer – int in Python can be converted to type Float by using the float function?
True
Correct! The float function can be used to covert a type int to a float for better precision.
AI assistant
True. An Integer – int in Python can be converted to type Float by using the float() function. The float() function takes any object as input and returns a floating-point number representation of that object.
For example, the following code converts the integer 123
to the floating-point number 123.0
:
integer = 123
floating_point_number = float(integer)
print(floating_point_number)
Output:
123.0
This is because the float() function automatically converts the integer 123
to a floating-point number when it is passed to the function.
You can also use the float() function to convert strings that represent numbers to floating-point numbers. For example, the following code converts the string "3.14"
to the floating-point number 3.14
:
string = "3.14"
floating_point_number = float(string)
print(floating_point_number)
Output:
3.14
The float() function is a very useful function in Python, and it is used in a variety of different ways. For example, you can use the float() function to perform calculations on floating-point numbers, to format strings, and to create log messages.
What is the purpose of break in a for loop in Python?
It controls the flow of the loop and stops the current loop from executing any further.
Correct! The break keyword will stop the loop from executing and transfer the control to the next block of code.
AI assistant
The break
statement is used to terminate a for loop immediately. When the break
statement is encountered, the loop is exited and the next statement after the loop is executed.
Here is an example of a for loop with a break
statement:
for i in range(10):
if i == 5:
break
print(i)
Output:
0
1
2
3
4
In this example, the loop will iterate over the numbers from 0 to 9. However, when the loop reaches the number 5, the break
statement is encountered and the loop is exited. As a result, the numbers 6, 7, 8, and 9 are not printed.
The break
statement can be used in both for loops and while loops. It is a useful tool for controlling the flow of execution of a program.
Here are some tips for using the break
statement:
- Use the
break
statement to terminate a loop when a specific condition is met. - Avoid using the
break
statement to exit a loop prematurely, unless it is absolutely necessary. - Be careful when using the
break
statement in nested loops. If you use thebreak
statement in an inner loop, it will only exit the inner loop.
By following these tips, you can use the break
statement effectively to control the flow of execution of your programs.
An enumerate function is used to provide the index of the current iteration of a for loop.
True
Correct! An enumerate function is used to provide the index of current iteration of a for loop.
AI assistant
True. An enumerate function is used to provide the index of the current iteration of a for loop. It takes an iterable as an argument and returns an iterator that yields tuples containing the index and the value of the current element in the iterable.
For example, the following code uses the enumerate function to print the index and value of each element in a list:
my_list = [1, 2, 3, 4, 5]
for index, value in enumerate(my_list):
print(index, value)
Output:
0 1
1 2
2 3
3 4
4 5
The enumerate function can be used in a variety of ways. For example, it can be used to:
- Iterate over the elements of a list and keep track of the index of each element.
- Create a new list that contains the indexes of the elements in another list.
- Create a new list that contains the values of the elements in another list, but in a different order.
The enumerate function is a very useful function in Python, and it is used in a variety of different ways.
What will be the output of the code below: a = isinstance(str, “aa”) print(a)
It will throw an error.
Correct ! It will throw a TypeError as the correct format here must be
isinstance(“aa”, str)
AI assistant
The output of the code below will be True
.
a = isinstance(str, "aa")
print(a)
The isinstance()
function checks if an object is an instance of a given class or type. In this case, the isinstance()
function is checking if the object "aa"
is an instance of the class str
. Since "aa"
is a string, the isinstance()
function will return True
.
Here is a breakdown of the code:
a = isinstance(str, "aa")
: This line assigns the boolean value returned by theisinstance()
function to the variablea
.print(a)
: This line prints the value of the variablea
to the console.
Since the isinstance()
function returns True
in this case, the output of the code will be True
.
Select all the valid input() formats among the following. Select all that apply 1
input(“”)
Correct! The input() can work even without assignment to some variable and an empty prompt
input()
Correct! The input() can work even without assignment to some variable.
name = input(“What is your name? “)
Correct! This is the standard format for using input()
AI assistant
All of the following input() formats are valid:
input("")
input()
name = input("What is your name? ")
"" = input("My name is: " + name)
The input()
function takes a prompt as an argument and returns the user’s input as a string. The prompt can be an empty string, or it can be a string that prompts the user for input.
The first two examples are simply calling the input()
function without any arguments. This will prompt the user to enter some input, and the input()
function will return the user’s input as a string.
The third example assigns the user’s input to a variable called name
. The prompt in this example asks the user for their name.
The fourth example is a bit more complicated. It uses the input()
function to get the user’s name, and then it uses the +
operator to concatenate the user’s name to the string “My name is: “. Finally, it uses the input()
function to get the user’s input again, but this time the prompt is an empty string. This will cause the input()
function to return the value of the previous expression, which is "My name is: " + name
.
Here is an example of how to use the input()
function in a Python program:
name = input("What is your name? ")
print("Hello, {}!".format(name))
Output:
What is your name? Bard
Hello, Bard!
Congratulations on reaching the end
of control flows and conditionals and the end of the module on
getting started with Python. Let’s recap what you’ve learned. So now you know how to explain
the history of programming and how it works in a general sense. Describe the benefits of Python and
where it’s used. Evaluate if your system is set up
correctly for Python development. Identify the differences of running
code from the command line via the IDE. Explain the importance of syntax and
space in Python. Describe what variables are and
how they are used. Identify data types in Python. Explain how to declare and use strings. Describe the two types of casting and
how to apply them. Describe the basics of user inputs and
console outputs. Recognize math and
logical operators in Python. Use conditional statements to
control the flow of programs. Use match case statement as
an alternative to if statements. Explain looping constructs and
how to use them and explain nested loops and how they work. You’ve learned a lot about the structure
and rules that guide Python and now you’re ready to create programs. Great work, see you next time.
Reading: Additional resources
Reading
Access the links below to learn more about programming in Python.
Explore the Python website to learn more about control flow: Learn more about Python
Check out W3Scools to learn more about Conditional Operators: W3Schools
Learn more about conditional statements at the Real Python website: realpython.com