Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

CSE 4235c Python Assignment 01

Download as pdf or txt
Download as pdf or txt
You are on page 1of 14
At a glance
Powered by AI
The key takeaways are learning Python fundamentals like data types, user input, conditionals, functions and dictionaries.

The main data types in Python are integers, floats, booleans, strings and lists/tuples.

To take user input in Python, you use the input() function and store the result in a variable.

CSE 4235c_Python Assignment 01

Exercise1
Create a program that asks the user to enter their name and their age. Print out a message
addressed to them that tells them the year that they will turn 100 years old.
Extras(For more practice):
1. Add on to the previous program by asking the user for another number and printing
out that many copies of the previous message. (Hint: order of operations exists in
Python)
2. Print out that many copies of the previous message on separate lines. (Hint: the string
"\n is the same as pressing the ENTER button)

User input in Python


To get user input in Python (3), the command you use is input(). Store the result in a variable,
and use it to your heart’s content. Remember that the result you get from the user will be a string,
even if they enter a number.
For example,
name = input("Give me your name: ")
print("Your name is " + name)
What this will print in the terminal (or the shell, whatever you are running Python in) will be:
>>> Give me your name: INSOFE
Your name is INSOFE
What happens at the end of input() is that it waits for the user to type something and press
ENTER. Only after the user presses ENTER does the program continue.

Manipulating strings (a few ways)


What you get from the input() function is a string. What can you do with it?
First: Make the string into a number. Let’s say you are 100% positive that the user entered a
number. You can turn the string into an integer with the function int(). (In a later exercise or two
or three there will be questions about what to do when the user does NOT enter a number and
you try to do this; for now don’t worry about that problem). Here is what this looks like:
age = input("Enter your age: ")
age = int(age)
(or, if you want to be more compact with your code)
age = int(input("Enter your age: "))

Inspire…Educate…Transform
CSE 4235c_Python Assignment 01
In both cases, age will hold a variable that is an integer, and now you can do math with it.
(Note, you can also turn integers into strings exactly in the opposite way, using the str() function)
Second: Do math with strings. What do I mean by that? I mean, if I want to combine
(concatenate is the computer science word for this) strings, all I need to do is add them:
print("Were" + "wolf")
print("Door" + "man")
print("4" + "chan")
print(str(4) + "chan")
The same works for multiplication:
print(4 * "test")
but division and subtraction do not work like this. In terms of multiplication, the idea of
multiplying two strings together is not well-defined. What does it mean to multiply two strings in
the first place? However, it makes sense in a way to specify multiplying a string by a number -
just repeat that string that the number of times. Try this in your own program with all the
arithmetic operations with numbers and strings - the best way to get a feel for what works and
what doesn’t is to try it!

Exercise 2
Ask the user for a number. Depending on whether the number is even or odd, print out an
appropriate message to the user. Hint: how does an even / odd number react differently when
divided by 2?
Extras(For More Practice):
1. If the number is a multiple of 4, print out a different message.

Modular arithmetic (the modulus operator)


We have been doing arithmetic (addition, subtraction, multiplication, division) since elementary
school, and often it is useful for us to find not the answer to a division problem but the remainder
when we do a division operation. This operation is called the “modulus operation.” For example,
when I divide 5 by 3, the remainder is 2, and the sentence reads like this: “5 modulo 3 is 2.”
In the Python shell:
>>> 5 % 3
2
>>> 6 % 3
0
>>> 7 % 3
Inspire…Educate…Transform
CSE 4235c_Python Assignment 01
1
The % sign is exactly the modulus operator.

Conditionals
When a computer (or a program) needs to decide something, it checks whether some condition is
satisfied, which is where the term conditional comes from. Conditionals are a fancy way of
saying “if statements”. If Michele was born in New York, she has an American passport. That
statement is a conditional (if statement) that in this case is true. In Python this works the same
way:

if age > 17:


print("can see a rated R movie")
elif age < 17 and age > 12:
print("can see a rated PG-13 movie")
else:
print("can only see rated PG movies")
When the program gets to the if statement, it will check the value of the variable called age
against all of the conditions, in order, and will print something to the screen accordingly. Note
that elif is a portmanteau of “else” and “if”. So if the variable age holds the value 15, the
statement "can see a rated PG-13 movie" will be printed to the screen.
Note how the statement elif age < 17 and age > 12 has the statement and - you can use or and not
in the same way. Understanding a bit about logic and how it works, or being able to rationally
think about logic will help you get the conditions right - oh, and a lot of practice.
Links about conditionals:
● http://docs.python.org/3.3/tutorial/controlflow.html
● http://www.pythonforbeginners.com/basics/python-if-elif-else-statement/

Checking for equality (and comparators in general)


A fundamental thing you want to do with your program checks whether some number is equal to
another. Say the user tells you how many questions they answered incorrectly on a practice
exam, and depending on the number of correctly-answered questions, you can suggest a specific
course of action. For integers, strings, floats, and many other variable types, this is done with a
simple syntax: ==. To explicitly check inequality, use !=.

if a == 3:
print("the variable has the value 3")
Inspire…Educate…Transform
CSE 4235c_Python Assignment 01
elif a != 3:
print("the variable does not have the value 3")
Notice how in this example, the condition is redundant. In the first condition we are checking
whether the variable a has the value 3 and in the second, we are checking whether a does NOT
have the value 3. However, if the first condition is not true (a is in fact not 3), then the second
condition is by definition true. So a more efficient way to write the above conditional is like this:
if a == 3:
print("the variable has the value 3")
else:
print("the variable does not have the value 3")

Exercise 3
Take a list, say for example this one: a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
and write a program that prints out all the elements of the list that are less than 5.
Extras(For more Practice):
1. Instead of printing the elements one by one, make a new list that has all the elements
less than 5 from this list in it and print out this new list.
2. Write this in one line of Python.
3. Ask the user for a number and return a list that contains only elements from the
original list a that are smaller than that number given by the user.

Lists
Lists are basically an ordered way of grouping things (called elements) - the cool thing about
lists in Python is that you can have a list that contains objects of multiple types. Your list can mix
between strings, integers, objects, other lists, what have you.
The way to construct an empty list is just to do
x = []
And your variable x now holds an empty list. To add things to this list, just “append” them to the
list. Like so:
x = []
x.append(3)
Your list x now looks like [3].
In Python, lists are also iterable, which means you can loop through them with a for loop in a
convenient way. (If you come from other languages like C++ or Java you are most likely used to

Inspire…Educate…Transform
CSE 4235c_Python Assignment 01
using a counter to loop through indices of a list - in Python you can actually loop through the
elements.) I will let the code speak for itself:
my_list = [1, 3, "Michele", [5, 6, 7]]

for element in my_list:


print(element)
Will yield the result:
1
3
"Michele"
[5, 6, 7]
There are many other properties of lists, but for the basic exercise, all you should need is this for
loop property.
For more information about lists in Python, check out these resources:
● http://docs.python.org/3.3/tutorial/datastructures.html
● http://www.tutorialspoint.com/python/python_lists.htm
● http://effbot.org/zone/python-list.htm

More Conditionals
The nice thing about conditionals is that they follow logical operations. They can also be used to
test equality. Let’s do a small example. Let’s say I want to make a piece of code that converts
from a numerical grade (1-100) to a letter grade (A, B, C, D, F). The code would look like this:
grade = input("Enter your grade: ")
if grade >= 90:
print("A")
elif grade >= 80:
print("B")
elif grade >= 70:
print("C")
elif grade >= 65:
print("D")

Inspire…Educate…Transform
CSE 4235c_Python Assignment 01
else:
print("F")
What happens if the grade is 50? All the conditions are false, so "F" gets printed on the screen.
But what if the grade is 95? Then all the conditions are true and everything gets printed, right?
Nope! What happens is the program goes line by line. The first condition (grade >= 90) is
satisfied, so the program enters into the code inside the if statement, executing print("A"). Once
code inside a conditional has been executed, the rest of the conditions are skipped and none of
the other conditionals are checked.

Exercise 4
Take two lists, say for example these two:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
and write a program that returns a list that contains only the elements that are common between
the lists (without duplicates). Make sure your program works on two lists of different sizes.
Extras(For More practice):
1. Randomly generate two lists to test this
2. Write this in one line of Python (don’t worry if you can’t figure this out at this point -
we’ll get to it soon)

List properties
In other words, “things you can do with lists.”
One of the interesting things you can do with lists in Python is figure out whether something is
inside the list or not. For example:
>>> a = [5, 10, 15, 20]
>>> 10 in a
True
>>> 3 in a
False
You can, of course, use this in loops, conditionals, and any other programming constructs.
list_of_students = ["Michele", "Sara", "Cassie"]
name = input("Type name to check: ")
if name in list_of_students:

Inspire…Educate…Transform
CSE 4235c_Python Assignment 01
print("This student is enrolled.")

Exercise 5
Let’s say I give you a list saved in a variable: a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]. Write one
line of Python that takes this list a and makes a new list that has only the even elements of this
list in it.

List Comprehensions
The idea of a list comprehension is to make the code more compact to accomplish tasks
involving lists. Take for example this code:
years_of_birth = [1990, 1991, 1990, 1990, 1992, 1991]
ages = []
for year in years_of_birth:
ages.append(2014 - year)
And at the end, the variable ages have the list [24, 23, 24, 24, 22, 23]. What this code did was
translate the years of birth into ages, and it took us a for loop and an append statement to a new
list to do that.
Compare to this piece of code:
years_of_birth = [1990, 1991, 1990, 1990, 1992, 1991]
ages = [2014 - year for year in years_of_birth]
The second line here - the line with ages is a list comprehension.
It accomplishes the same thing as the first code sample - at the end, the ages variable has a list
containing [24, 23, 24, 24, 22, 23], the ages corresponding to all the birthdates.
The idea of the list comprehension is to condense the for loop and the list appending into one
simple line. Notice that the for loop just shifted to the end of the list comprehension, and the part
before the for keyword is the thing to append to the end of the new list.
You can also embed if statements into the list comprehension - check out the following reference
to help you out.
https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions
Now You can complete practice problems in previous exercises.

Exercise 6
Generate a random number between 1 and 9 (including 1 and 9). Ask the user to guess the
number, then tell them whether they guessed too low, too high, or exactly right. (Hint: remember
to use the user input lessons from the very first exercise)

Inspire…Educate…Transform
CSE 4235c_Python Assignment 01
Extras( More Practice Problems):
● Keep the game going until the user types “exit”
● Keep track of how many guesses the user has taken, and when the game ends, print
this out.

Random Numbers (and Modules)


This is your first exposure to using Python code that somebody else wrote. In Python, these
formally-distributed code packages are called modules. The thing we want from a module in this
exercise is the ability to generate random numbers. This comes from the random module.
To use a module, at the top of your file, type
import random
This means you are allowing your Python program to use a module called random in the rest of
your code.
To use it (and generate a random integer), now type:
a = random.randint(2, 6)
Once you run this program, the variable a will have a random integer that the computer made for
you, between 2 and 6 (including 2 and 6).
The specific documentation for this method is here.
https://docs.python.org/3.3/library/random.html#random.randint
There are many ways you can generate random numbers - integers, decimals, and much more.
The Python documentation has much more detailed information about what is possible from the
random module.

Exercise 7
Ask the user for a number and determine whether the number is prime or not. (For those who
have forgotten, a prime number is a number that has no divisors.).
Take this opportunity to practice using functions, described below.
Functions
One of the programmings of the tool gives us is the ability to break down problems into easier
(or perhaps previously solved) or reusable subproblems. It is good practice to have a function
have a single purpose, and the name of that function should hint at it’s purpose in some way.
Most programming languages have this idea of a function, subroutine, or subprogram. In Python,
a function is a programming construct that allows exactly that.
Let’s look at a simple example:
def get_integer():

Inspire…Educate…Transform
CSE 4235c_Python Assignment 01
return int(input("Give me a number: "))
In this small example, we used the same code that asks a user for input as a tabbed line
underneath this def statement. The def means that everything tabbed underneath is a function.
The name get_integer() is just a name.
If I just include this code inside a Python file and run it, nothing will happen - all We have done
so far is wrapped the code inside of a function;
def get_integer():
return int(input("Give me a number: "))
age = get_integer()
school_year = get_integer()
if age > 15:
print("You are over the age of 15")
print("You are in grade " + str(school_year))
What We have done here is called the function (told it to run) by writing age = get_integer().
When this line of code runs, what happens is the program will execute (run) the function by
asking me for a number, then return it (giving it back to me) by saving it inside the variable age.
Now when I want to ask the user for another number (this time representing the school year), I
do the same thing with the variable school_year.
Reusable functions
This is all well and good, but I can make my function so much more for me. Right now, my
function will always ask the user for a number by printing the string "Give me a number: ". What
if I want to print a different string every time I ask the user for a number, but otherwise use the
same idea for the function? In other words, I want a variable parameter in my function that
changes every time I call the function based on something I (the programmer) want to be
different.
I can do this by passing (giving) my function a variable. Like this:
def get_integer(help_text):
return int(input(help_text))
Now what I can do when I call the function is something like this:
def get_integer(help_text):
return int(input(help_text))
age = get_integer("Tell me your age: ")
school_year = get_integer("What grade are you in? ")

Inspire…Educate…Transform
CSE 4235c_Python Assignment 01
if age > 15:
print("You are over the age of 15")
print("You are in grade " + str(school_year))
Now it is easier for a user to use the program, because the help text is different.
These variables you pass to functions are called variables, parameters, or arguments.
Default arguments
In the example above, once I have added an argument to my function, I always have to give an
argument when I call the function. I can’t forget to give the get_integer() function from above a
string to print to the screen. In some cases, I want there to be a “default” behavior for my
function that happens when I create an argument for it but don’t give it any.
In the example above, if I don’t give a custom string (which may be 95% of the time I use this
function), I just want the input() line to say "Give me a number: " and I want to save myself the
trouble of writing this every single time I call the function. So what I can do is give my function
default arguments. Like so:
def get_integer(help_text="Give me a number: "):
return int(input(help_text))
What happens now is I can use the function in two ways: by giving it an argument and by NOT
giving it an argument.
def get_integer(help_text="Give me a number: "):
return int(input(help_text))

age = get_integer("Tell me your age: ")


school_year = get_integer()
if age > 15:
print("You are over the age of 15")
print("You are in grade " + str(school_year))
The first time I call the function, it will print "Tell me your age: ", but the second time, it will
print "Give me a number:", because I did not give it a string and it will execute the default
behavior.

Exercise 8
Write a program that asks the user how many Fibonacci numbers to generate and then generates
them. Take this opportunity to think about how you can use functions. Make sure to ask the user
to enter the number of numbers in the sequence to generate.(Hint: The Fibonacci seqence is a
Inspire…Educate…Transform
CSE 4235c_Python Assignment 01
sequence of numbers where the next number in the sequence is the sum of the previous two
numbers in the sequence. The sequence looks like this: 1, 1, 2, 3, 5, 8, 13, …)

Exercise 9
Implement a function that takes as input three variables, and returns the largest of the three. Do
this without using the Python max() function!
Hint: Use if...else statement

Exercise 10
Write a function that takes an ordered list of numbers (a list where the elements are in order from
smallest to largest) and another number. The function decides whether or not the given number is
inside the list and returns (then prints) an appropriate boolean. (Linear Search)
Extras(More Practice): Use binary search.

Binary search

There are a number of ways to search for elements in a list, and there is no one correct way to do
so. The point of this exercise is to get you thinking about possible ways to search for elements in
the list, in an entire sequence of exercises about lists, searching, and sorting. This exercise might
seem silly and easy at first, but the more you dive into this topic, the more difficult it becomes.
The word “binary” means there are two choices (in computers, often this is 0 or 1, but it really
means any choice between two things). “Search” is to look for something. So the main idea
behind binary search is to look for something in a way that gives you a decision tree for where to
look, containing two choices. Let me give you an example:
Let’s take the list a = [1, 3, 5, 30, 42, 43, 500]. It is an “ordered list”, or a list where the elements
in the list go from smaller to larger. Let’s say we want to know whether the element 9 is in the
list or not. Here is what we do:
● Look at the middle element in the list - it is ‘30’. * ‘9 < 30’, so let us ignore the
elements to the right of ‘30’.
● The new list we are looking at is now [1, 3, 5].
● Look at the middle element in this new list - it is 3.
● ‘9 > 3’, so ignore the elements to the left of 3.
● The new list we are looking at is [5].
● The list has one element and it is not 9.
● 9 is not in the list.
What the example shows is that in an ordered list, knowing how the element you are looking for
compares to another element in the list splits the list in two - one half where the element can be,
and one where it definitely cannot be. In the case where our list contains millions of elements,
knowing that we can cut the “search space” in half is a great increase in efficiency.
Inspire…Educate…Transform
CSE 4235c_Python Assignment 01
When you are writing the solution, first try to write it without the binary search. Then when you
want to try implementing binary search, write a separate function. In the solution, I will give an
example for how to write a binary search in Python

Exercise 11
For this exercise, we will keep track of when our friend’s birthdays are, and be able to find that
information based on their name.
Create a dictionary (in your file) of names and birthdays. When you run your program it should
ask the user to enter a name and return the birthday of that person back to them. The interaction
should look something like this:
>>> Welcome to the birthday dictionary. We know the birthdays of:
Albert Einstein
Benjamin Franklin
Ada Lovelace
>>> Who's birthday do you want to look up?
Benjamin Franklin
>>> Benjamin Franklin's birthday is 01/17/1706.

Dictionaries
Dictionaries are Python’s way of associating two pieces of data together.
(https://docs.python.org/3.3/tutorial/datastructures.html#dictionaries)
student_scores = {'Adama': 100, 'Starbuck': 75, 'Apollo': 80, 'Athena': 85, 'Agathon': 90}
The strings (or whatever happens to the left of the: sign), are called keys. When I want to access
the values (the things to the right of the: sign), I need to ask the dictionary for the value
associated with the key:
adama_score = student_scores['Adama']
You can then modify the score and save it back to the dictionary:
adama_score = student_scores['Adama']
adama_score += 100 % adama_score is now 200. This doesn't change the dictionary value
student_scores['Adama'] = adama_score % the score in the dictionary is now updated
I can’t ask the dictionary for the key associated with a value, but I can get a list of all the keys,
and the same for all the values:
all_scores = student_scores.keys()
all_names = student_scores.values()

Inspire…Educate…Transform
CSE 4235c_Python Assignment 01
I can use the in keyword (just like in lists), do dictionary comprehensions like list
comprehensions, and iterate over the elements in the dictionary (the syntax is just a little bit
different).
for pair in student_scores.items():
print(pair)
And this prints out pairs of keys and values that look like: (Adama, 100), etc.
Because dictionaries are not ordered, looping through them does not guarantee the key/value
pairs coming out in a particular order. So be careful.

Please find the solutions at the following link https://www.practicepython.org/exercises/

Exercise 12
A website requires the users to input username and password to register. Write a
program to check the validity of password input by users.

Following are the criteria for checking the password:

1. At least 1 letter between [a-z]

2. At least 1 number between [0-9]

3.At least 1 letter between [A-Z]

4. At least 1 character from [$#@]

5. Minimum length of transaction password: 6

6. The maximum length of transaction password: 12

Your program should accept a sequence of comma-separated passwords and will check
them according to the above criteria. Passwords that match the criteria are to be printed,
each separated by a comma.

Exercise 13
i. Define a function that can receive two integral numbers in string form and compute
their sum and then print it in the console.

Inspire…Educate…Transform
CSE 4235c_Python Assignment 01
ii. Define a function that can receive two integral numbers in string form and compute
their sum and then print it in the console.
iii. Define a function to check the given number is a palindrome or not.
iv. Define a function to print the sum of digits of a given number.

Inspire…Educate…Transform

You might also like