Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Lesson 2 Variable and User Input

Lesson 2 of the Python programming course focuses on variables and user input, explaining how to store data, perform mathematical computations, and handle strings. It covers the flexibility of variable naming, the importance of user input, and how to convert string inputs into numeric values for calculations. Additionally, it introduces basic math operations and string manipulation techniques, emphasizing the use of libraries for more advanced mathematical functions.

Uploaded by

Qombuter Agafari
Copyright
© © All Rights Reserved
Available Formats
Download as ODP, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Lesson 2 Variable and User Input

Lesson 2 of the Python programming course focuses on variables and user input, explaining how to store data, perform mathematical computations, and handle strings. It covers the flexibility of variable naming, the importance of user input, and how to convert string inputs into numeric values for calculations. Additionally, it introduces basic math operations and string manipulation techniques, emphasizing the use of libraries for more advanced mathematical functions.

Uploaded by

Qombuter Agafari
Copyright
© © All Rights Reserved
Available Formats
Download as ODP, PDF, TXT or read online on Scribd
You are on page 1/ 56

Lesson 2: Get Interactive With Variables

and User Input


Introduction to Python Programming
Lesson 2: Get Interactive With
Variables and User Input

Lesson Overview

Introduction

Variables

Writing Interactive Applications

Math Computations

Review
Introduction


In the last lesson, you created a simple Python
program and got familiar with IDLE.

In this lesson, you’ll continue exploring Python by
discovering how Python stores data and how you
can get input from users.

A variable is a named place in memory where you
can store a value as the program runs.

They can be either numeric values or strings & python works with each
differently.

3
Introduction


We will also see some common mathematical
operators and some of the special things you can
do with Python as you work with numbers.

Finally, you’ll put your new knowledge of number
and string variables to use as you learn how to
get input from the user.

Inputs in Python work a bit differently from other high-level languages
so will spend some time exploring that.

Let’s go in to Lesson 2!

4
Variables: Python Data Types

5
Variables: Storing Numbers


If you've ever written computer code in other high-
level languages like C++ or Java, then you're used
to first declaring your variable before you use it.

In other words, you write a line of code that tells the computer to set aside
memory to be formatted as a certain data type so that you can use it in your
program.

One of the features of Python is that there's no
need to declare your variables.

Instead, you just write your code with the name of
the variable you want, followed by an equal sign
and then the value you want stored in that location.

6
Variables: Storing Numbers


For example, if you want to store the value 10 in a
variable named shoe_size, you'd write this:
shoe_size=10

The variable can store a whole number, as in the
example above, or a number with a decimal point,
as shown here:
shoe_size=10.5

There is no need to explicitly tell the computer
what kind of value the variable is storing.

In fact, this variable can store a whole number and then immediately
switch to storing a decimal.
7
Variables: Storing Numbers


Here’s a code that demonstrates that with the
output.

8
Variables: Variable Names in Python


Python allows you to choose pretty much
whatever name you want, as long as the variable
name starts with a letter and contains only
letters, digits, or the underscore character (_).

Here is a valid name : idNumber , exchange_rate , Variable1,

Here are some invalid ones: 2ndName, Percentage%

Another restriction for your variable names is
keywords or reserved words.

These words have special meanings in Python,
and you aren’t allowed to use them as your
variable names.
9
Variables: Variable Names in Python


To see the list of keywords in Python type in the
code below:
import keyword
print (keyword.kwlist)

Python will give you the list of the keywords you
have to keep in mind when naming your
variables. The list is:-

10
Variables: Variable Names in Python


Normally it’s common to use variable names with
all lower case letter separated by underscores.
student_age , average_score, window_height

This is up to your preference. You can use any
combination of small letters and uppercase
letters.

It’s good to stick to a certain standard through
out for easier readability of your code.

11
Variables: Working with Strings


Before we go any further with numerical
variables, let's switch gears and take a quick look
at strings.

A string is a sequence of zero or more characters.
As you learned earlier, you can make string.

You can make string literals by enclosing them in
double quotes or single quotes as you saw in your
first program.
name=”Python”
name=’python’

12
Variables: Working with Strings


Ability to use single or double quotes simplifies
creating strings which include quotations such
as:

13
Variables: Escape Sequences


If you've done programming in other languages, you
probably already know about escape sequences.

This is basically just putting a backslash character \
in your string to give the computer notice that the
next character means something different.

For example, if you prefer using double quotes to
define your literal strings, then you can always put
the backslash character before the double quotes
within your string.
quote = "The women all said, \"Hello\""
print (quote)

14
Variables: Escape Sequences


Here’s another example which allows you to
insert tabs in your string.

15
Variables: Escape Sequences


There are a number of escape characters. Here is
a list of them.

16
Variables: Working with Strings.


Another interesting and useful twist in Python
programming is that you can mix numbers and
strings.

Just like you could make a numeric variable hold a
whole number at one point and then a number
with a decimal – you can actually use a variable to
hold a number and then a string. For example.
data = 4
data = -12.3
data = "hello there"

17
Variables: Working with Strings.


Try it!

18
Variables: Multiple Assignments in a
Single Line of Code


Here’s one final thing to note about variables and
assigning them values.

Python will actually let you assign multiple
variables different values in the same line of code.

In other words, you don’t have to place each variable on a separate line.

Here’s an example: (Try it in the IDLE command
prompt)
a, b = 1, 2
print (a)
print(b)

19
Variables: Multiple Assignments in a
Single Line of Code


You should get a result like:

20
Variables: Multiple Assignments in a
Single Line of Code


This might not come as much of a shock to you.
However, if you've done programming in C#, C++,
or Java, you know that this just isn't possible in
those languages.

Some programmers don’t like syntax like that,
but others love it. It does cut down on the
number of lines of code, which is good.

Just keep in mind that it's an option you can use.

Now let’s learn how to get an input from a user.

21
Writing Interactive Applications: User
Input as Strings


So far we’ve only dealt with programs that
display output with out any means of getting
input from the user. However there are many
situations you want your program to get data
from the user. In this section we will look at that.

There are two basic ways to get input from the
user. Both methods work the same,

but one enables you to read the user's response as a string.

The other reads it as a number. Let's start with the string method.

22
Writing Interactive Applications: User
Input as Strings


For string input, Python uses a function called input.

This function enables you to print a prompt to your user.
This is a good programming practice that you should
strongly consider putting into your code. Here's the
general form of the input function:
<variable> = input(<Prompt>)

The angle brackets < and > aren't part of the code. This
is just a way of saying put your variable here.

Technically, the variable in the above statement isn't
part of the input function either.

However, if you're taking the time to get input from the
user, you'll need to put it somewhere.

23
Writing Interactive Applications: User
Input as Strings


Let’s write a program that asks the user for their name and
then print it back for them.

This is how the code looks like:
# Get the name from the user
value = input("Please enter your name: ")
print (value)

The first thing you'll probably note about this code is that
the first line starts with #. This line is a comment. By putting
the pound sign there, we're telling the interpreter to ignore
the rest of the line.

Although comments aren't required in programs, it's a really
good idea to include them because they make it easier to
read and understand the code.
24
Writing Interactive Applications: User
Input as Strings


Write the above code in the editor and then run
it. You should get something like this:-

25
Writing Interactive Applications: User
Input as Strings


Go ahead and run this program a few times and
type in different characters. Try putting in a
number or a character like a dollar sign ($). The
program should always work the same and just
give you back whatever you enter.

That's because the characters you're typing are
just stored in a string variable exactly as you
type them. You might not think this is a big deal,
but wait until you start working with numeric
input. You'll see a difference there.

26
Writing Interactive Applications:
Converting Numeric Input to a String


Suppose you want to ask the user's age and then
say how old the user will be in 10 years. Using
what you know already, you might choose to start
with a call to input and then add 10 to the age:
age = input("Enter your age ")
future_age = age + 10
print (future_age)

This seems like a reasonable approach; however
if you try to run this code and enter a number,
you'll find there's a problem.

27
Writing Interactive Applications:
Converting Numeric Input to a String


You see the following error message:

28
Writing Interactive Applications:
Converting Numeric Input to a String


That error message is trying to tell you that you
can’t add a number to a string.

Recall that input( ) gives us back the value as a
string, even if that string is storing a numeric
value, and that you cannot add a number to a
string.

The way to get around this is to make use of either
the int( ) function (for integers) or the float()
function (for floating-point numbers) to convert the
string into a number before doing the math:
future_age = int(age) + 10

29
Writing Interactive Applications:
Converting Numeric Input to a String


With that our code will look like
age = input("Enter your age ")
future_age = int(age) + 10
print (future_age)

However many Python programmers choose to
simply wrap the int( ) or float() function call
around the input( ) function call, as in:
age = int(input("Enter your age "))
future_age = age + 10
print (future_age)
30
Writing Interactive Applications:
Converting Numeric Input to a String


The second code is neater because the value in age
is a number from the very beginning.

Run the first code and then in the prompt try adding a 10 to age as in
age+10

And see the result.

At this point, you have all the basics for user input
and basic use of numeric and string variables.

Now let’s move on and see how to perform math
operations with numeric variables & some tools
that can be applied to strings.

31
Math Computations: Numeric
Manipulation


Let’s face it: computers came about because people
wanted a way to be able to do math quickly and
accurately. There will be times when you'll need to do
math operations in your Python code, so let’s have a
look at the available tools for that.

Basic Math

We’ve seen basic operation such as simple addition, subtraction, multiplication,
and division with the +, -, * and / operators, respectively.

When you do any kind of math operation, the result takes on the format of the
original operands. This means that if you do something like add the whole
number 1 to the whole number 2, the result is the whole number 3. Likewise, if
you add the decimal number 1.0 to the decimal number 2.0, you get the decimal
number 3.0.
32
Math Computations: Numeric
Manipulation


Other useful Operators

We’ve also seen the modulus operator % which gives you the remainder
after doing long division.
7%2
will give 1.

The other operator is ** which is the exponentiation operator.

Type this code to see how they behave and look at the results by varying
the numbers.
print(2**2)
print(89%7)

33
Math Computations: Importing Libraries


There are some more advanced math things you
can do by using a math library.

A math library is a file that has some math
functions and constants that you can use in your
programs if you need them.

Before you can use a library, you must to use an
import statement to import it.

An import statement is a line of code that tells
the computer that you're going to reference
something in a particular library file.

34
Math Computations: Importing Libraries


To import the math library into your program file,
make the import statement the first line of your
program. Then you can use whatever is available in
the library. For example, consider the following
program:
import math

print ("The value of Pi is")


print (math.pi)

print ("There's even another way to")


print ("do power, with math.pow")
print (math.pow(2, 2) )

35
Math Computations: Importing Libraries


In the above code, the first line, import math,
imports the math library. Then the third line calls
one of the math constants from that library:
math.pi. The fifth and sixth lines refer to another
function from the library: math.pow.

You can use dir(<libraryname>) to list all
functions and constants in a library(module).

36
Math Computations: Importing Libraries


For reference here’s a table showing what this
functions do.

37
Math Computations: Importing Libraries


For reference here’s a table showing what this
functions do.

38
Math Computations: Importing Libraries


For reference here’s a table showing what this
functions do.

39
Math Computations: Importing Libraries


For reference here’s a table showing what this
functions do.

40
Math Computations: String
Manipulation


String is an important data type, and Python has
done its best to make strings as easy to work with
as possible.

One thing programmers commonly want to do with
strings is to add one to another.

Now this isn't adding like math, but instead
concatenation, which means appending one string
to the end of another.

Type this in the prompt and see the result:
print("Addis"+ "Ababa")
print("Addis"+" "+"Ababa")
41
Math Computations: String
Manipulation


Python takes this a step further, and in addition to being
able to use + with strings, you can also use *.

Try this one out in the IDLE Shell window:
print ("Selam " * 3)

The result will be SelamSelamSelam.

You might not think this is a very useful tool. But imagine
if you were creating some type of report and you wanted
to separate each section some way. You can create a
horizontal line composed of a repeated character by
specifying the character, a multiplication operator (*), and
the number of times it should be repeated. Try this out to
see for yourself:
print("=" * 80)
42
Math Computations: Other String
Manipulation Commands


Python provides a number of tools to help you
work with strings. For example, it's quite common
to need to know the length of a string.

For that, you can use the len( ) function. Try it out
at the command prompt by typing the following:
word = "My words are important!"
print (len(word))

43
Math Computations: Other String
Manipulation Commands


There are also functions that let you search a
string for a particular

substring (find),

break strings into substrings (split),

remove white space from the ends of your string (strip),

tell if the letters are uppercase (isupper), or

convert all letters to lowercase (lower).

44
Math Computations: Other String
Manipulation Commands


Methods for string manipulation

45
Math Computations: Other String
Manipulation Commands


Methods for string manipulation

46
Math Computations: Other String
Manipulation Commands


Methods for string manipulation

47
Math Computations: Other String
Manipulation Commands


Methods for string manipulation

48
Math Computations: Other String
Manipulation Commands


All string methods return new strings and do not
modify your original string.

So keep in mind that if you're trying to
manipulate your strings, there's probably a
function that'll make your work easier.

Don’t worry about memorizing these methods –
you can look them up when you need.

49
Math Computations: Indexing and
Slicing


Strings are just a collection of zero or more characters.
Python enables you to access individual characters with a
number or index. For example, try out the following code:
phrase = "Python rocks"
print (phrase [0] )

By placing the number 0 inside the square brackets,
you’re asking for the first letter in the phrase variable,
which is P.

One very important thing to note about indexing strings
in Python is that you can only use it to access the
characters. That is, you cannot use this method to put a
new character in a certain position.

50
Math Computations: Indexing and
Slicing


So the following will generate an error:
phrase [0] = 'p'

But that's okay. You can accomplish the same
thing by doing this:
phrase = 'p' + phrase [1:]

Try that in the prompt and use print(phrase) to
see how that affected it.

Now let’s see slicing.

51
Math Computations: Indexing and
Slicing


If you provide two numbers, separated by a
colon, you can get a range of characters out of
the string. That’s known as slicing. You can test
this out with the following code:
phrase = "Python rocks"
print (phrase [1:3] )

Is phrase[3] included in the slice?

How would you slice the string to get the word
rock?

What about if you wanted the word rocks?

52
Math Computations: Indexing and
Slicing


For rocks you can use this:
print(phrase[7:])

This may be a bit of a pain, but the more you
work with this and practice, the more you'll get
used to the way Python does things.

Also keep in mind how powerful slicing is.
Remember, there's no function call here.

53
Math Computations: Indexing and
Slicing


One last note regarding the print function. If you
want to use two different print statements and
still get the output on the same line – you can do
that in Python 3 by using the end attribute to
replace the standard end ( a carriage return) with
a blank space. For example:-
value1 = 1
value2 = 2
print(value1, end=" ")
print(value2, end=" ")

54
Lesson 2 Review


When you began this lesson, you might have thought that there
wasn't much to variables and input. And in some ways, that's right.

As you saw, the basic use of numeric and string variables is pretty
easy.

Even input with the input function is fairly straightforward. But
once you get into the language a little bit, you find that it goes
pretty deep.

Remember, the goal of Python is to give you a full set of simple
tools that you can use to do common things. The best part is that
we've only scratched the surface.

In the next lesson, you’ll learn how to crate a program that makes
decisions. You'll then be able to do things like ask users a question
and then run one set of code or another based on the answer they
give. This is really going to make for a personal, interactive
program that your users are sure to enjoy.

55
Some exercise:


Write a program the prompts a user to input
two numbers and then add and multiply them
and display the two results.

Write a program that prompts the user for his
first and last name and then displays his full
name in UPPERCASE.

Write a program that asks a user for his first
and last name and return his initials. For
example Abebe Kebede will be A. K.

Write a program that solves quadratic
equations of the form Ax2+Bx+C=0
56

You might also like