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

Python Lecture

Uploaded by

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

Python Lecture

Uploaded by

jamescarloangelo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Python

A program will ask the user to enter a temperature and convert it to Fahrenheit.
Sample output:

Source code:

temp = eval(input('Enter a temperature in Celsius: '))


print('In Fahrenheit, that is', 9/5*temp+32)

The input function’s job is to ask the user to type something in and to capture what the user types.
The part in quotes is the prompt that the user sees. It is called a string and it will appear to the program’s user exactly as it
appears in the code itself.
The eval function is something we use it when we’re getting numerical input.
We need to give a name to the value that the user enters so that the program can remember it and use it in the second line. The
name we use is temp and we use the equals sign to assign the user’s value to temp.
The second line uses the print function to print out the conversion. The part in quotes is another string and will appear to your
program’s user exactly as it appears in quotes here. The second argument to the print function is the calculation. Python will do
the calculation and print out the numerical result.
Write a program that computes the average
of two numbers that the user enters:
Sample output:

Source code:

num1 = eval(input('Enter the first number: '))


num2 = eval(input('Enter the second number: '))
print('The average of the numbers you entered is', (num1+num2)/2)
Remember…
• We use single quotes or double quotes to represent a string in
Python.
• Case matters. To Python, print, Print, and PRINT are all different
things
• Spaces matter at the beginning of lines, but not elsewhere.
For example, the code below will not work.
temp = eval(input('Enter a temperature in Celsius: ‘))
print('In Fahrenheit, that is', 9/5*temp+32)
• Spaces in most other places don’t matter. For instance, the following
lines have the same effect:
print('Hello world!’)
print ('Hello world!’)
print( 'Hello world!’ )
• Python itself totally relies on things like the placement of commas
and parentheses so it knows what’s what. It is not very good at
figuring out what you mean, so you have to be precise.
• The input function is a simple way for your program to get
information from people using your program.
• The eval function converts the text entered by the user into a
number.
• The print function requires parenthesis() around its arguments.
• Anything inside quotes will(with a few exceptions) be printed exactly as it
appears. Example: print('Hi there’)
• print('3+4’)
• print(3+4)
• To print several things at once, separate them by commas. Python will
automatically insert spaces between them.
• print('The value of 3+4 is', 3+4)
• print('A', 1, 'XYZ', 2)
Optional arguments
Two optional arguments to the print function
• sep (short for separator) argument- can use to change that space to
something else
For example, using sep=':' would separate the arguments by a colon and
sep='#' would separate the arguments by one pound sign.

One particularly useful possibility is to have nothing inside the quotes, as in


sep=''. This says to put no separation between the arguments.
• end argument - can use to keep the print function from advancing to the next
line
• Ask the user to enter a number x. Use the sep optional argument to
print out x, 2x, 3x, 4x, and 5x, each separated by three dashes, like
below.
Variable
One of the major purposes of a variable is to remember a value from
one part of a program so that it can be used in another part of the
program.
• Variable names
• There are just a couple of rules to follow when naming your
variables.
• Variable names can contain letters, numbers, and the underscore.
• Variable names cannot contain spaces.
• Variable names cannot start with a number.
• Case matters—for instance, temp and Temp are different.
Activity 2
1. Write a program that asks the user for a weight in kilograms and
converts it to pounds. There are 2.2 pounds in a kilogram.
2. Write a program that asks the user to enter three numbers (use
three separate input statements). Create variables called total and
average that hold the sum and average of the three numbers and
print out the values of total and average.
3. A lot of cell phones have tip calculators. Write one. Ask the user for
the price of the meal and the percent tip they want to leave. Then
print both the tip amount and the total bill with the tip included.
BASIC PROGRAMMING

GENEVEV G. REYES
Subject Teacher
Review
• What are the two(2) optional arguments to the print function?
• This print argument can use to keep the print function from
advancing to the next line.
• This print argument can use to change that space to something
else.
• What is the output of the program below?
print ('The sum of 5 and 1 is', 5+1, '.', sep=':')
a.

b.
Prep Task:
Create a program that will print Hello ten times:
Sample output:
For loops
Example 1. The following program will print Hello ten times:
The structure of a for loop is as follows:
for variable name in range( number of times to repeat ) :
statements to be repeated

The syntax is important here. The word for must be in lowercase, the
first line must end with a colon, and the statements to be repeated
must be indented. Indentation is used to tell Python which statements
will be repeated.
Task 1
Create a program that prints your name five(5) times
using the for loop.
Task 2
Create a program that prints I LOVE YOU. five(5) times
in one line using the for loop.
Sample output:
Example 2
• Create a program that asks the user for a number and prints
its square, then asks for another number and prints its
square, etc. It does this three times and then prints that the
loop is done.
Sample output
Example 3
What is the output of the program below?
print(‘A’)
print('B’)
for i in range(5):
print('C’)
print('D’)
print('E')
Example 4
• Write a program that outputs like this:
The loop variable
• It’s a convention in programming to use the letters i, j, and k for loop
variables, unless there’s a good reason to give the variable a more
descriptive name.
The range function
• The value we put in the range function determines how many times
we will loop.
• The way range works is it produces a list of numbers from zero to the
value minus one. For instance, range(5) produces five values: 0, 1, 2,
3, and 4.
• If we want the list of values to start at a value other than 0, we can
do that by specifying the starting value.
• The statement range(1,5) will produce the list 1, 2, 3, 4. This brings up one
quirk of the range function—it stops one short of where we think it should.
• If we wanted the list to contain the numbers 1 through 5 (including 5), then
we would have to do range(1,6).
• Another thing we can do is to get the list of values to go up by more
than one at a time. To do this, we can specify an optional step as the
third argument. The statement range(1,10,2) will step through the list
by twos, producing 1, 3, 5, 7, 9.
• To get the list of values to go backwards, we can use a step of-1. For
instance, range(5,1,-1) will produce the values 5, 4, 3, 2, in that order.
(Note that the range function stops one short of the ending value 1).
Here are a few more examples:
Write a program that outputs below.

Source Code:
for i in range(5,0,-1):
print(i, end=' ‘)
print('Blast off!!')
A Trickier Example
The program below prints a rectangle of stars that is 4 rows tall and 6
rows wide.

Output:
for i in range(4):
print('*'*(i+1))

The key is to change the 6 to i+1. Each time through the loop the
program will now print i+1 stars instead of 6 stars. The loop counter
variable i runs through the values 0, 1, 2, and 3. Using it allows us to
vary the number of stars.
Exercises
1.A. Write a program that outputs 100 lines, numbered 1 to 100, each
with your name on it. The output should look like the output
below.

1.B. Write a program that outputs 100 lines, numbered 1 to 100, each
with the name you entered. See the sample output below.
2. Write a program that asks the user for their name and how many
times to print it. The pro gram should print out the user’s name the
specified number of times.

3. Write a program that uses a for loop to print the numbers 8, 11, 14,
17, 20, ..., 83, 86, 89.
4. Write a program that uses a for loop to print the numbers 100, 98,
96, ..., 4, 2.
1.

2.

3.
4.
Math Operators
• Here is a list of the common operators in Python:
• Exponentiation - Python uses ** for exponentiation. The
caret, ^, is used for something else.
Example:
print (5**2)
answer: 25

• Integer division - The integer division operator, //, requires


some explanation. Basically, for positive numbers it
behaves like ordinary division except that it throws away
the decimal part of the result.
For instance, while 8/5 is 1.6, we have 8//5 equal to 1.
• Modulo -The modulo operator, %, returns the remainder from a
division.
• For instance, the result of 18%7 is 4 because 4 is the remainder when
18 is divided by 7. This operation is surprisingly useful. For instance, a
number is divisible by n precisely when it leaves a remainder of 0
when divided by n. Thus to check if a number, n, is even, see if n%2 is
equal to 0. To check if n is divisible by 3, see if n%3 is 0.
• The modulo operator shows up surprisingly often in formulas. If you
need to “wrap around” and come back to the start, the modulo is
useful. For example, think of a clock. If you go six hours past 8 o’clock,
the result is 2 o’clock. Mathematically, this can be accomplished by
doing a modulo by 12. That is, (8+6)%12 is equal to 2.
• As another example, take a game with players 1 through 5. Say you
have a variable player that keeps track of the current player. After
player 5 goes, it’s player 1’s turn again. The modulo operator can be
used to take care of this:
player = player%5+1
When player is 5, player%5 will be 0 and expression will set player to 1.
Order of operations
Exponentiation gets done first, followed by multiplication and division
(including // and %), and addition and subtraction come last. The
classic math class mnemonic, PEMDAS (Please Excuse My Dear Aunt
Sally), might be helpful.
This comes into play in calculating an average. Say you have three
variables x, y, and z, and you want to calculate the average of their
values. To expression x+y+z/3 would not work. Because division comes
before addition, you would actually be calculating x + y + z 3 instead of
x+y+z 3 . This is easily fixed by using parentheses: (x+y+z)/3.
In general, if you’re not sure about something, adding parentheses
might help and usually doesn’t do any harm.

You might also like