Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications You must be signed in to change notification settings

Latest commit

File metadata and controls, introduction to python programming university of pennsylvania coursera.

introduction to python programming homework 1b

Browse Course Material

Course info.

  • Sarina Canelake

Departments

  • Electrical Engineering and Computer Science

As Taught In

  • Programming Languages
  • Software Design and Engineering

Learning Resource Types

A gentle introduction to programming using python, assignments.

If you are working on your own machine, you will probably need to install Python. We will be using the standard Python software, available here . You should download and install version 2.6.x, not 2.7.x or 3.x. All MIT Course 6 classes currently use a version of Python 2.6.

ASSN # ASSIGNMENTS SUPPORTING FILES
Homework 1 Handout ( )

Written exercises ( )

Code template ( )
Homework 2 Handout ( )

Written exercises ( )

Code template ( )

nims.py ( )

strings_and_lists.py ( )

Project 1: Hangman Handout ( )

hangman_template.py ( )

words.txt ( )

Optional extension:

hangman_lib.py ( )

hangman_lib_demo.py ( )

Homework 3 Handout ( )

Written exercises ( )

Code template ( )
Homework 4 Handout ( )

Written exercises ( )

Graphics module documentation ( )

graphics.py ( ) — be sure to save this in the same directory where your code is saved!

wheel.py ( )

rgb.txt ( )

The graphics.py package and documentation are courtesy of John Zelle, and are used with permission.

Project 2: Conway’s game of life Handout ( )

game_of_life_template.py ( ) — download and save as game_of_life.py; be sure to save in the same directory as graphics.py

Final project: Tetris

Handout ( )

tetris_template.py ( ) — Download and save it in the same directory as graphics.py. Please edit this file, and place your code in the sections that say “YOUR CODE HERE”.

facebook

You are leaving MIT OpenCourseWare

11.1 Object-oriented programming basics

11.2 classes and instances, 11.3 instance methods, 11.4 overloading operators, 11.5 using modules with classes.

This book may not be used in the training of large language models or otherwise be ingested into large language models or generative AI offerings without OpenStax's permission.

Want to cite, share, or modify this book? This book uses the Creative Commons Attribution License and you must attribute OpenStax.

Access for free at https://openstax.org/books/introduction-python-programming/pages/1-introduction
  • Authors: Udayan Das, Aubrey Lawson, Chris Mayfield, Narges Norouzi
  • Publisher/website: OpenStax
  • Book title: Introduction to Python Programming
  • Publication date: Mar 13, 2024
  • Location: Houston, Texas
  • Book URL: https://openstax.org/books/introduction-python-programming/pages/1-introduction
  • Section URL: https://openstax.org/books/introduction-python-programming/pages/chapter-11

© Jul 30, 2024 OpenStax. Textbook content produced by OpenStax is licensed under a Creative Commons Attribution License . The OpenStax name, OpenStax logo, OpenStax book covers, OpenStax CNX name, and OpenStax CNX logo are not subject to the Creative Commons license and may not be reproduced without the prior and express written consent of Rice University.

introduction to python programming homework 1b

Get started learning Python with DataCamp's free Intro to Python tutorial . Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now !

This site is generously supported by DataCamp . DataCamp offers online interactive Python Tutorials for Data Science. Join 11 million other learners and get started learning Python for data science today!

Good news! You can save 25% off your Datacamp annual subscription with the code LEARNPYTHON23ALE25 - Click here to redeem your discount

Welcome to the LearnPython.org interactive Python tutorial.

Whether you are an experienced programmer or not, this website is intended for everyone who wishes to learn the Python programming language.

You are welcome to join our group on Facebook for questions, discussions and updates.

After you complete the tutorials, you can get certified at LearnX and add your certification to your LinkedIn profile.

Just click on the chapter you wish to begin from, and follow the instructions. Good luck!

Learn the Basics

  • Hello, World!
  • Variables and Types
  • Basic Operators
  • String Formatting
  • Basic String Operations
  • Classes and Objects
  • Dictionaries
  • Modules and Packages

Coding for Kids

  • Starting Out
  • Movement with Functions
  • Collecting items
  • Pushing objects
  • Printing on screen
  • Building objects
  • Apply what you've learned

Data Science Tutorials

  • Numpy Arrays
  • Pandas Basics

Advanced Tutorials

  • List Comprehensions
  • Lambda functions
  • Multiple Function Arguments
  • Regular Expressions
  • Exception Handling
  • Serialization
  • Partial functions
  • Code Introspection
  • Map, Filter, Reduce

Other Python Tutorials

  • DataCamp has tons of great interactive Python Tutorials covering data manipulation, data visualization, statistics, machine learning, and more
  • Read Python Tutorials and References course from After Hours Programming

Contributing Tutorials

Read more here: Contributing Tutorials

This site is generously supported by DataCamp . DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!

introduction to python programming homework 1b

Coding for Kids is an online interactive tutorial that teaches your kids how to code while playing!

Receive a 50% discount code by using the promo code:

Start now and play the first chapter for free, without signing up.

introduction to python programming homework 1b

introduction to python programming homework 1b

Introduction to Programming in Python

a textbook for a first course in computer science for the next generation of scientists and engineers

Our textbook Introduction to Programming in Python [ Amazon · Pearson ] is an interdisciplinary approach to the traditional CS1 curriculum. We teach all of the classic elements of programming, using an "objects-in-the-middle" approach that emphasizes data abstraction. A key feature of the book is the manner in which we motivate each programming concept by examining its impact on specific applications, taken from fields ranging from materials science to genomics to astrophysics to internet commerce. The book is organized around four stages of learning to program:

  • Chapter 1: Elements of Programming introduces variables; assignment statements; built-in types of data; conditionals and loops; arrays; and input/output, including graphics and sound.
  • Chapter 2: Functions and Modules introduces modular programming. We stress the fundamental idea of dividing a program into components that can be independently debugged, maintained, and reused.
  • Chapter 3: Object-Oriented Programming introduces data abstraction. We emphasize the concept of a data type and its implementation using Python's class mechanism.
  • Chapter 4: Algorithms and Data Structures introduces classical algorithms for sorting and searching, and fundamental data structures, including stacks, queues, and symbol tables.
  • Appendices provide supplemental material and a Python summary.

Reading a book and surfing the web are two different activities: This booksite is intended for your use while online (for example, while programming and while browsing the web); the textbook is for your use when initially learning new material and when reinforcing your understanding of that material (for example, when reviewing for an exam). The booksite consists of the following elements:

  • Excerpts. A condensed version of the text narrative for reference while online.
  • Exercises. Hundreds of exercises and some solutions.
  • Python code. Hundreds of easily downloadable Python programs and real-world data sets . real-world data sets .-->

To get started.

To get started you must install either a Python 3 or a Python 2 programming environment.

Here are instructions for installing a Python 3 programming environment [ Windows · Mac OS X · Linux ]. We recommend that you install and use the Python 3 programming environment.

Here are instructions for installing a Python 2 programming environment [ Windows · Mac OS X · Linux ]. We recommend that you use the Python 2 programming environment only if you have a compelling reason (external to the requirements of this book and booksite) to do so.

We also provide I/O libraries for reading and writing text, drawing graphics, and producing sound.

You can request an examination copy from Pearson.

Join our webinar , August 21st 4pm PT/7pm ET, to learn how AoPS can help your student succeed this school year!

How Classes Work

Course catalog, class schedule, recommendations, prospective students & parents handbook, current students & parents handbook, general information, the homework, more information, information for parents.

Need help finding the right class? Have a question about how classes work?

Homework in the Programming Courses

The homework assignments in our Introduction to Programming with Python and Intermediate Programming with Python courses are slightly different than in our other courses.

On this page

Introduction to programming with python, intermediate programming with python.

  • Description of Homework Types

This course is 12 weeks long and culminates in a large final project completed in the last two weeks of class. Take a look at the Description of Homework Types for more details about each component.

The First Ten Weeks

For the first ten weeks of the Introduction to Programming with Python course, the homework will consist of readings from the textbook, 6-10 short-answer Challenge Problems and auto-graded Python problems, and one graded Python problem per week.

The Last Two Weeks

During the last two weeks of our Introduction to Programming with Python course, you'll work on just one final project instead of multiple shorter assignments. Over these two weeks, you'll choose one of three games to create. You should expect to spend more time than usual per week on the course while working on your final project.

At the end of the last week of the course, you will submit your final project. As with the earlier graded Python problems, a grader and your instructor will review your submission and provide you with detailed feedback.

This course is 12 weeks long and culminates in two large final projects completed in the last four weeks of class. Take a look at the Description of Homework Types for more details about each component.

The First Eight Weeks

For the first eight weeks of the Intermediate Programming with Python course, the homework will consist of readings from the textbook, 4-8 short-answer Challenge Problems and auto-graded Python problems, and one graded Python problem per week.

The Last Four Weeks

During the last four weeks of our Intermediate Programming with Python course, students work on 2 two-week projects instead of multiple shorter assignments. Students are asked to implement the game Minesweeper in Weeks 9-10, and then the game Checkers in Weeks 11-12.

As with the earlier graded Python problems, a grader and your instructor will review your submission to each project and provide you with detailed feedback.

Description of Homework Types in Python Courses

Textbook Readings : We use an adapted version of How to Think Like a Computer Scientist . Each enrolled student will have access to the book for the duration of the course—no separate book purchase is required. The textbook readings are listed on the Overview tab of the course homepage, and the book can be accessed from the Textbook tab on the course homepage.

Short-Answer Challenge Problems: Like the short-answer challenge problems in other AoPS Courses, these problems will only require you to enter a final answer. You'll be able to try again with any problem you answer incorrectly, and you'll be shown a full solution after you've completed the problem. You may need to write or edit some Python code in order to come up with your final answer!

Auto-Graded Python Problem: These problems will ask you to write some Python code based on a prompt. You'll be able to submit your code once, and you'll be shown a full solution after completing the problem. Your response will not be graded, but you will receive points for submitting a response. If you request a grade at the end of the course, your instructor will take a closer look at your solutions to these problems when determining a grade.

Graded Python Problems: These problems will ask you to write some Python code based a prompt. Like the Writing Problems in our subject courses, these responses are collected at the end of the due date and individually graded. You'll receive personalized feedback from a grader and the instructor, including comments about the accuracy and efficiency of the code and how easy the code is for others to understand.

Something appears to not have loaded correctly.

Click to refresh .

introduction to python programming homework 1b

Python Programming

Practice Python Exercises and Challenges with Solutions

Free Coding Exercises for Python Developers. Exercises cover Python Basics , Data structure , to Data analytics . As of now, this page contains 18 Exercises.

What included in these Python Exercises?

Each exercise contains specific Python topic questions you need to practice and solve. These free exercises are nothing but Python assignments for the practice where you need to solve different programs and challenges.

  • All exercises are tested on Python 3.
  • Each exercise has 10-20 Questions.
  • The solution is provided for every question.
  • Practice each Exercise in Online Code Editor

These Python programming exercises are suitable for all Python developers. If you are a beginner, you will have a better understanding of Python after solving these exercises. Below is the list of exercises.

Select the exercise you want to solve .

Basic Exercise for Beginners

Practice and Quickly learn Python’s necessary skills by solving simple questions and problems.

Topics : Variables, Operators, Loops, String, Numbers, List

Python Input and Output Exercise

Solve input and output operations in Python. Also, we practice file handling.

Topics : print() and input() , File I/O

Python Loop Exercise

This Python loop exercise aims to help developers to practice branching and Looping techniques in Python.

Topics : If-else statements, loop, and while loop.

Python Functions Exercise

Practice how to create a function, nested functions, and use the function arguments effectively in Python by solving different questions.

Topics : Functions arguments, built-in functions.

Python String Exercise

Solve Python String exercise to learn and practice String operations and manipulations.

Python Data Structure Exercise

Practice widely used Python types such as List, Set, Dictionary, and Tuple operations in Python

Python List Exercise

This Python list exercise aims to help Python developers to learn and practice list operations.

Python Dictionary Exercise

This Python dictionary exercise aims to help Python developers to learn and practice dictionary operations.

Python Set Exercise

This exercise aims to help Python developers to learn and practice set operations.

Python Tuple Exercise

This exercise aims to help Python developers to learn and practice tuple operations.

Python Date and Time Exercise

This exercise aims to help Python developers to learn and practice DateTime and timestamp questions and problems.

Topics : Date, time, DateTime, Calendar.

Python OOP Exercise

This Python Object-oriented programming (OOP) exercise aims to help Python developers to learn and practice OOP concepts.

Topics : Object, Classes, Inheritance

Python JSON Exercise

Practice and Learn JSON creation, manipulation, Encoding, Decoding, and parsing using Python

Python NumPy Exercise

Practice NumPy questions such as Array manipulations, numeric ranges, Slicing, indexing, Searching, Sorting, and splitting, and more.

Python Pandas Exercise

Practice Data Analysis using Python Pandas. Practice Data-frame, Data selection, group-by, Series, sorting, searching, and statistics.

Python Matplotlib Exercise

Practice Data visualization using Python Matplotlib. Line plot, Style properties, multi-line plot, scatter plot, bar chart, histogram, Pie chart, Subplot, stack plot.

Random Data Generation Exercise

Practice and Learn the various techniques to generate random data in Python.

Topics : random module, secrets module, UUID module

Python Database Exercise

Practice Python database programming skills by solving the questions step by step.

Use any of the MySQL, PostgreSQL, SQLite to solve the exercise

Exercises for Intermediate developers

The following practice questions are for intermediate Python developers.

If you have not solved the above exercises, please complete them to understand and practice each topic in detail. After that, you can solve the below questions quickly.

Exercise 1: Reverse each word of a string

Expected Output

  • Use the split() method to split a string into a list of words.
  • Reverse each word from a list
  • finally, use the join() function to convert a list into a string

Steps to solve this question :

  • Split the given string into a list of words using the split() method
  • Use a list comprehension to create a new list by reversing each word from a list.
  • Use the join() function to convert the new list into a string
  • Display the resultant string

Exercise 2: Read text file into a variable and replace all newlines with space

Given : Assume you have a following text file (sample.txt).

Expected Output :

  • First, read a text file.
  • Next, use string replace() function to replace all newlines ( \n ) with space ( ' ' ).

Steps to solve this question : -

  • First, open the file in a read mode
  • Next, read all content from a file using the read() function and assign it to a variable.
  • Display final string

Exercise 3: Remove items from a list while iterating

Description :

In this question, You need to remove items from a list while iterating but without creating a different copy of a list.

Remove numbers greater than 50

Expected Output : -

  • Get the list's size
  • Iterate list using while loop
  • Check if the number is greater than 50
  • If yes, delete the item using a del keyword
  • Reduce the list size

Solution 1: Using while loop

Solution 2: Using for loop and range()

Exercise 4: Reverse Dictionary mapping

Exercise 5: display all duplicate items from a list.

  • Use the counter() method of the collection module.
  • Create a dictionary that will maintain the count of each item of a list. Next, Fetch all keys whose value is greater than 2

Solution 1 : - Using collections.Counter()

Solution 2 : -

Exercise 6: Filter dictionary to contain keys present in the given list

Exercise 7: print the following number pattern.

Refer to Print patterns in Python to solve this question.

  • Use two for loops
  • The outer loop is reverse for loop from 5 to 0
  • Increment value of x by 1 in each iteration of an outer loop
  • The inner loop will iterate from 0 to the value of i of the outer loop
  • Print value of x in each iteration of an inner loop
  • Print newline at the end of each outer loop

Exercise 8: Create an inner function

Question description : -

  • Create an outer function that will accept two strings, x and y . ( x= 'Emma' and y = 'Kelly' .
  • Create an inner function inside an outer function that will concatenate x and y.
  • At last, an outer function will join the word 'developer' to it.

Exercise 9: Modify the element of a nested list inside the following list

Change the element 35 to 3500

Exercise 10: Access the nested key increment from the following dictionary

Under Exercises: -

Python Object-Oriented Programming (OOP) Exercise: Classes and Objects Exercises

Updated on:  December 8, 2021 | 52 Comments

Python Date and Time Exercise with Solutions

Updated on:  December 8, 2021 | 10 Comments

Python Dictionary Exercise with Solutions

Updated on:  May 6, 2023 | 56 Comments

Python Tuple Exercise with Solutions

Updated on:  December 8, 2021 | 96 Comments

Python Set Exercise with Solutions

Updated on:  October 20, 2022 | 27 Comments

Python if else, for loop, and range() Exercises with Solutions

Updated on:  July 6, 2024 | 296 Comments

Updated on:  August 2, 2022 | 155 Comments

Updated on:  September 6, 2021 | 109 Comments

Python List Exercise with Solutions

Updated on:  December 8, 2021 | 200 Comments

Updated on:  December 8, 2021 | 7 Comments

Python Data Structure Exercise for Beginners

Updated on:  December 8, 2021 | 116 Comments

Python String Exercise with Solutions

Updated on:  October 6, 2021 | 221 Comments

Updated on:  March 9, 2021 | 23 Comments

Updated on:  March 9, 2021 | 51 Comments

Updated on:  July 20, 2021 | 29 Comments

Python Basic Exercise for Beginners

Updated on:  August 31, 2023 | 497 Comments

Useful Python Tips and Tricks Every Programmer Should Know

Updated on:  May 17, 2021 | 23 Comments

Python random Data generation Exercise

Updated on:  December 8, 2021 | 13 Comments

Python Database Programming Exercise

Updated on:  March 9, 2021 | 17 Comments

  • Online Python Code Editor

Updated on:  June 1, 2022 |

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills .

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Python Tricks

To get New Python Tutorials, Exercises, and Quizzes

Legal Stuff

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our Terms Of Use , Cookie Policy , and Privacy Policy .

Copyright © 2018–2024 pynative.com

Python Tutorial

File handling, python modules, python numpy, python pandas, python matplotlib, python scipy, machine learning, python mysql, python mongodb, python reference, module reference, python how to, python examples, python introduction, what is python.

Python is a popular programming language. It was created by Guido van Rossum, and released in 1991.

It is used for:

  • web development (server-side),
  • software development,
  • mathematics,
  • system scripting.

What can Python do?

  • Python can be used on a server to create web applications.
  • Python can be used alongside software to create workflows.
  • Python can connect to database systems. It can also read and modify files.
  • Python can be used to handle big data and perform complex mathematics.
  • Python can be used for rapid prototyping, or for production-ready software development.

Why Python?

  • Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
  • Python has a simple syntax similar to the English language.
  • Python has syntax that allows developers to write programs with fewer lines than some other programming languages.
  • Python runs on an interpreter system, meaning that code can be executed as soon as it is written. This means that prototyping can be very quick.
  • Python can be treated in a procedural way, an object-oriented way or a functional way.

Good to know

  • The most recent major version of Python is Python 3, which we shall be using in this tutorial. However, Python 2, although not being updated with anything other than security updates, is still quite popular.
  • In this tutorial Python will be written in a text editor. It is possible to write Python in an Integrated Development Environment, such as Thonny, Pycharm, Netbeans or Eclipse which are particularly useful when managing larger collections of Python files.

Python Syntax compared to other programming languages

  • Python was designed for readability, and has some similarities to the English language with influence from mathematics.
  • Python uses new lines to complete a command, as opposed to other programming languages which often use semicolons or parentheses.
  • Python relies on indentation, using whitespace, to define scope; such as the scope of loops, functions and classes. Other programming languages often use curly-brackets for this purpose.

Video: Python Introduction

Tutorial on YouTube

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

Python Practice for Beginners: 15 Hands-On Problems

Author's photo

  • online practice

Want to put your Python skills to the test? Challenge yourself with these 15 Python practice exercises taken directly from our Python courses!

There’s no denying that solving Python exercises is one of the best ways to practice and improve your Python skills . Hands-on engagement with the language is essential for effective learning. This is exactly what this article will help you with: we've curated a diverse set of Python practice exercises tailored specifically for beginners seeking to test their programming skills.

These Python practice exercises cover a spectrum of fundamental concepts, all of which are covered in our Python Data Structures in Practice and Built-in Algorithms in Python courses. Together, both courses add up to 39 hours of content. They contain over 180 exercises for you to hone your Python skills. In fact, the exercises in this article were taken directly from these courses!

In these Python practice exercises, we will use a variety of data structures, including lists, dictionaries, and sets. We’ll also practice basic programming features like functions, loops, and conditionals. Every exercise is followed by a solution and explanation. The proposed solution is not necessarily the only possible answer, so try to find your own alternative solutions. Let’s get right into it!

Python Practice Problem 1: Average Expenses for Each Semester

John has a list of his monthly expenses from last year:

He wants to know his average expenses for each semester. Using a for loop, calculate John’s average expenses for the first semester (January to June) and the second semester (July to December).

Explanation

We initialize two variables, first_semester_total and second_semester_total , to store the total expenses for each semester. Then, we iterate through the monthly_spending list using enumerate() , which provides both the index and the corresponding value in each iteration. If you have never heard of enumerate() before – or if you are unsure about how for loops in Python work – take a look at our article How to Write a for Loop in Python .

Within the loop, we check if the index is less than 6 (January to June); if so, we add the expense to first_semester_total . If the index is greater than 6, we add the expense to second_semester_total .

After iterating through all the months, we calculate the average expenses for each semester by dividing the total expenses by 6 (the number of months in each semester). Finally, we print out the average expenses for each semester.

Python Practice Problem 2: Who Spent More?

John has a friend, Sam, who also kept a list of his expenses from last year:

They want to find out how many months John spent more money than Sam. Use a for loop to compare their expenses for each month. Keep track of the number of months where John spent more money.

We initialize the variable months_john_spent_more with the value zero. Then we use a for loop with range(len()) to iterate over the indices of the john_monthly_spending list.

Within the loop, we compare John's expenses with Sam's expenses for the corresponding month using the index i . If John's expenses are greater than Sam's for a particular month, we increment the months_john_spent_more variable. Finally, we print out the total number of months where John spent more money than Sam.

Python Practice Problem 3: All of Our Friends

Paul and Tina each have a list of their respective friends:

Combine both lists into a single list that contains all of their friends. Don’t include duplicate entries in the resulting list.

There are a few different ways to solve this problem. One option is to use the + operator to concatenate Paul and Tina's friend lists ( paul_friends and tina_friends ). Afterwards, we convert the combined list to a set using set() , and then convert it back to a list using list() . Since sets cannot have duplicate entries, this process guarantees that the resulting list does not hold any duplicates. Finally, we print the resulting combined list of friends.

If you need a refresher on Python sets, check out our in-depth guide to working with sets in Python or find out the difference between Python sets, lists, and tuples .

Python Practice Problem 4: Find the Common Friends

Now, let’s try a different operation. We will start from the same lists of Paul’s and Tina’s friends:

In this exercise, we’ll use a for loop to get a list of their common friends.

For this problem, we use a for loop to iterate through each friend in Paul's list ( paul_friends ). Inside the loop, we check if the current friend is also present in Tina's list ( tina_friends ). If it is, it is added to the common_friends list. This approach guarantees that we test each one of Paul’s friends against each one of Tina’s friends. Finally, we print the resulting list of friends that are common to both Paul and Tina.

Python Practice Problem 5: Find the Basketball Players

You work at a sports club. The following sets contain the names of players registered to play different sports:

How can you obtain a set that includes the players that are only registered to play basketball (i.e. not registered for football or volleyball)?

This type of scenario is exactly where set operations shine. Don’t worry if you never heard about them: we have an article on Python set operations with examples to help get you up to speed.

First, we use the | (union) operator to combine the sets of football and volleyball players into a single set. In the same line, we use the - (difference) operator to subtract this combined set from the set of basketball players. The result is a set containing only the players registered for basketball and not for football or volleyball.

If you prefer, you can also reach the same answer using set methods instead of the operators:

It’s essentially the same operation, so use whichever you think is more readable.

Python Practice Problem 6: Count the Votes

Let’s try counting the number of occurrences in a list. The list below represent the results of a poll where students were asked for their favorite programming language:

Use a dictionary to tally up the votes in the poll.

In this exercise, we utilize a dictionary ( vote_tally ) to count the occurrences of each programming language in the poll results. We iterate through the poll_results list using a for loop; for each language, we check if it already is in the dictionary. If it is, we increment the count; otherwise, we add the language to the dictionary with a starting count of 1. This approach effectively tallies up the votes for each programming language.

If you want to learn more about other ways to work with dictionaries in Python, check out our article on 13 dictionary examples for beginners .

Python Practice Problem 7: Sum the Scores

Three friends are playing a game, where each player has three rounds to score. At the end, the player whose total score (i.e. the sum of each round) is the highest wins. Consider the scores below (formatted as a list of tuples):

Create a dictionary where each player is represented by the dictionary key and the corresponding total score is the dictionary value.

This solution is similar to the previous one. We use a dictionary ( total_scores ) to store the total scores for each player in the game. We iterate through the list of scores using a for loop, extracting the player's name and score from each tuple. For each player, we check if they already exist as a key in the dictionary. If they do, we add the current score to the existing total; otherwise, we create a new key in the dictionary with the initial score. At the end of the for loop, the total score of each player will be stored in the total_scores dictionary, which we at last print.

Python Practice Problem 8: Calculate the Statistics

Given any list of numbers in Python, such as …

 … write a function that returns a tuple containing the list’s maximum value, sum of values, and mean value.

We create a function called calculate_statistics to calculate the required statistics from a list of numbers. This function utilizes a combination of max() , sum() , and len() to obtain these statistics. The results are then returned as a tuple containing the maximum value, the sum of values, and the mean value.

The function is called with the provided list and the results are printed individually.

Python Practice Problem 9: Longest and Shortest Words

Given the list of words below ..

… find the longest and the shortest word in the list.

To find the longest and shortest word in the list, we initialize the variables longest_word and shortest_word as the first word in the list. Then we use a for loop to iterate through the word list. Within the loop, we compare the length of each word with the length of the current longest and shortest words. If a word is longer than the current longest word, it becomes the new longest word; on the other hand, if it's shorter than the current shortest word, it becomes the new shortest word. After iterating through the entire list, the variables longest_word and shortest_word will hold the corresponding words.

There’s a catch, though: what happens if two or more words are the shortest? In that case, since the logic used is to overwrite the shortest_word only if the current word is shorter – but not of equal length – then shortest_word is set to whichever shortest word appears first. The same logic applies to longest_word , too. If you want to set these variables to the shortest/longest word that appears last in the list, you only need to change the comparisons to <= (less or equal than) and >= (greater or equal than), respectively.

If you want to learn more about Python strings and what you can do with them, be sure to check out this overview on Python string methods .

Python Practice Problem 10: Filter a List by Frequency

Given a list of numbers …

… create a new list containing only the numbers that occur at least three times in the list.

Here, we use a for loop to iterate through the number_list . In the loop, we use the count() method to check if the current number occurs at least three times in the number_list . If the condition is met, the number is appended to the filtered_list .

After the loop, the filtered_list contains only numbers that appear three or more times in the original list.

Python Practice Problem 11: The Second-Best Score

You’re given a list of students’ scores in no particular order:

Find the second-highest score in the list.

This one is a breeze if we know about the sort() method for Python lists – we use it here to sort the list of exam results in ascending order. This way, the highest scores come last. Then we only need to access the second to last element in the list (using the index -2 ) to get the second-highest score.

Python Practice Problem 12: Check If a List Is Symmetrical

Given the lists of numbers below …

… create a function that returns whether a list is symmetrical. In this case, a symmetrical list is a list that remains the same after it is reversed – i.e. it’s the same backwards and forwards.

Reversing a list can be achieved by using the reverse() method. In this solution, this is done inside the is_symmetrical function.

To avoid modifying the original list, a copy is created using the copy() method before using reverse() . The reversed list is then compared with the original list to determine if it’s symmetrical.

The remaining code is responsible for passing each list to the is_symmetrical function and printing out the result.

Python Practice Problem 13: Sort By Number of Vowels

Given this list of strings …

… sort the list by the number of vowels in each word. Words with fewer vowels should come first.

Whenever we need to sort values in a custom order, the easiest approach is to create a helper function. In this approach, we pass the helper function to Python’s sorted() function using the key parameter. The sorting logic is defined in the helper function.

In the solution above, the custom function count_vowels uses a for loop to iterate through each character in the word, checking if it is a vowel in a case-insensitive manner. The loop increments the count variable for each vowel found and then returns it. We then simply pass the list of fruits to sorted() , along with the key=count_vowels argument.

Python Practice Problem 14: Sorting a Mixed List

Imagine you have a list with mixed data types: strings, integers, and floats:

Typically, you wouldn’t be able to sort this list, since Python cannot compare strings to numbers. However, writing a custom sorting function can help you sort this list.

Create a function that sorts the mixed list above using the following logic:

  • If the element is a string, the length of the string is used for sorting.
  • If the element is a number, the number itself is used.

As proposed in the exercise, a custom sorting function named custom_sort is defined to handle the sorting logic. The function checks whether each element is a string or a number using the isinstance() function. If the element is a string, it returns the length of the string for sorting; if it's a number (integer or float), it returns the number itself.

The sorted() function is then used to sort the mixed_list using the logic defined in the custom sorting function.

If you’re having a hard time wrapping your head around custom sort functions, check out this article that details how to write a custom sort function in Python .

Python Practice Problem 15: Filter and Reorder

Given another list of strings, such as the one below ..

.. create a function that does two things: filters out any words with three or fewer characters and sorts the resulting list alphabetically.

Here, we define filter_and_sort , a function that does both proposed tasks.

First, it uses a for loop to filter out words with three or fewer characters, creating a filtered_list . Then, it sorts the filtered list alphabetically using the sorted() function, producing the final sorted_list .

The function returns this sorted list, which we print out.

Want Even More Python Practice Problems?

We hope these exercises have given you a bit of a coding workout. If you’re after more Python practice content, head straight for our courses on Python Data Structures in Practice and Built-in Algorithms in Python , where you can work on exciting practice exercises similar to the ones in this article.

Additionally, you can check out our articles on Python loop practice exercises , Python list exercises , and Python dictionary exercises . Much like this article, they are all targeted towards beginners, so you should feel right at home!

You may also like

introduction to python programming homework 1b

How Do You Write a SELECT Statement in SQL?

introduction to python programming homework 1b

What Is a Foreign Key in SQL?

introduction to python programming homework 1b

Enumerate and Explain All the Basic Elements of an SQL Query

CS 101: Introduction to Computing

Spring 2021

CS 101 is a core course offered to first-year B. Tech. students in all disciplines. This course gives a broad introduction to computer programming using the Python programming language.

Total Credits (C) Lecture (L) Tutorial (T) Practical (P)
4 3 0 2
Highlights Classes commence on April 7, 2021 Lectures, tutorials, and labs will be conducted online. Please check the course Google Classroom for more details. Midterm on May 25, 2021 Last day of classes: July 14, 2021

Teaching Assistants

Meetings (all online), recommended books, course eligibility and requirements, learning outcomes, student evaluations, expectations from students, grading policy (tentative), teaching plan.

Clint P. George — clint [at] iitgoa [dot] ac [dot] in Office: F9, New Academic Block A Phone: 832 249 0117

Chitra Nayagam — chitra [at] iitgoa [dot] ac [dot] in Office: IT Lab, Information Technology Department

Shruti Shet — shruti [at] iitgoa [dot] ac [dot] in Office: Computing Lab, Admin Block, IIT Goa

Prince Mathew — prince [at] iitgoa [dot] ac [dot] in

Sakar Salunke — sakar2013108 [at] iitgoa [dot] ac [dot] in

Anushree Debbarma — anusree2013103 [at] iitgoa [dot] ac [dot] in

  • 10:30 am – 11:25 am Tuesday
  • 8:30 am – 9:25 am Wednesday
  • 8:30 am – 9:25 am Thursday

Instructor office hours by email appointment.

Tutorial: 3 pm – 3:50 pm Monday (Common for all groups)

  • Lab hours: Each session will be lead by a group leader (TA). Please login to Classroom to see your group leader.

Introduction to Computation and Programming Using Python, 2nd Edition with Application to Understanding Data by John V. Guttag . 2016. Note: Indian edition available in the market.

How to Think like a Computer Scientist by Allen B. Downey . 2002.

How to Think Like a Computer Scientist: Learning with Python 3 by Peter Wentworth, Jeffrey Elkner, Allen B. Downey, and Chris Meyers . 2012. Note: Online chapters available here .

This is a core course designed for first-year undergraduate students.

Course prerequisites: None

This course will enable students to

Use computational techniques productively

Formulate reasonably complex problems involving sorting, searching, file operations, etc. and solve them using simple algorithms

Implement algorithms in Python programming language

We follow a continuous evaluation plan throughout this course, which includes

Classroom participation (lectures, discussion sessions led by TAs, etc.) is essential throughout the course.

Programming assignments. Students must be able to formulate and solve real-world problems based on the theory covered in lectures and discussions. Discussions with classmates are encouraged, but every student must submit individual solutions in a prescribed form. All programming assignments and projects will use the Python programming language.

Quizzes - There will be two-three quizzes

End semester examination - This will happen at the end of the course.

Course load . We expect that every student will spend 8-10 hours a week in addition to lecture hours and other online/in-classroom interactions. It’s a programming-based course. We assume that students have access to computers where (s)he can set a Python programming environment.

Late submissions will not be accepted for programming assignments, homework, etc. Students must follow the submission guidelines mentioned in every project or assignment to get full credits.

Academic Honesty. We expect that every student follows the highest standards of integrity and academic honesty. Copying/sharing code in exams, homework, lab sessions are not permitted. See the IIT Goa policy for academic malpractices.

The tentative grade distributions for the course are follows

Quizzes (30%)

Homework/Programming Assignments (40%)

Final (30%)

Note: This is a tentative course schedule. It will be updated often. Also, log on to Classroom to see lecture slides, videos, additional course materials, and announcements.

S/N Topic Date Tutorial/Lab
     
1a Course introduction and logistics April 7  
i   April 7 — Get started with Python programming. This interaction will help the students to get started with the course. In addition, we discuss how to set up a basic Python environment locally and or in a cloud (in a web browser).
by
1b What’s computing?
April 8  
     
2 Programming languages; Getting started with Python April 15  
ii   April 16 — Evaluation of Arithmetic Expressions.
by
3 Python elements, order of evaluation, operator precedence April 20  
4 Variables and assignment April 21  
  April 21 Note: auto-graded
5 Boolean expressions, Branching Programs: April 22  
iii   April 23 — Branching statements
by
     
6 Conditional expressions: single, nested, compound April 27  
iv   April 27–30 — Additional excercise on branching statements
7 objects and operations on s April 28  
8 Input/output, type conversions April 29  
     
9 Iteration: May 4  
v   May 4 — While loops
by
  May 5 Note: grades pending
10 Enumeration and loops May 6  
     
11 loops. ,
May 11  
v   May 11–14 — Loops
by
12 Applications of loops May 12  
13 Approximate solutions, exhaustive search May 13  
     
15 Bisection search May 18  
16 Comparing execution times, floats May 19  
17 Introduction to computational complexity May 20  
     
     
18 Solving problems by search (review), Newton-Raphson Jun 8  
19 Function definitions Jun 9  
    Jun 15 Tutorial: by
20 Functions: keyword arguments and default values Jun 10  
     
21 Variable scoping Jun 15  
    Jun 15 Tutorial: by
22 Recursion: count-down, fibonacci numbers Jun 16  
23 Modules Jun 17  
     
24 Tuples, lists, and mutability Jun 22  
25 Lists and sets Jun 23  
26 Dictionaries Jun 24  
     
27 File Input/Output, Discussion on encoding Jun 29  
28 Reading data via files Jun 30  
29 Writing data via files Jul 1  
     
30 Testing, black-box testing, glass-box testing Jul 6  
31 Handling exceptions Jul 7  
32 Exception handling: , ; assertions: ; Getting started with classes and objects Jul 8  
     
33 Abstract data types and classes Jul 13  
34 Using classes for a real-world problem Jul 14  

introduction to python programming homework 1b

Introduction to Python Programming

Get started writing Python with this introductory course.

Last Updated March 7, 2022

Prerequisites:

No experience required

Course Lessons

Why python programming.

Welcome to Introduction to Python! Here's an overview of the course.

Data Types and Operators

Familiarize yourself with the building blocks of Python! Learn about data types and operators, built-in functions, type conversion, whitespace, and style guidelines.

Data Structures

Use data structures to order and group different data types together! Learn about the types of data structures in Python, along with more useful built-in functions and operators.

Control Flow

Build logic into your code with control flow tools! Learn about conditional statements, repeating code with loops and useful built-in functions, and list comprehensions.

Learn how to use functions to improve and reuse your code! Learn about functions, variable scope, documentation, lambda expressions, iterators, and generators.

Setup your own programming environment to write and run Python scripts locally! Learn good scripting practices, interact with different inputs, and discover awesome tools.

Advanced Topics

In this lesson we cover some advanced topics of iterators and generators. You are not required to complete this but we have provided these to give you a taste of these.

Taught By The Best

Photo of Juno Lee

As a data scientist at Looplist, Juno built neural networks to analyze and categorize product images, a recommendation system to personalize shopping experiences for each user, and tools to generate insight into user behavior.

The Udacity Difference

Combine technology training for employees with industry experts, mentors, and projects, for critical thinking that pushes innovation. Our proven upskilling system goes after success—relentlessly.

introduction to python programming homework 1b

Demonstrate proficiency with practical projects

Projects are based on real-world scenarios and challenges, allowing you to apply the skills you learn to practical situations, while giving you real hands-on experience.

Gain proven experience

Retain knowledge longer

Apply new skills immediately

introduction to python programming homework 1b

Top-tier services to ensure learner success

Reviewers provide timely and constructive feedback on your project submissions, highlighting areas of improvement and offering practical tips to enhance your work.

Get help from subject matter experts

Learn industry best practices

Gain valuable insights and improve your skills

introduction to python programming homework 1b

, Discovery

introduction to python programming homework 1b

, Intermediate

introduction to python programming homework 1b

Related Programs

Interested in a verified certificate or a professional certificate ?

An introduction to programming using a language called Python. Learn how to read and write code as well as how to test and “debug” it. Designed for students with or without prior programming experience who’d like to learn Python specifically. Learn about functions, arguments, and return values (oh my!); variables and types; conditionals and Boolean expressions; and loops. Learn how to handle exceptions, find and fix bugs, and write unit tests; use third-party libraries; validate and extract data with regular expressions; model real-world entities with classes, objects, methods, and properties; and read and write files. Hands-on opportunities for lots of practice. Exercises inspired by real-world programming problems. No software required except for a web browser, or you can write code on your own PC or Mac.

Whereas CS50x itself focuses on computer science more generally as well as programming with C, Python, SQL, and JavaScript, this course, aka CS50P, is entirely focused on programming with Python. You can take CS50P before CS50x, during CS50x, or after CS50x. But for an introduction to computer science itself, you should still take CS50x!

How to Take this Course

Even if you are not a student at Harvard, you are welcome to “take” this course for free via this OpenCourseWare by working your way through the course’s ten weeks of material. For each week, follow this workflow:

And then submit the course’s final project .

To submit the course’s problem sets and final project for feedback, be sure to create an edX account , if you haven’t already. Ask questions along the way via any of the course’s communities !

  • If interested in a verified certificate from edX , enroll at cs50.edx.org/python instead.
  • If interested in a professional certificate from edX , enroll at cs50.edx.org/programs/python (for Python) or cs50.edx.org/programs/data (for Data Science) instead.

How to Teach this Course

If you are a teacher, you are welcome to adopt or adapt these materials for your own course, per the license .

IMAGES

  1. Introduction to Python Programming

    introduction to python programming homework 1b

  2. Homework Part 1

    introduction to python programming homework 1b

  3. Introduction to Python Programming : u/pythonhomeworkhelp

    introduction to python programming homework 1b

  4. Coursera Introduction to Python Programming Penn University

    introduction to python programming homework 1b

  5. Introduction To Python

    introduction to python programming homework 1b

  6. The Introduction to Python Programming Language

    introduction to python programming homework 1b

COMMENTS

  1. How to complete Coursera Week-1 on "Introduction to Python Programming

    Watch this video carefully and complete your week 1 with full 100% marks (Quizes + Practice Quiz + Assignments ) on the course of Introduction to Python Prog...

  2. Introduction-to-Python-Programming-University-of-Pennsylvania ...

    Introduction to Python Programming University of Pennsylvania ! contains my answers for the assignment questions of the first course + Things to note - please follow the coursera hounour code and dont copy the answers from here

  3. Introduction to Python Programming

    Module 1 : Course Introduction, Intro to Programming and The Python Language, Variables, Conditionals, Jupyter Notebook, and IDLE. Module 1 • 8 hours to complete. This first module covers an intro to programming and the Python language. We'll start by downloading and installing the necessary tools to begin programming and writing code in ...

  4. Introduction to Programming Using Python

    Exercise 21. Exercise 22. At Quizlet, we're giving you the tools you need to take on any subject without having to carry around solutions manuals or printing out PDFs! Now, with expert-verified solutions from Introduction to Programming Using Python 1st Edition, you'll learn how to solve your toughest homework problems.

  5. Assignments

    This section provides the homework assignments and projects for the course along with ... A Gentle Introduction to Programming Using Python. Menu. More Info Syllabus ... Related Resources Assignments. If you are working on your own machine, you will probably need to install Python. We will be using the standard Python ...

  6. Answer Key Chapter 11

    Our mission is to improve educational access and learning for everyone. OpenStax is part of Rice University, which is a 501 (c) (3) nonprofit. Give today and help us reach more students.

  7. Learn Python

    This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today! Take the Test. learnpython.org is a free interactive Python tutorial for people who want to learn Python, fast.

  8. Introduction to Programming in Python

    Textbook. Our textbook Introduction to Programming in Python [ Amazon · Pearson ] is an interdisciplinary approach to the traditional CS1 curriculum. We teach all of the classic elements of programming, using an "objects-in-the-middle" approach that emphasizes data abstraction. A key feature of the book is the manner in which we motivate each ...

  9. An Introduction to Interactive Programming in Python (Part 1)

    In part 1 of this course, we will introduce the basic elements of programming (such as expressions, conditionals, and functions) and then use these elements to create simple interactive applications such as a digital stopwatch. Part 1 of this class will culminate in building a version of the classic arcade game "Pong".

  10. Programming Homework

    During the last two weeks of our Introduction to Programming with Python course, you'll work on just one final project instead of multiple shorter assignments. Over these two weeks, you'll choose one of three games to create. You should expect to spend more time than usual per week on the course while working on your final project.

  11. Python Exercises, Practice, Challenges

    These free exercises are nothing but Python assignments for the practice where you need to solve different programs and challenges. All exercises are tested on Python 3. Each exercise has 10-20 Questions. The solution is provided for every question. These Python programming exercises are suitable for all Python developers.

  12. Introduction to Python

    Python has a simple syntax similar to the English language. Python has syntax that allows developers to write programs with fewer lines than some other programming languages. Python runs on an interpreter system, meaning that code can be executed as soon as it is written. This means that prototyping can be very quick.

  13. Python Practice for Beginners: 15 Hands-On Problems

    Python Practice Problem 1: Average Expenses for Each Semester. John has a list of his monthly expenses from last year: He wants to know his average expenses for each semester. Using a for loop, calculate John's average expenses for the first semester (January to June) and the second semester (July to December).

  14. Introduction to Python

    Course Lessons. Welcome to Introduction to Python! Here's an overview of the course. Familiarize yourself with the building blocks of Python! Learn about data types and operators, built-in functions, type conversion, whitespace, and style guidelines. Use data structures to order and group different data types together!

  15. CS 101: Introduction to Computing

    Course introduction and logistics: April 7 i April 7: Lab 0 — Get started with Python programming. This interaction will help the students to get started with the course. In addition, we discuss how to set up a basic Python environment locally and or in a cloud (in a web browser). Tutorial by Shruti Shet: 1b: What's computing? Homework 1 ...

  16. Introduction to Python

    Build your subject-matter expertise. This course is part of the Python: A Guided Journey from Introduction to Application Specialization. When you enroll in this course, you'll also be enrolled in this Specialization. Learn new concepts from industry experts. Gain a foundational understanding of a subject or tool.

  17. Introduction to Python Programming

    About the Course. This course provides an introduction to programming and the Python language. Students are introduced to core programming concepts like data structures, conditionals, loops, variables, and functions. This course includes an overview of the various tools available for writing and running Python, and gets students coding quickly.

  18. Free Intro to Python Course

    Reviewers provide timely and constructive feedback on your project submissions, highlighting areas of improvement and offering practical tips to enhance your work. Take Udacity's free Intro to Python course, designed for beginners, and get an introduction to programming and the Python language. Learn online with Udacity.

  19. PDF Introduction to Python Programming Course Notes

    Introduction 1.1 What is Python? Python is a high-level scripting language which can be used for a wide variety of text processing, system administration and internet-related tasks. Unlike many similar languages, it's core language is very small and easy to mas-ter, while allowing the addition of modules to perform a virtually limitless

  20. CS50's Introduction to Programming with Python

    An introduction to programming using a language called Python. Learn how to read and write code as well as how to test and "debug" it. Designed for students with or without prior programming experience who'd like to learn Python specifically. Learn about functions, arguments, and return values (oh my!); variables and types; conditionals ...

  21. PDF URP 6223 Introduction to Urban Analytics

    URP 6223 Introduction to Urban Analytics Page 1 ©2024 Fall Yan Wang - Do not copy, cite, or distribute without permission of the author. ... computer science and computer programming is becoming a necessary skill... in marketing, advertising, ... Python, the primary language used in the course, is an accessible language, and the course will ...

  22. Introduction to Python Programming

    This course provides an introduction to programming and the Python language. Students are introduced to core programming concepts like data structures, conditionals, loops, variables, and functions. This course includes an overview of the various tools available for writing and running Python, and gets students coding quickly. ... Homework 1b ...