This document discusses strings in Python. It shows how to create strings, concatenate strings using the + operator, use print() to output strings, and run Python scripts. It also covers string slicing to access parts of a string, string indices, the len() function, and calculating string halfway points using integer division.
This presentation provides the information on python including the topics Python features, applications, variables and operators in python, control statements, numbers, strings, print formatting, list and list comprehension, dictionaries, tuples, files, sets, boolean, mehtods and functions, lambda expressions and a sample project using Python.
This Edureka Python tutorial is a part of Python Course (Python Tutorial Blog: https://goo.gl/wd28Zr) and will help you in understanding what exactly is Python and its various applications. It also explains few Python code basics like data types, operators etc. Below are the topics covered in this tutorial:
1. Introduction to Python
2. Various Python Features
3. Python Applications
4. Python for Web Scraping
5. Python for Testing
6. Python for Web Development
7. Python for Data Analysis
Python 101: Python for Absolute Beginners (PyTexas 2014)Paige Bailey
If you're absolutely new to Python, and to programming in general, this is the place to start!
Here's the breakdown: by the end of this workshop, you'll have Python downloaded onto your personal machine; have a general idea of what Python can help you do; be pointed in the direction of some excellent practice materials; and have a basic understanding of the syntax of the language.
Please don't forget to bring your laptop!
Audience: "Python 101" is geared toward individuals who are new to programming. If you've had some programming experience (shell scripting, MATLAB, Ruby, etc.), then you'll probably want to check out the more intermediate workshop, "Python 101++".
This presentation provides the information on python including the topics Python features, applications, variables and operators in python, control statements, numbers, strings, print formatting, list and list comprehension, dictionaries, tuples, files, sets, boolean, mehtods and functions, lambda expressions and a sample project using Python.
This Edureka Python tutorial is a part of Python Course (Python Tutorial Blog: https://goo.gl/wd28Zr) and will help you in understanding what exactly is Python and its various applications. It also explains few Python code basics like data types, operators etc. Below are the topics covered in this tutorial:
1. Introduction to Python
2. Various Python Features
3. Python Applications
4. Python for Web Scraping
5. Python for Testing
6. Python for Web Development
7. Python for Data Analysis
Python 101: Python for Absolute Beginners (PyTexas 2014)Paige Bailey
If you're absolutely new to Python, and to programming in general, this is the place to start!
Here's the breakdown: by the end of this workshop, you'll have Python downloaded onto your personal machine; have a general idea of what Python can help you do; be pointed in the direction of some excellent practice materials; and have a basic understanding of the syntax of the language.
Please don't forget to bring your laptop!
Audience: "Python 101" is geared toward individuals who are new to programming. If you've had some programming experience (shell scripting, MATLAB, Ruby, etc.), then you'll probably want to check out the more intermediate workshop, "Python 101++".
This Edureka Python tutorial will help you in learning various sequences in Python - Lists, Tuples, Strings, Sets, Dictionaries. It will also explain various operations possible on them. Below are the topics covered in this tutorial:
1. Python Sequences
2. Python Lists
3. Python Tuples
4. Python Sets
5. Python Dictionaries
6. Python Strings
Youtube Link: https://youtu.be/woVJ4N5nl_s
** Python Certification Training: https://www.edureka.co/data-science-python-certification-course **
This Edureka PPT on 'Python Basics' will help you understand what exactly makes Python special and covers all the basics of Python programming along with examples.
Follow us to never miss an update in the future.
YouTube: https://www.youtube.com/user/edurekaIN
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
Castbox: https://castbox.fm/networks/505?country=in
Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...Edureka!
This Edureka "Python Loops" tutorial (Python Tutorial Blog: https://goo.gl/wd28Zr) will help you in understanding different types of loops used in Python. You will be learning how to implement all the loops in python practically. Below are the topics covered in this tutorial:
1) Why to use loops?
2) What are loops?
3) Types of loops in Python: While, For, Nested
4) Demo on each Python loop
This Edureka Python Programming tutorial will help you learn python and understand the various basics of Python programming with examples in detail. Below are the topics covered in this tutorial:
1. Python Installation
2. Python Variables
3. Data types in Python
4. Operators in Python
5. Conditional Statements
6. Loops in Python
7. Functions in Python
8. Classes and Objects
Python Tutorial | Python Tutorial for Beginners | Python Training | EdurekaEdureka!
This Edureka Python tutorial will help you in understanding the various fundamentals of Python programming with examples in detail. This Python tutorial helps you to learn following topics:
1. Introduction to Python
2. Who uses Python
3. Features of Python
4. Operators in Python
5. Datatypes in Python
6. Flow Control
7. Functions in Python
8. File Handling in Python
Provides an introductory level understanding of the Python Programming Language and language features. Serves as a guide for beginners and a reference to Python basics and language use cases.
This Edureka Python tutorial will help you in learning various sequences in Python - Lists, Tuples, Strings, Sets, Dictionaries. It will also explain various operations possible on them. Below are the topics covered in this tutorial:
1. Python Sequences
2. Python Lists
3. Python Tuples
4. Python Sets
5. Python Dictionaries
6. Python Strings
Youtube Link: https://youtu.be/woVJ4N5nl_s
** Python Certification Training: https://www.edureka.co/data-science-python-certification-course **
This Edureka PPT on 'Python Basics' will help you understand what exactly makes Python special and covers all the basics of Python programming along with examples.
Follow us to never miss an update in the future.
YouTube: https://www.youtube.com/user/edurekaIN
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
Castbox: https://castbox.fm/networks/505?country=in
Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...Edureka!
This Edureka "Python Loops" tutorial (Python Tutorial Blog: https://goo.gl/wd28Zr) will help you in understanding different types of loops used in Python. You will be learning how to implement all the loops in python practically. Below are the topics covered in this tutorial:
1) Why to use loops?
2) What are loops?
3) Types of loops in Python: While, For, Nested
4) Demo on each Python loop
This Edureka Python Programming tutorial will help you learn python and understand the various basics of Python programming with examples in detail. Below are the topics covered in this tutorial:
1. Python Installation
2. Python Variables
3. Data types in Python
4. Operators in Python
5. Conditional Statements
6. Loops in Python
7. Functions in Python
8. Classes and Objects
Python Tutorial | Python Tutorial for Beginners | Python Training | EdurekaEdureka!
This Edureka Python tutorial will help you in understanding the various fundamentals of Python programming with examples in detail. This Python tutorial helps you to learn following topics:
1. Introduction to Python
2. Who uses Python
3. Features of Python
4. Operators in Python
5. Datatypes in Python
6. Flow Control
7. Functions in Python
8. File Handling in Python
Provides an introductory level understanding of the Python Programming Language and language features. Serves as a guide for beginners and a reference to Python basics and language use cases.
Life can be stressful, and joyful, and difficult, and exciting, and negative, depending on how you choose to make it. There are spiritual and psychological factors which may impact one’s overall wellness. Teaching yourself to do a periodic spiritual and psychological inventory of what’s going on with you, in your life, will help gain a greater perspective on how to deal with the challenge’s in life and how to celebrate life’s joys. The aspects of spiritual wellness outlined in the following inventory include, life’s purpose, connections or relationships, forgiveness, love, practice and being present.
Boca Raton Movers providing moving service in South Florida from last 10 years. Our service region includes all of Miami-Dade, Broward, Palm Beach and the nearby areas in the Southern Florida region. Much to your delight, our Boca Raton Movers provides shipping contains, blankets and other wrapping materials for successfully packing your items, as well as custom-made shipping containers for fragile items and electronics.
Finding Our Value in Lower Usage Numbers: An Examination of Reference Servic...Elizabeth Namei
Paper presented at the California Association of Research Libraries Conference, April 2016
Analysis of 2 cases studies - Demand Driven Acquisitions impact on ILL and Self-service reference impact on traditional reference services
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docxpriestmanmable
ISTA 130: Lab 2
1 Turtle Review
Here are all of the turtle functions we have utilized so far in this course:
turtle.forward(distance) – Moves the turtle forward in the direction it is currently facing the distance
entered
turtle.backward(distance) – Same as forward but it moves in the opposite direction the turtle is facing
turtle.right(degrees) – Roates the turtle to the right by the degrees enteres
turtle.left(degrees) – Same as right, but it rotates the turtle to the left
turtle.pensize(size) – Adjusts the size of the line left by the turtle to whatever value is entered for size
turtle.home() – Moves the turtle to the default location and faces it to the right
turtle.clear() – Clears all the lines that were left by the turtle in the window.
turtle.penup() – Causes the turtle to stop leaving lines (until pen is placed back down)
turtle.pendown() – Places the pen back down to the turtle can continue leaving lines when forward and
backward are called.
turtle.pencolor(color string) – Changes the color of the lines left by the turtle to whatever color string
entered (so long as Python recognizes it).
turtle.bgcolor(color string) – Changes the background color for the window that the turtle draws in.
turtle.speed(new speed) – Changes the speed at which the turtle moves to whatever newSpeed is.
turtle.clearscreen() – Deletes all drawings and turtles from the screen, leaving it in its initial state
Note that abbreviations also exist for many of these functions; for example:
� turtle.fd(distance)
� turtle.rt(degrees)
� turtle.pu()
1
2 Functions and Parameters
Here is the square function we looked at yesterday:
def square(side_length):
’’’
Draws a square given a numerical side_length
’’’
turtle.forward(side_length)
turtle.right(90)
turtle.forward(side_length)
turtle.right(90)
turtle.forward(side_length)
turtle.right(90)
turtle.forward(side_length)
turtle.right(90)
return
square(50) # This would give side_length the value of 50
square(100) # This would give side_length the value of 100
print side_length # This will give an error because side_length
# only exists inside the function!
Try it out:
(1 pt.) Create a new file called lab02.py. In this file, create a simple function called rhombus. It
will take one parameter, side length. Using this parameter, have your function create a rhombus
using turtle graphics. Call your rhombus function in the script. What happens if you provide no
arguments to the function? Two or three arguments?
Then, modify your rhombus function so it takes another argument for the angle inside the
rhombus.
3 Data types
Python recognizes many different types of values when working with data. These can be numbers,
strings of characters, or even user defined objects. For the time being, however, were only going to
focus on three of the data types:
integer – These are whole numbers, both positive and negative. Examples are 5000, 0, and -25
float – These are numbers that are followed by a decimal poi ...
learn how to program with python
from scratch to be an expert
use the link in the first slide to get the full course
here is the link if you want : https://oke.io/JdxdUl
the link of the documentation : https://oke.io/J6DeY3
link to download python : https://oke.io/BENgRLR2
The 21P/GIACOBINI-ZINNER COMET - font: WGN, Journal of the International Meteor Organization Wgn26-5.pdf (ver pág. 202)
Link: https://www.imo.net/publications/wgn/ e https://www.imo.net/files/wgn/WGN%201998.zip
1948 - Será uma coincidência ou Obra de Deus?Helio Colombe
Você sabe o que aconteceu no ano 1948 depois de Adão?
Veja e fique impressionado como eu!
Assista o vídeo completo em Youtube: https://youtu.be/jFEA_ycXSBE
www.heliogiroto.com
Por que o arrebatamento da igreja deve ocorrer no ano novo judeu - PortuguêsHelio Colombe
Veja o VIDEO explicativo em: https://www.youtube.com/watch?v=X183jYhf25Q
EN ESPAÑOL - https://goo.gl/p0XAnk
Qual é o dia mais provável do Arrebatamento da Igreja Cristã ??
Entenda por que o arrebatamento pode acontecer no Rosh Roshana
Por que dias 2 ou 3 Outubro de 2016 devemos vigiar muito mais?
Qual é o Calendário de Deus?
Entenda as 7 festas do Calendário Profético de Deus
O verdadeiro percursor do Pentecostalismo baseado nas Escrituras foi este autor! Essa obra é uma relíquia que todos devemos ler sobre o Batismo no Espírito Santo.
Todos os meus agradecimentos ao irmão Alex do Seminário SDC - Brasil.
Adobe Muse - Guia de referencia
Como criar seu primeiro site usando Adobe Muse (sem programar).
Cómo crear su primera página web usando Adobe Muse (sin códigos y sin programar).
LINK DE LA DIAPOSITIVA 31: http://www.jstor.org/stable/3154641?seq=1#page_scan_tab_contents
- Porqué es peligroso invocar el nombre Jehová
- Y porqué tenemos en nuestras Biblias el nombre Jehová.
- Porqué se dice que se perdió la pronunciación
- Desde cuándo existe este nombre
- Cuál es la prueba definitiva que Jesucristo y los apóstoles NUNCA llamaron a Dios de Jehová.
- Porqué sugiero que se retire el nombre Jehová inmediatamente de nuestras Biblias!
- Porqué algunos cristianos usan SEÑOR en vez de Jehová o Yahweh
- Qué Nombre debemos usar
www.heliocolombe.wordpress.com
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
Generating a custom Ruby SDK for your web service or Rails API using Smithyg2nightmarescribd
Have you ever wanted a Ruby client API to communicate with your web service? Smithy is a protocol-agnostic language for defining services and SDKs. Smithy Ruby is an implementation of Smithy that generates a Ruby SDK using a Smithy model. In this talk, we will explore Smithy and Smithy Ruby to learn how to generate custom feature-rich SDKs that can communicate with any web service, such as a Rails JSON API.
Neuro-symbolic is not enough, we need neuro-*semantic*Frank van Harmelen
Neuro-symbolic (NeSy) AI is on the rise. However, simply machine learning on just any symbolic structure is not sufficient to really harvest the gains of NeSy. These will only be gained when the symbolic structures have an actual semantics. I give an operational definition of semantics as “predictable inference”.
All of this illustrated with link prediction over knowledge graphs, but the argument is general.
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
In this insightful webinar, Inflectra explores how artificial intelligence (AI) is transforming software development and testing. Discover how AI-powered tools are revolutionizing every stage of the software development lifecycle (SDLC), from design and prototyping to testing, deployment, and monitoring.
Learn about:
• The Future of Testing: How AI is shifting testing towards verification, analysis, and higher-level skills, while reducing repetitive tasks.
• Test Automation: How AI-powered test case generation, optimization, and self-healing tests are making testing more efficient and effective.
• Visual Testing: Explore the emerging capabilities of AI in visual testing and how it's set to revolutionize UI verification.
• Inflectra's AI Solutions: See demonstrations of Inflectra's cutting-edge AI tools like the ChatGPT plugin and Azure Open AI platform, designed to streamline your testing process.
Whether you're a developer, tester, or QA professional, this webinar will give you valuable insights into how AI is shaping the future of software delivery.
UiPath Test Automation using UiPath Test Suite series, part 3DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 3. In this session, we will cover desktop automation along with UI automation.
Topics covered:
UI automation Introduction,
UI automation Sample
Desktop automation flow
Pradeep Chinnala, Senior Consultant Automation Developer @WonderBotz and UiPath MVP
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
💥 Speed, accuracy, and scaling – discover the superpowers of GenAI in action with UiPath Document Understanding and Communications Mining™:
See how to accelerate model training and optimize model performance with active learning
Learn about the latest enhancements to out-of-the-box document processing – with little to no training required
Get an exclusive demo of the new family of UiPath LLMs – GenAI models specialized for processing different types of documents and messages
This is a hands-on session specifically designed for automation developers and AI enthusiasts seeking to enhance their knowledge in leveraging the latest intelligent document processing capabilities offered by UiPath.
Speakers:
👨🏫 Andras Palfi, Senior Product Manager, UiPath
👩🏫 Lenka Dulovicova, Product Program Manager, UiPath
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
6. >>> 30.5>>>
Integers and Floats
35
35
int
30.5
float
An int is a
whole number
A float is a
decimal number
Here’s a little Python terminology.
7. >>>>>>
Order of Operations
PEMDAS: Parentheses Exponent Multiplication Division Addition Subtraction
These are the calculations happening first.
5 + 7 * 3
26
5 + 21
( 5 + 7 ) * 3
36
12 * 3Behind
the
scenes
8. >>>
Let’s use some math to figure out if this swallow can carry this coconut!
Can a Swallow Carry a Coconut?
So, 1 swallow can carry 20 grams
What we know: A swallow weighs 60g and can carry 1/3 of its weight.
…but a coconut weighs 1450 grams
20
Swallow’s weight in grams Divide by 3
60 / 3
9. >>>
Let’s try to figure out how many swallows it takes to carry 1 coconut.
1450 /
Coconut weight Divide by 3Swallow’s weight
24.17 / 3
That number seems way too low.
Let’s look at what happened behind the scenes:
8.06
1450 / 60 / 3
We wanted 60/3 to happen first — we can add parentheses to fix this.
How Many Swallows Can Carry a Coconut?
60 / 3
What we know: A swallow weighs 60g and can carry 1/3 of its weight.
10. >>>
How many swallows does it take to carry 1 coconut?
Using Correct Order of Operations
1450 /
Coconut weight Divide by 3Swallow’s weight
That’s a lot of swallows!
72.5
1450 / ( 20 )
60 / 3 )(
What we know: A swallow weighs 60g and can carry 1/3 of its weight.
11.
12. >>>
>>>
>>>
Let’s see if we can get closer to 1 swallow with other fruits.
What Other Fruits Can a Swallow Carry?
Great!
We found one that
works!
6.4# swallows per apple: 128 /
0.4# swallows per cherry: 8 /
# swallows per coconut: 1450 / 72.5
Seems like we’re
repeating this a lot
( 60 / 3 )
( 60 / 3 )
( 60 / 3 )
13. >>>
>>>
>>>
Creating a Variable in Python
>>>
Less repeated calculations
More organized
swallow_limit = 60 / 3
# swallows per apple: 6.4
# swallows per cherry: 0.4
# swallows per coconut: 1450 / 72.5
variable name value to store
Use variables to store a value that can be used later in your program.
swallow_limit
swallow_limit
swallow_limit
128 /
8 /
14. >>>
>>>
>>>
Variables keep your code more readable and assign meaning to values.
Using Variables Assigns Meaning
num_per_cherry = 8 / swallow_limit
swallow_limit = 60 / 3
swallows_per_cherry
0.4
swallows_per_cherry =
15. As long as you’re not breaking these rules, you can name variables anything you want!
What Should I Name My Variables?
swallowLimit camel case, later words are capitalized
Pep 8 Style Guide does NOT recommend:
no spaces = 0 no spaces in the name
3mice, $mice no digits or special characters in front
swallow_limit lowercase, use underscores for spaces
Pep 8 Style Guide recommends:
Check Pep 8 style guide here - http://go.codeschool.com/pep8-styleguide
16. Step 1: Declare variables for each value and find out the macaw’s carrying limit.
Can a Macaw Carry a Coconut?
>>>
>>>
>>>
>>>
>>>
300
Notice our variables
are descriptive,
but we’re still using
abbreviations where
appropriate.
coco_wt = 1450
macaw_wt = 900
perc = 1/3
macaw_limit = macaw_wt * perc
macaw_limit
17. Can a Macaw Carry a Coconut?
Step 2: Divide the coconut’s weight by the limit.
4.8
>>> num_macaws
>>> num_macaws = coco_wt/macaw_limit
>>>
>>>
# macaws needed to carry a coconut
>>>
>>>
coco_wt = 1450
macaw_wt = 900
perc = 1/3
macaw_limit = macaw_wt * perc
18. >>>
>>>
>>>
Occasionally, we will want to use modules containing functionality that is not built in to
the Python language.
Importing Modules — Extra Functionality
5
import math
This is importing extra math functions
math.ceil(num_macaws)
num_macaws = 4.8
ceil() is short for ceiling, which rounds up
Check out Python libraries here - http://go.codeschool.com/python-libraries
19. >>>
>>>
>>>
>>>
>>>
>>>
5
coco_wt = 1450
macaw_wt = 900
perc = 1/3
macaw_limit = macaw_wt * perc
num_macaws = coco_wt/macaw_limit
>>>
math.ceil(num_macaws)
import math
Step 3: Use the ceiling function to round up.
Can a Macaw Carry a Coconut?
22. Creating Strings
>>>string
'Hello World'
Strings are a sequence of characters that can store letters, numbers, or a combination — anything!
Create a string with quotes
>>> "SPAM83"
'SPAM83'
Single or double quotes work —
just be consistent
string'Hello World'
23. String Concatenation With +
We can combine (or concatenate) strings by using the + operator.
last_name = 'Python'>>>
'MontyPython'
first_name = 'Monty'>>>
full_name = first_name +>>>
full_name>>>
Need to add a space!
last_name
24. Concatenating a Space
last_name = 'Python'>>>
'Monty Python'
first_name = 'Monty'>>>
full_name = first_name +>>>
full_name>>>
We can
concatenate a
space character
between the words
last_name' ' +
25. Moving Our Code to a Script File
last_name = 'Python'
first_name = 'Monty'
full_name = first_name +
full_name
Each line is entered
on the command line
last_name = 'Python'
first_name = 'Monty'
full_name = first_name + ' ' + last_name
Instead, we can put all lines into a single script file
script.py
But how can we output the value of full_name?
>>>
>>>
>>>
>>>
last_name' ' +
26. Output From Scripts With print()
print full_name
Monty Python
Everything in
1 script: script.py
print(full_name)
Prints whatever is
inside the ()
print(first_name, last_name)
print() as many things as you want,
just separate them with commas
Monty Python
last_name = 'Python'
first_name = 'Monty'
full_name = first_name + ' ' + last_name
print() automatically adds spaces
between arguments
In Python 2,
print doesn’t need ()
27. >>>
Running a Python Script
python script.py
This is the command to run Python
scripts
Monty Python
Put the name of your script file here
script.py
print(full_name)
last_name = 'Python'
first_name = 'Monty'
full_name = first_name + ' ' + last_name
29. script.py
Comments Describe What We’re Doing
Let’s write a script to describe what Monty Python is.
#means this line is a comment anddoesn’t get run
1969
name = 'Monty Python'
description = 'sketch comedy group'
# Describe the sketch comedy group
year =
30. Concatenating Strings and Ints
When we try to concatenate an int, year, with a string, we get an error.
script.py
TypeError: Can't convert 'int' object to str implicitly
Year is an int,
not a string
# Introduce them
1969
name = 'Monty Python'
description = 'sketch comedy group'
year =
# Describe the sketch comedy group
is a' description formed in yearsentence = name + '+ ' ++ '
31. Concatenating Strings and Ints
script.py
We could add quotes
and make the year a
string instead of an int
This will work, but it really makes sense to keep numbers as numbers.
'1969'
# Introduce them
name = 'Monty Python'
description = 'sketch comedy group'
year =
# Describe the sketch comedy group
is a' description formed in yearsentence = name + '+ ' ++ '
32. Turning an Int Into a String
script.py
Monty Python is a sketch comedy group formed in 1969
Instead, convert
the int to a string
when we
concatenate
with str()
print(sentence)
is a
# Introduce them
' description formed in yearstr( )sentence = name + '+ ' ++ '
name = 'Monty Python'
description = 'sketch comedy group'
year =
# Describe the sketch comedy group
1969
33. print() Casts to String Automatically
script.py
print() does string
conversions for us
Monty Python is a sketch comedy group formed in 1969
1969
# Introduce them
print( , , , , )is a description formed in year'name ' ' '
name = 'Monty Python'
description = 'sketch comedy group'
year =
# Describe the sketch comedy group
1969
34. Dealing With Quotes in Strings
# Describe Monty Python's work
famous_sketch = 'Hell's Grannies'
script.py
Syntax Error: invalid syntax
Interpreter thinks the
quote has ended and
doesn’t know what S is
# Describe Monty Python's work
famous_sketch1 = "Hell's Grannies"
script.py
Hell's Grannies
Start with '' instead —
now the ' no longer means
the end of the string
''
'
)print(famous_sketch1
35. # Describe Monty Python's work
famous_sketch1 = "
Hell's Grannies The Dead Parrot
script.py
Special Characters for Formatting
We want to add some more sketches and print them out
This works, but we want to format it better.
Let’s add another
famous sketch
)
famous_sketch2 = '
print( , famous_sketch2
Hell's Grannies"
The Dead Parrot'
famous_sketch1
36. # Describe Monty Python's work
famous_sketch1 = "
script.py
Special Characters — Newline
Add a newline
to make this look better
n is a special character that means new line.
This works, but we want to indent the titles.
Famous Work:
Hell's Grannies
The Dead Parrot
n
nThe Dead Parrot'
Hell's Grannies"
famous_sketch2 = '
print('Famous Work:', famous_sketch1, famous_sketch2)
37. Famous Work:
Hell's Grannies
The Dead Parrot
Special Characters — Tab
# Describe Monty Python's work
famous_sketch1 = "
script.py
Add a tab to indent and
make this look even
better
t is a special character that means tab.
n
n The Dead Parrot'
Hell's Grannies"
famous_sketch2 = '
print('Famous Work:', famous_sketch1, famous_sketch2)
t
t
38.
39. >>>
>>>
Strings Behind the Scenes — a List of Characters
greeting =
>>> greeting[0] 'H'
greeting[11] '!'
A string is a list of characters, and each character in this list has a position or an index.
We can get each character by
calling its index with []
greeting[12] IndexError: string index out of range
Starts at 0
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10][11]
'H E L L O W O R L D !'
40. 'H E L L O W O R L D !'
There are a few built-in string functions — like len(), which returns the length of a string and is very useful.
# print the length of greeting
greeting = 'HELLO WORLD!'
print( len(greeting) )
script.py
12
[0] [1] [2] [3] [4] [5] [6] [7] [8][9][10][11]
12
String Built-in Function — len()
41. word1 = 'Good'
end1 = word1[2] + word1[3]
print(end1)
script.py
The last half of the word:
characters at positions
[2] and [3]
'G o o d'
[0] [1] [2] [3]
'E v e n i n g'
[0] [1] [2] [3] [4] [5] [6]
Good Evening
od
od ning
The Man Who Only Says Ends of Words
42. >>>
word = "P y t h o n"
[0] [1] [2] [3] [4] [5]
word[2:5] tho
Boundary
starts before
index 2
Boundary
ends before
index 5
Start
boundary
End
boundary
Using Slices to Access Parts of a String
43. >>>>>>
>>>>>>
o d
Slice Formula and Shortcuts
word1 ='G o o d'
[0] [1] [2] [3]
word1[0:2] G o
slice formula: variable [start : end+1]
word1[2:4] G oo d
Shortcuts:
word1[:2] G o
Means from start to position
[0] [1] [2] [3]
word1 ='G o o d'
word1[2:]
Means from position to end
Good
Go
Good
od
44. 'G o o d'
word1 = 'Good'
end1 =
script.py
[0] [1] [2] [3]
'E v e n i n g'
[0] [1] [2] [3] [4] [5] [6]
Replace this with a slice
word1[2:4]
od
Good
od
Incorporating String Slices Into Our Solution
print(end1)
word1[3]+word1[2]
45. Using the String Slice Shortcut
'G o o d'
word1 = 'Good'
end1 = word1[2:]
script.py
[0] [1] [2] [3]
'E v e n i n g'
[0] [1] [2] [3] [4] [5] [6]
print(end1, end2)
word2 = 'Evening'
end2 = word2[3:]
Improved this with a
shortcut
od ning
It would be great if we didn’t have to know the halfway points were at 2 and 3…
Good Evening
od ning
46. The Index at the Halfway Point
The len() function will let us calculate the halfway index of our word.
'G o o d'
[0] [1] [2] [3]
'E v e n i n g'
[0] [1] [2] [3] [4] [5] [6]
script.py
# Calculate the halfway index
half1 = len(word1)/
half2 = len(word2)/
PROBLEM: indexes have to be
integers — floats won’t work!
half1 is 2.0
half2 is 3.5
Good Evening
od ning
word2 = 'Evening'
2
2
word1 = 'Good'
47. The Index at the Halfway Point
// 2 division signs means integer division in Python.
'G o o d'
[0] [1] [2] [3]
'E v e n i n g'
[0] [1] [2] [3] [4] [5] [6]
script.py
// Also rounds down to the
nearest integer
half1 is
4//2 = 2
half2 is
7//2 = 3
// Means integer division
Integer division vs floor
division. Be consistent if
we cover in Level 1.
In Python 2,
single division /
is int division unless
there are floats involved
# Calculate the halfway index
half1 = len(word1)/
half2 = len(word2)/
word2 = 'Evening'
2
2
/
/
word1 = 'Good'
48. Making Our Program More Reusable
Calculating the halfway index makes our logic reusable.
od ning
word2[half2:]
script.py
word1[half1:]
'G o o d'
[0] [1] [2] [3]
'E v e n i n g'
[0] [1] [2] [3] [4] [5] [6]
half1 is
4//2 = 2
half2 is
7//2 = 3
Good Evening
od ning
half1 = len(word1)/ 2/
word1 = 'Good'
end1 = word1[2:]
half2 = len(word2)/
word2 = 'Evening'
2/
end2 = word2[3:]
print(end1, end2)
51. Extended Battle Rules
if there's more than 10 knights
Trojan Rabbit!
otherwise
if there's less than 3 knights
Retreat!
52. >>>
>>>
>>>
>>>
>>>
There are 6 comparators in Python:
Comparison Operators
<
less than
<=
less than
equal to
==
equal to
!=
not
equal to
>=
greater than
equal to
>
greater than
True5 < 10
Is 5 less than 10 ??
5 == 10
Is 5 equal to 10 ??
False
name = 'Pam'
Is name equal to Jim ??
name == 'Jim'
name != 'Jim'
Is name NOT equal to Jim ??
True
False
Setting the name variable
equal to 'Pam'
54. >>>
>>>
In programming, a boolean is a type that can only be True or False.
Booleans
True booleans
is_raining = True
is_raining
True
False
Capital T and Capital F
55. script.py
Conditional — if, then
# Battle Rules
num_knights =
Then do this
Then this
Retreat!
Raise the white flag!
An if statement lets us decide what to do: if True, then do this.
If True:True
Any indented code that
comes after an if
statement is called a
code block
2
print('Retreat!')
print('Raise the white flag!')
if num_knights < 3:
56. script.py
Conditional — if, then
# Battle Rules
num_knights =
False
Because the
conditional is False,
this block doesn’t run
Nothing happens…
*crickets*
An if statement lets us decide what to do: if False, then don’t do this.
4
print('Retreat!')
print('Raise the white flag!')
if num_knights < 3:
57. script.py
The code continues to run as usual, line by line, after the conditional block.
The Program Continues After the Conditional
Knights of the Round Table!
# Battle Rules
num_knights =
Always this
This block doesn’t run,
but the code right
outside of the block
still does
False
4
print('Knights of the Round Table!')
print('Retreat!')
print('Raise the white flag!')
if num_knights < 3:
58. In Python, indent with 4 spaces. However, anything will work as long as you’re consistent.
Rules for Whitespace in Python
if num_knights == 1:
# Block start
print('Do this')
print('And this')
print('Always this')
IndentationError: unexpected indent
2 spaces
4 spaces
Irregular spacing is
a no-no!
The PEP 8 style guide recommends 4 spaces - http://go.codeschool.com/pep8-styleguide
60. Conditional — if False else
script.py
# Battle Rules
num_knights = 4
if num_knights < 3:
print('Retreat!')
else:
print('Truce?')
Truce?
If this statement is True,
then run the indented code below
Otherwise,
then run the indented code below
61.
62. Conditionals — How to Check Another Condition?
script.py
Truce?
Otherwise if at least 10,
then Trojan Rabbit
X
else:
print('Truce?')
if num_knights < 3:
print('Retreat!')
# Battle Rules
num_knights = 10
63. elif Allows Checking Alternatives
Else sequences
will exit
as soon as a
statement is True…
…and continue
the program after
script.py
# Battle Rules
num_knights = 10
Trojan Rabbit
else:
print('Truce?')
elif num_knights >= 10:
print('Trojan Rabbit')
elif means otherwise if
elif day == 'Tuesday':
print('Taco Night')
We can have multiple elifs
if num_knights < 3:
print('Retreat!')
day = 'Wednesday'
64. King Arthur has decided:
Combining Conditionals With and/or
if num_knights < 3:
print('Retreat!')
if num_knights >= 10:
print('Trojan Rabbit!')
On all Mondays, we retreat
We can only use the Trojan Rabbit on Wednesday
(we’re renting it out on other days)
OR
if it’s a Monday
Retreat!
AND
it’s Wednesday
Trojan Rabbit!
65. if num_knights < 3 or day == "Monday":
print('Retreat!')
On all Mondays, or if we have less than 3 knights, we retreat.
Putting or in Our Program
If we have less than 3 knights OR If it’s a Monday Spelled out Monday, and
Wednesday on the next
slide.
66. if num_knights >= 10 and day == "Wednesday":
print('Trojan Rabbit!')
We can only use the Trojan Rabbit if we have at least 10 knights AND it’s Wednesday.
Putting and in Our Program
If we have at least 10 knights AND If it’s a Wednesday
67. Make it possible to combine comparisons or booleans.
Boolean Operators — and / or
True False
True
False
True
False
True
True
False
If 1 is True
or result will be True
True False
True
False
True
False
True
False
False
If 1 is False
and result will be False
and
and
and
or
or
or
68. script.py
Incorporating the Days of the Week
Checking day of the week
# Battle Rules
num_knights = 10
day = 'Wednesday'
if num_knights < 3 or day == 'Monday':
print('Retreat!')
elif num_knights >= 10 and day == 'Wednesday':
print('Trojan Rabbit!')
else:
print('Truce?')
69. User Input — With the input() Function
script.py
# Ask the user to input the day of the week
day = input('Enter the day of the week')
print('You entered:', day)
prints out this statement
and waits for user input
day saves the user's input
In Python 2,
raw_input() is used
instead of input()
70. Receiving User Input From Console
Just like we can print() text to the console, we can also get user input from the console.
script.py
User enters #, but it comes in as textChange (or cast) the string to an int
Enter the number of knights
You entered: 10
10
User enters 10
if num_knights < 3 or day == 'Monday':
print('Retreat!')
num_knights = int(input('Enter the number of knights'))
print('You entered:', num_knights)
# Ask the user to input the number of knights
71. Different Input and Conditionals Changes Output
script.py
# Battle Rules
num_knights = int(input('How many knights?'))
day = input('What day is it?'))
if num_knights < 3 or day == 'Monday':
print('Retreat!')
elif num_knights >= 10 and day == 'Wednesday':
print('Trojan Rabbit!')
else:
print('Truce?')
How many knights?
Retreat
2
What day is it? Tuesday
2How many knights?
Trojan Rabbit!
12
What day is it? Wednesday
Different user input
causes different
program flow:
1st run
2nd run
1st run 2nd run
73. script.py
Nested Conditionals — Ask Follow-up Questions
if num_knights < 3 or day == 'Monday':
print('Retreat!')
if num_knights >= 10 and day == 'Wednesday':
print('Trojan Rabbit!')
else:
print('Truce?')
# Original Battle Rules
First, find out if our enemy
is the killer bunny
If not,
then use the
original battle rules
Do the original battle rules here
# Battle Rules
num_knights = int(input('Enter number of knights')
day = input('Enter day of the week')
enemy = input('Enter type of enemy')
else:
if enemy == 'killer bunny':
print('Holy Hand Grenade!')
74. Nested Conditionals
script.py
Our final
Rules of Engagement
# Battle Rules
num_knights = int(input('Enter number of knights')
day = input('Enter day of the week')
enemy = input('Enter type of enemy')
else:
if num_knights < 3 or day == 'Monday':
print('Retreat!')
if num_knights >= 10 and day == 'Wednesday':
print('Trojan Rabbit!')
else:
print('Truce?')
# Original Battle Rules
if enemy == 'killer bunny':
print('Holy Hand Grenade!')