0% found this document useful (0 votes)
9 views15 pages

Lesson2 - Python Variables - CBSE

The document provides an overview of variables in Python, including their purpose, naming rules, and common errors such as NameError. It explains how to assign, change, and delete variable values, as well as introduces data types like strings, integers, and floats. Additionally, it covers string methods, formatting, and exercises to reinforce learning.

Uploaded by

Atharv Kulkarni
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)
9 views15 pages

Lesson2 - Python Variables - CBSE

The document provides an overview of variables in Python, including their purpose, naming rules, and common errors such as NameError. It explains how to assign, change, and delete variable values, as well as introduces data types like strings, integers, and floats. Additionally, it covers string methods, formatting, and exercises to reinforce learning.

Uploaded by

Atharv Kulkarni
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/ 15

Variables

Variables are also used to store the data types like string, integer, and float values.

Example

message1 = 'Hello python world'


message2 = "Hello python world"
message3 = """Hello python world"""
message4 = 100
print(message1)
print(message2)
print(message3)
print(message4)

Hello python world


Hello python world
Hello python world
100.1

A variable holds a value. You can change the value of a variable at any point.

Naming rules

Variables name can only contain letters, numbers, and underscores.

Variable names can start with a letter or an underscore, but can not start with a number.

Spaces are not allowed in variable names, so we use underscores instead of spaces. For example, use student_name instead of "student
name".

You cannot use Python keywords as variable names.

Variable names should be descriptive, without being too long. For example mc_wheels is better than just "wheels", and
number_of_wheels_on_a_motorycle.

Variable names are case-sensitive (Ram, ram and RAM are three different variables)

#Legal variable names:


myvar = "hackers"
my_var = "hackers"
_my_var = "hackers"
myVar = "hackers"
MYVAR = "hackers"
myvar2 = "hackers"

#Illegal variable names:


2myvar = "hackers"
my-var = "hackers"
my var = "hackers"

NameError
There is one common error when using variables, that you will almost certainly encounter at some point. Take a look at this code, and see if
you can figure out why it causes an error.

# my variable name is message and not messages


message = "Thank you for sharing Python with the world, Guido!"
print(messages)

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-2-11ab9aca3b0e> in <module>
1 message = "Thank you for sharing Python with the world, Guido!"
----> 2 print(messages)

NameError: name 'messages' is not defined

Let's look through this error message. First, we see it is a NameError. Then we see the file that caused the error, and a green arrow shows us
what line in that file caused the error. Then we get some more specific feedback, that "name 'mesage' is not defined".

You may have already spotted the source of the error. We spelled message two different ways. Python does not care whether we use the
variable name "message" or "mesage". Python only cares that the spellings of our variable names match every time we use them.

This is pretty important, because it allows us to have a variable "name" with a single name in it, and then another variable "names" with a
bunch of names in it.

We can fix NameErrors by making sure all of our variable names are spelled consistently.

#Assigning a value to a variable


message_for_kids = "preparing young minds for future with AI"
print(message_for_kids)

preparing young minds for future with AI

#Changing value of a variable


message_for_kids = "preparing young minds for future with AI"
print(message_for_kids)
message_for_kids = 100
print(message_for_kids)

preparing young minds for future with AI


India joined GPAI 2020

# Assigning different values to different variables in single line


a,b,c = 5,2.6,"Hello"
print(a)
print(type(a))
print(b)
print(type(b))
print(c)
print(type(c))

5
<class 'int'>
2.6
<class 'float'>
Hello
<class 'str'>

# Assigning same value to different variable


x=y=z="Same"
print(x)
print(y)
print(z)

Same
Same
Same

# deleting a variable
num = 12
print(num)
del num
print(num)

12

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-9-4d92581f8e3d> in <module>
3 print(num)
4 del num
----> 5 print(num)

NameError: name 'num' is not defined

# variable type
# variable type
# string type variable
# integer type variable
# float type variable

var = "hello world"


var1 = 45
var2 = 5.009
var = "a"

#boolean variable type


python = True
java = False

Exercises

Hello World - variable

Store your own version of the message "Hello World" in a variable, and print it.

One Variable, Two Messages:

Store a message in a variable, and then print that message.

Store a new message in the same variable, and then print that new message.

# Ex 2.1 : Hello World - Variable

# put your code here

# Ex 2.2 : One Variable, Two Messages

# put your code here

Sequence
A sequence is an ordered collection of items, indexed by positive integers. It is a combination of mutable and non-mutable data types. Three
types of sequence data type available in Python are:

a) Strings

b) Lists

c) Tuples

Introduction to strings
String is an ordered sequence of letters/characters.
They are enclosed in single quotes (‘ ‘) or double (“ “).

The quotes are not part of string.

They only tell the computer where the string constant begins and ends.

They can have any character or sign, including space in them.

my_string = "This is a double-quoted string."


my_string = 'This is a single-quoted string.'

This lets us make strings that contain quotations.

quote = "Linus Torvalds once said, /'Any program is only as good as it is useful.'"
print(quote)

Linus Torvalds once said, /'Any program is only as good as it is useful.'

Multiline Strings
In case we need to create a multiline string, there is the triple-quote to the rescue: '''

multiline_string = '''This is a string where I


can confortably write on multiple lines
without worring about to use the escape character "\\" as in
the previsou example.
As you'll see, the original string formatting is preserved.
'''

print(multiline_string)

This is a string where I


can confortably write on multiple lines
without worring about to use the escape character "\" as in
the previsou example.
As you'll see, the original string formatting is preserved.

multiline_string = """This is a string where I


can confortably write on multiple lines
without worring about to use the escape character "\\" as in
the previsou example.
As you'll see, the original string formatting is preserved."""

print(multiline_string)

This is a string where I


can confortably write on multiple lines
without worring about to use the escape character "\" as in
the previsou example.
As you'll see, the original string formatting is preserved.

txt = "We are the so-called "Vikings" from the north."


print(txt)

File "<ipython-input-76-485014d8dfdf>", line 1


txt = "We are the so-called "Vikings" from the north."
^
SyntaxError: invalid syntax

txt = "We are the so-called \"Vikings\" from the north."


print(txt)

We are the so-called "Vikings" from the north.

Strings are Arrays


Strings are Arrays

Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters.

However, Python does not have a character data type, a single character is simply a string with a length of 1.

Square brackets can be used to access elements of the string.

a = "Hello, World!"
print(a[1])

b = "Hello, World!"
print(b[2:5])

a = "Hello, World!"
print(len(a))

String Methods

Changing case

You can easily change the case of a string, to present it the way you want it to look.

first_name = 'eric'

print(first_name)
print(first_name.title())

eric
Eric

It is often good to store data in lower case, and then change the case as you want to for presentation. This catches some TYpos. It also
makes sure that 'eric', 'Eric', and 'ERIC' are not considered three different people.

Some of the most common cases are lower, title, and upper.

first_name = 'eric'

print(first_name)
print(first_name.title())
print(first_name.upper())

first_name_titled = 'Eric'
print(first_name_titled.lower())

eric
Eric
ERIC
eric

Note: Please notice that the original strings remain always unchanged

You will see this syntax quite often, where a variable name is followed by a dot and then the name of an action, followed by a set of
parentheses. The parentheses may be empty, or they may contain some values.

variable_name.action()

In this example, the word "action" is the name of a method.

A method is something that can be done to a variable.

The methods lower, title, and upper are all functions that have been written into the Python language, which do something to strings.

Later on, you will learn to write your own methods.

replace method
#replace() method replaces a string with another string:

a = "Hello, World!"
print(a.replace("H", "J"))

Jello, World!

split method

#split() method splits the string into substrings if it finds instances of the separator:

a = "Hello, World, How are you guys?!"


print(a.split(",")) # returns ['Hello', ' World!']

['Hello', ' World', ' How are you guys?!']

Check String

#To check if a certain phrase or character is present in a string, we can use the keywords in or not in.
#Check if the phrase "ain" is present in the following text:

txt = "The national educational policy 2020 is awaited one!!!"


x = "nal" in txt
print(x)

True

txt = "The national educational policy 2020 is awaited one!!!"


x = "nal" not in txt
print(x)

False

String Concatenation

#To concatenate, or combine, two strings you can use the + operator.
a = "Hello"
b = "World"
c = a + b
print(c)

#To add a space between them, add a " "


a = "Hello"
b = "World"
c = a + " " + b
print(c)

string formatting

# we cannot combine strings and numbers like this:


age = 36
txt = "My name is John, I am " + age
print(txt)

But we can combine strings and numbers by using the format() method!

The format() method takes the passed arguments, formats them, and places them in the string where the placeholders {} are.

age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))
print(type(txt))

My name is John, and I am 36


<class 'str'>

quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))

---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-75-028a26256fd8> in <module>
1 myorder = "I want {} pieces of item {} for {} dollars."
----> 2 print(myorder.format(quantity=2, itemno=3, price=5))
3

IndexError: tuple index out of range

string_name = 'The result of the calculation of {calc} is {res}'

print("String name: ", string_name)

print(string_name.format(calc='(3*4)+2', res=(3*4)+2))

String name: The result of the calculation of {calc} is {res}


The result of the calculation of (3*4)+2 is 14

strip method

The term "whitespace" refers to characters that the computer is aware of, but are invisible to readers. The most common whitespace
characters are spaces, tabs, and newlines.

Spaces are easy to create, because you have been using them as long as you have been using computers. Tabs and newlines are
represented by special character combinations.

The two-character combination "\t" makes a tab appear in a string. Tabs can be used anywhere you like in a string.

print("Hello everyone!")

Hello everyone!

print("\tHello everyone!")

Hello everyone!

print("Hello \teveryone!")

The combination "\n" makes a newline appear in a string. You can use newlines anywhere you like in a string.

print("Hello everyone!")

print("\nHello everyone!")

print("Hello \neveryone!")

print("\n\n\nHello everyone!")

Stripping whitespace

Many times you will allow users to enter text into a box, and then you will read that text and use it. It is really easy for people to include extra
whitespace at the beginning or end of their text. Whitespace includes spaces, tabs, and newlines.
It is often a good idea to strip this whitespace from strings before you start working with them. For example, you might want to let people log
in, and you probably want to treat 'eric ' as 'eric' when you are trying to see if I exist on your system.

You can strip whitespace from the left side, the right side, or both sides of a string.

name = ' eric '

print(name.lstrip())
print(name.rstrip())
print(name.strip())

eric
eric
eric

It's hard to see exactly what is happening, so maybe the following will make it a little more clear:

name = ' eric '

print('-' + name.lstrip() + '-')


print('-' + name.rstrip() + '-')
print('-' + name.strip() + '-')

-eric -
- eric-
-eric-

Exercises

Someone Said

Find a quote that you like. Store the quote in a variable, with an appropriate introduction such as "Ken Thompson once said, 'One of my most
productive days was throwing away 1000 lines of code'". First Name Cases

First Name Cases

Store your first name, in lowercase, in a variable.

Using that one variable, print your name in lowercase, Titlecase, and UPPERCASE.

Full name

Store your first name and last name in separate variables, and then combine them to print out your full name.

About This Person

Choose a person you look up to. Store their first and last names in separate variables.

Use concatenation to make a sentence about this person, and store that sentence in a variable.

Print the sentence.

Name strip

Store your first name in a variable, but include at least two kinds of whitespace on each side of your name.

Print your name as it is stored.

Print your name with whitespace stripped from the left side, then from the right side, then from both sides.

# Ex 2.3 : Someone Said

# put your code here

# Ex 2.4 : First Name Cases


# put your code here

# Ex 2.5 : Full Name

# put your code here

# Ex 2.6 : About This Person

# put your code here

# Ex 2.7 : Name Strip

# put your code here

Numbers
Number data type stores Numerical Values. These are of three different types:

a) Integer & Long

b) Float / floating point

c) complex numbers

x = 1 # integer

y = 2.8 # float

z = 1j # complex

Integers
Range of an integer in Python can be from -2147483648 to +2147483647, and long integer has unlimited range subject to available memory.

Integers are the whole numbers consisting of + or – sign with decimal digits like 100000, -99, 0, 17.

While writing a large integer value, don’t use commas to separate digits.

Also, integers should not have leading zeros.

x = 1
y = 35656222554887711
z = -3255522

print(3+2)
a=-90000
print(type(a))

5
<class 'int'>

print(3-2)

print(3*2)

print(3/2)

1.5

print(3**2)

You can use parenthesis to modify the standard order of operations.

standard_order = 2+3*4
standard_order = 2+3*4
print(standard_order)

my_order = (2+3)*4
print(my_order)

Floating-Point numbers
Numbers with fractions or decimal point are called floating point numbers.

A floating-point number will consist of sign (+,-) sequence of decimals digits and a dot such as 0.0, -21.9, 0.98333328, 15.2963

x = 1.10
y = 1.0
z = -35.59

x = 35e3
y = 12E4
z = -87.7e100

print(0.1+0.1)

0.2

However, sometimes you will get an answer with an unexpectly long decimal part:

print(0.1+0.2)

0.30000000000000004

This happens because of the way computers represent numbers internally; this has nothing to do with Python itself. Basically, we are used to
working in powers of ten, where one tenth plus two tenths is just three tenths. But computers work in powers of two. So your computer has to
represent 0.1 in a power of two, and then 0.2 as a power of two, and express their sum as a power of two. There is no exact representation
for 0.3 in powers of two, and we see that in the answer to 0.1+0.2.

Python tries to hide this kind of stuff when possible. Don't worry about it much for now; just don't be surprised by it, and know that we will
learn to clean up our results a little later on.

You can also get the same kind of result with other operations.

print(3*0.1)

0.30000000000000004

# Test
3 * 0.1 == 0.3

False

#-2.0 x 105 will be represented as -2.0e5 2.0X10-5 will be 2.0E-5


a = -2.0e5
print(a)
print(type(a))

-200000.0
<class 'float'>

Complex number

Complex numbers are written with a "j" as the imaginary part


Complex numbers are written with a "j" as the imaginary part

x = 3+5j
y = 5j
z = -5j

Booleans

Booleans represent one of two values: True or False.

In programming you often need to know if an expression is True or False.

You can evaluate any expression in Python, and get one of two answers, True or False.

When you compare two values, the expression is evaluated and Python returns the Boolean answer

print(10 > 9)
print(10 == 9)
print(10 < 9)

a = 200
b = 33

if b > a:
print("b is greater than a")
else:
print("b is not greater than a")

x = "Hello"
y = 15

print(bool(x))
print(bool(y))

Almost any value is evaluated to True if it has some sort of content.

Any string is True, except empty strings.

Any number is True, except 0.

Any list, tuple, set, and dictionary are True, except empty ones.

bool("abc")
bool(123)
bool(["apple", "cherry", "banana"])

bool(False)
bool(None)
bool(0)
bool("")
bool(())
bool([])
bool({})

Type Conversion
The process of converting the value of one data type (integer, string, float, etc.) to another data type is called type conversion. Python has two
types of type conversion.

1. Implicit Type Conversion

2. Explicit Type Conversion

Implicit Type Conversion

Python automatically converts one data type to another data type. This process doesn't need any user involvement.

# Code to calculate the Simple Interest


principle_amount = 2000
roi = 4.5
time = 10
simple_interest = (principle_amount * roi * time)/100
print("datatype of principle amount : ", type(principle_amount))
print("datatype of rate of interest : ", type(roi))
print("value of simple interest : ", simple_interest)
print("datatype of simple interest : ", type(simple_interest)) #implicit conversion

a = 10
b = "Hello"
print(a+b)

c = 'Ram'
N = 3
print(c*N)

x = True
y = 10
print(x + 10)

m = False
n = 23
print(n – m)

Try It Yourself:

1) Take a Boolean value and add a string to it

2) Take a string and float number and try adding both

3) Take a Boolean and a float number and try adding both.

Explicit Type Conversion

In Explicit Type Conversion, users convert the data type of an object to required data type. We use the predefined functions like int(), float(),
str(), etc to perform explicit type conversion.

This type of conversion is also called typecasting because the user casts (changes) the data type of the objects.

Birth_day = 10
Birth_month = "July"
print("data type of Birth_day before type casting :", type(Birth_day))
print("data type of Birth_month : ", type(Birth_month))
Birth_day = str(Birth_day)
print("data type of Birth_day after type casting :",type(Birth_day))
Birth_date = Birth_day + ' ' + Birth_month

print("birth date of the student : ", Birth_date)


print("data type of Birth_date : ", type(Birth_date))

data type of Birth_day before type casting : <class 'int'>


data type of Birth_month : <class 'str'>
data type of Birth_day after type casting : <class 'str'>
birth date of the student : 10 July
data type of Birth_date : <class 'str'>

a = 20
b = "Apples"
print(str(a)+ b)

x = 20.3
y = 10
print(int(x) + y)

m = False
n = 5
print(bool(n)+ m)

1
Try it yourself

1) Take a Boolean value “False” and a float number “15.6” and perform the AND operation on both

2) Take a string “ Zero” and a Boolean value “ True” and try adding both by using the Bool() function.

3) Take a string “Morning “ and the float value “90.4” and try and add both of them by using the float() function. Perform the above mentioned
Try it Yourself in the lab and write down the observations to be discussed later in the class.

Exercises

Arithmetic
Write a program that prints out the results of at least one calculation for each of the basic operations: addition, subtraction, multiplication,
division, and exponents.

Order of Operations

Find a calculation whose result depends on the order of operations.

Print the result of this calculation using the standard order of operations.

Use parentheses to force a nonstandard order of operations. Print the result of this calculation.

Long Decimals

On paper, 0.1+0.2=0.3. But you have seen that in Python, 0.1+0.2=0.30000000000000004.

Find at least one other calculation that results in a long decimal like this.

# Ex 2.8 : Arithmetic
a = 6
b = 5
print("a + b = ", end='')
o = a+b
print(o)

# Ex 2.9 : Order of Operations


result = (3*4)+2
print('The result of the calculation of (3*4)+2', result, sep=' = ')

# Ex 2.10 : Long Decimals


print(3.125 / 0.2)

Challenges

Neat Arithmetic
Store the results of at least 5 different calculations in separate variables. Make sure you use each operation at least once.

Print a series of informative statements, such as "The result of the calculation 5+7 is 12."

Neat Order of Operations

Take your work for "Order of Operations" above.

Instead of just printing the results, print an informative summary of the results.

Show each calculation that is being done and the result of that calculation. Explain how you modified the result using parentheses.

Long Decimals - Pattern

On paper, 0.1+0.2=0.3. But you have seen that in Python, 0.1+0.2=0.30000000000000004.

Find a number of other calculations that result in a long decimal like this. Try to find a pattern in what kinds of numbers will result in long
decimals.

# Challenge: Neat Arithmetic

# Put your code here

# Challenge: Neat Order of Operations

# Put your code here

# Challenge: Long Decimals - Pattern

# Put your code here

Comments
As you begin to write more complicated code, you will have to spend more time thinking about how to code solutions to the problems you
want to solve.

Once you come up with an idea, you will spend a fair amount of time troubleshooting your code, and revising your overall approach.

Comments allow you to write in English, within your program. In Python, any line that starts with a pound (#) symbol is ignored by the Python
interpreter.

Commenting one line at a time

# Performing addition of two variables


a = 12 # defining variable a and its value
b = 10 # defining variable b and its value
addition = a + b # Addition logic definition
print(addition) # getting output

22

Commenting Multiple lines at a time

"""
These lines are commented to perform addition task
We will define two variables
we will apply addition logic
we will print the output
"""
a = 12
b = 10
addition = a + b
print(addition)

22
What makes a good comment?

It is short and to the point, but a complete thought. Most comments should be written in complete sentences.

It explains your thinking, so that when you return to the code later you will understand how you were approaching the problem.

It explains your thinking, so that others who work with your code will understand your overall approach to a problem.

It explains particularly difficult sections of code in detail.

When should you write a comment?

When you have to think about code before writing it.

When you are likely to forget later exactly how you were approaching a problem.

When there is more than one way to solve a problem.

When others are unlikely to anticipate your way of thinking about a problem.

Writing good comments is one of the clear signs of a good programmer. If you have any real interest in taking programming seriously, start
using comments now. You will see them throughout the examples in these notebooks.

Exercises

First Comments

Choose the longest, most difficult, or most interesting program you have written so far. Write at least one comment in your program.

# Ex 2.10 : First Comments

# put your code here

Overall Challenges

We have learned quite a bit so far about programming, but we haven't learned enough yet for you to go create something. In the next
notebook, things will get much more interesting, and there will be a longer list of overall challenges.

# Overall Challenge

# Put your code here

# I learned how to strip whitespace from strings.


name = '\t\teric'
print("I can strip tabs from my name: " + name.strip())
Loading [MathJax]/jax/output/CommonHTML/fonts/TeX/fontdata.js

You might also like