0% found this document useful (0 votes)
2 views

5_6149975860259591061

The document is a lecture outline on programming for data science, focusing on Python variables and simple data types. It covers topics such as naming variables, using strings, handling whitespace, and performing basic arithmetic operations. The lecture also addresses common errors and best practices in Python programming.

Uploaded by

Tausif Ahmed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

5_6149975860259591061

The document is a lecture outline on programming for data science, focusing on Python variables and simple data types. It covers topics such as naming variables, using strings, handling whitespace, and performing basic arithmetic operations. The lecture also addresses common errors and best practices in Python programming.

Uploaded by

Tausif Ahmed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

DS 1501: Programming for Data Science

Lecture 02: Variables and Simple Data types

Dr. Md Saddam Hossain Mukta


Associate Professor & Undergraduate Program
Coordinator
Department of CSE, UIU
Email: [email protected]
Outlines
● Python variables
● Naming a variable
● String
● Whitespace
● Error with string
● Numbers
Running a hello_world.py
● print("Hello Python world!")

● When you run the file hello_world.py, the ending .py indicates
that the file is a Python program.

● Your editor then runs the file through the Python interpreter

● When the interpreter sees the word print, it prints to the


screen whatever is inside the parentheses
Variables
■ Let’s try using a variable

message = "Hello Python world!"

print(message)

● Hello Python world!


● We’ve added a variable named message. Every variable holds a value, which is the
information associated with that variable.
● Adding a variable makes a little more work for the Python interpreter.
● When it processes the first line, it associates the text “Hello Python world!”
● When it reaches the second line, it prints the value associated with message to the
screen.
Variables (contd.)
message = "Hello Python world!"

print(message)

message = "Hello Python Crash Course world!"

print(message)

Hello Python world!

Hello Python Crash Course world!

You can change the value of a variable in your program at any time, and Python will always keep
track of its current value.
Naming and Using Variables
● Variable names can contain only letters, numbers, and underscores. For instance,
you can call a variable message_1 but not 1_message.
● Spaces are not allowed in variable names, but underscores can be used to separate
words in variable names.
● greeting_message works, but greeting message will cause errors.
● Avoid using Python keywords and function names as variable names such as def,
else, elif, continue, etc.
● Variable names should be short but descriptive. For example, name is better than n,
student_name is better than s_n, and name_length is better than
length_of_persons_name
Name Errors When Using Variables
● We’ll write some code that generates an error on purpose.

message = "Hello Python Crash Course reader!"

print(mesage)

● The interpreter provides a traceback when a program cannot run successfully. A


traceback is a record of where the interpreter ran into trouble when trying to execute
your code.
An error occurs in line 2 of the file
Traceback (most recent call last): Hello_world.py

File "hello_world.py", line 2, in <module> The interpreter shows this line to help us spot
print(mesage) the error quickly

NameError: name 'mesage' is not defined tells us what kind of error it found
Strings
● A string is simply a series of characters. Anything inside quotes is considered a string
in Python, and you can use single or double quotes around your strings like this

"This is a string."
'This is also a string.'
● This flexibility allows you to use quotes and apostrophes within your strings:

message="I like jack's preference"


msg='He told- "I am fine"'
Changing Case in a String with Methods
● You can do with strings is change the case of the words in a string.
name = "ada lovelace"
print(name.title())

Ada Lovelace

● The method title() appears after the variable in the print() statement.
● A method is an action that Python can perform on a piece of data. The dot (.) after
name in name.title() tells Python to make the title() method act on the variable name.
● Every method is followed by a set of parentheses, because methods often need
additional information to do their work.
● The title() function doesn’t need any additional information, so its parentheses are
empty.
Changing Case in a String with Methods
name ="Ada Lovelace"
print(name.upper())
print(name.lower())

ADA LOVELACE
ada lovelace

● The lower() method is particularly useful for storing data.


● Many times you convert strings to lowercase before storing them.
Combining or Concatenating Strings
● It’s often useful to combine strings.
● For example, you might want to store a first name and a last name in separate
variables, and then combine them when you want to display someone’s full name:
first_name = "ada"
last_name = "lovelace"
full_name = first_name + " " + last_name
print(full_name)
● Python uses the plus symbol (+) to combine strings
● Output is:
ada lovelace
● You can use concatenation to compose complete messages
print("Hello, " + full_name.title() + "!")

Hello, Ada Lovelace!


Combining or Concatenating Strings
● You can use concatenation to compose a message and then store the entire
message in a variable:
first_name = "ada"
last_name = "lovelace"
full_name = first_name + " " + last_name
message = "Hello, " + full_name.title() + "!"
print(message)
Adding Whitespace to Strings with Tabs or Newlines
● whitespace refers to any nonprinting character
● For example, spaces, tabs, and end-of-line symbols
print("Languages:\nPython\nC\nJavaScript")
Languages:
Python
C
JavaScript

print("Languages:\n\tPython\n\tC\n\tJavaScript")
Languages:
Python
C
JavaScript
Stripping Whitespace
● Extra whitespace can be confusing in your programs. To programmers 'python' and
'python ' look pretty much the same.
● But to a program, they are two different strings. Python detects the extra space in
'python ' and considers it significant unless you tell it otherwise.
● It’s important to think about whitespace, because often you’ll want to compare two
strings to determine whether they are the same.
● For example, one important instance might involve checking people’s usernames
when they log in to a website.
● Fortunately, Python makes it easy to eliminate extraneous whitespace from data that
people enter.
Stripping Whitespace
● Python can look for extra whitespace on the right and left sides of a string. To ensure
that no whitespace exists at the right end of a string, use the rstrip() method.
favorite_language = 'python '
print(favorite_language.rstrip())
● you can see the space at the end of the value v. When the rstrip() method acts on
the variable favorite_language, this extra space is removed. But it is a temporary
solution.
● To remove the whitespace from the string permanently, you have to store the
stripped value back into the variable:
>>>favorite_language = 'python '
>>>favorite_language = favorite_language.rstrip()
>>>favorite_language
'python'
Stripping Whitespace
● You can also strip whitespace from the left side of a string using the lstrip() method
or strip whitespace from both sides at once using strip():
>>> favorite_language = ' python '
>>> favorite_language.rstrip()
' python'
>>> favorite_language.lstrip()
'python '
>>> favorite_language.strip()
'python'

● Experimenting with these stripping functions can help you become familiar with
manipulating strings.
● In the real world, these stripping functions are used most often to clean up user input
before it’s stored in a program.
Syntax Errors with Strings
● A syntax error occurs when Python doesn’t recognize a section of your program as
valid Python code.
● If you use an apostrophe within single quotes, you’ll produce an error.
message = 'One of Python's strengths is its diverse community.'
print(message)

File "apostrophe.py", line 1


message = 'One of Python's strengths is its diverse community.'
^
SyntaxError: invalid syntax

● Experimenting with these stripping functions can help you become familiar with
manipulating strings.
● In the real world, these stripping functions are used most often to clean up user input
before it’s stored in a program.
Numbers (i.e., Integers)
● Numbers are used quite often in programming to keep score in games, represent
data in visualizations, store information in web applications
● You can add (+), subtract (-), multiply (*), and divide (/) integers in Python.
>>> 2 + 3
5
>>> 3 - 2
1
>>> 2 * 3
6
>>> 3 / 2
1.5
● Python uses two multiplication symbols to represent exponents
>>> 3 ** 2
9
>>> 3 ** 3
27
Operator Precedence
● Python supports the order of operations too, so you can use multiple operations in
one expression.
● You can also use parentheses to modify the order of operations so Python can
evaluate your expression in the order you specify.

>>> 2 + 3*4
14
>>> (2 + 3) * 4
20
Floats
● Python calls any number with a decimal point a float. This term is used in most
programming languages, and it refers to the fact that a decimal point can appear at
any position in a number.
>>> 0.1 + 0.1
0.2
>>> 2 * 0.1
0.2
● But be aware that you can sometimes get an arbitrary number of decimal places in
your answer:
>>> 0.2 + 0.1
0.30000000000000004
Errors with the str() Function
● Sometimes you will want to use a variable’s value within a message

age = 23
message = "Happy " + age + "rd Birthday!"
print(message)

● But if you run this code, you’ll see that it generates an error

Traceback (most recent call last):


File "birthday.py", line 2, in <module>
message = "Happy " + age + "rd Birthday!"
u TypeError: Can't convert 'int' object to str implicitly

● This is a type error. It means Python can’t recognize the kind of information you’re
using.
Errors with the str() Function
● When you use integers within strings like this, you need to specify explicitly that you
want Python to use the integer as a string of characters.

age = 23
message = "Happy " + str(age) + "rd Birthday!"
print(message)
Integers in Python 2
● Python 2 returns a slightly different result when you divide two integers:

>>> python2.7
>>> 3 / 2
1

● Instead of 1.5, Python returns 1. Division of integers in Python 2 results in an integer


with the remainder truncated. Note that the result is not a rounded integer; the
remainder is simply omitted.
● To avoid this behavior in Python 2, make sure that at least one of the numbers is a
float

>>> 3.0 / 2
1.5
Comments
● Comments are an extremely useful feature in most programming languages.
● As your programs become longer and more complicated, you should add notes
within your programs that describe your overall approach to the problem you’re
solving.
● A comment allows you to write notes in English within your programs.
● The hash mark (#) indicates a comment
# Say hello to everyone.
print("Hello Python people!")

● Python ignores the first line and executes the second line.

Hello Python people!


Thank you

You might also like