0% found this document useful (0 votes)
5 views49 pages

Python Cheat Sheet

This document is a Python cheat sheet that covers various fundamental concepts such as comments, lists, tuples, if statements, dictionaries, and user input. It provides essential syntax and functionality for each topic, including how to manipulate lists, use conditional statements, and accept user input. The cheat sheet serves as a quick reference guide for Python programming basics.

Uploaded by

danielmasai033
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views49 pages

Python Cheat Sheet

This document is a Python cheat sheet that covers various fundamental concepts such as comments, lists, tuples, if statements, dictionaries, and user input. It provides essential syntax and functionality for each topic, including how to manipulate lists, use conditional statements, and accept user input. The cheat sheet serves as a quick reference guide for Python programming basics.

Uploaded by

danielmasai033
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PYTHON CHEAT SHEET

BY
KIPLANGAT COSMAS

1
RUNNING PYTHON FROM TERMINAL

2
COMMENTS IN PYTHON

Comments are notes within your programs that describe your overall
approach to the problem you’re solving.

Python comments start with a (#). Anything following a it in your code is
ignored by the Python interpreter.


Comments explain what your code is supposed to do and how you are
making it work.

3
LISTS IN PYTHON

4
LISTS IN PYTHON

A list is a collection of items in a particular order

List can contain anything, such as names, letters
numbers etc.

List names are written in plural such as letters, digits etc.

In Python, squre brackets( [ ] ) indicate a list, and
individual elements in a list are separeted by commas.

5
ACCESSING ELEMENTS IN A LIST

Lists are ordered collectios, so we can access any element
in a list by telling Python index of the item desired.

NOTE

Index start form 0 not 1

To access the last index in the list we use [-1] . We can
access list from the right using negative indexs.

6
Using individual values from a list

We can use individual values from a listas we would any
other variable

7
Modifying, Adding, and Removing Elements

Most lists we create are dynamic, meaning we build lists
and then add and remove elements from them as the
program runs its course.

Modifying elements in a list

8
Adding elements to a list

Appending elements to the end of a list

9

Inserting Elements into a list
You can add a new element at any position in a list by
using insert method. You do this by specifying the index
of the new element and the value of the new item:

10

Removing Elements from a list
You can remove an item from a list according to its position
or value.
Removing an element using the del Statement

If you know the positio of an item in the list you can use the
del statement to remove it. But you cant access the value
that was removed from the list after using the del
statement.

11

Removing an item using the pop( ) method
The pop( ) method removes the last item in a list, but
lets you work with that item after removing it.

12

Poping items from any position in a list
We can use pop( ) to remove an item from any position
in a list by including the index of the item we want to
remove in parentheses:


NOTE
We use the del statement if we want don’t want to use
an item removed from the list.
We use the pop( ) method if we want to use the removed
item. 13

Removing an item by value
Sometimes we don’t know the positon of the value we
want to remove from the list. If we know the value to
remove, we can use the remove( ) method.
For Examle the code below remove ducati from the list

14
Organizing a list

We cant control or predict the order in which users
provide data. We may want to organize data in a
paticular order or preserve the original order of the list.
Sorting a list permanently with the sort( ) method

15

Sorting a list Temporarily with the sorted( ) function

To maintain the original order of a list but present it in a
sorted order, we use the sorted( ) function.

16
WORKING WITH LISTS

Looping through an entire list
when you want to do the same action with every item in
a list, you can use Python’s for loop.
For example we can print the whole list without printing
list items individualy using the following code:

17

Using the range( ) function
Python’s range( ) function makes it easy to generate a
series of numbers.


NB: this will print from 1 to 4, it doest print 5 because
python starts counting from the number you provide the
and stops when it reaches the second number provided.
If you pass a single value to the range ( ) as its
argument, it will start the sequence of numbers at 0 then
stop when it reaches the value provided. 18
Using range( ) to make a list of numbers


To print even numbers

19
Slicing a list

20
Looping through a slice

21
Coping lists

22

Printing a list in Reverse order
we use the reverse( ) method, to reverse the original
order of a list.

23
Finding the length of a list

We use the len( ) function to quickly find the lenth of a
list. This is important to know how long the list is e.g how
many users in have regestered in your website.

24
WORKING WITH TUPLES

Tuple looks like a list, exept that a holds values which
are immutable – they cant change while the program is
running.

You can access individual elements by using each item’s
index, just as you would for a list. We define a tuple
using parentheses ( ). for one element we define a taple
with a trailing comma. When working we tuples we can
override its contents to redefine in using a for loop.

25
IF STATEMENTS

26
Simple if statements

The simplest kind of if statement has one test and one
action. If the condition test evaluates to True, python
executes the code following the if statement. If the test
evaluates to false, python ignores the code following the
if statement.

27
If-else statements

An if-else block is similar to a simple if statement, but the
else statement allows you to define an action or set of
actions that are executed when the conditional test fails.
The if-else structure works well in situations in which you
want Python to always execute one of two possible
actions.

28
The if-elif-else chain

To test more than two possible situations, we use
Python’s if-elif-else. Python executes only one block in
an if-elif-else chain. It runs each conditional test in order,
until one passes. When a test passes, the code following
that test is executed and Python skips the rest of the
tests. You can use as many elif blocks in your code as
you like

29
Comparison signs

Equality ==

Inequality !=

Less than <

Greater than >

Less than or equal to <=

Greater than or equal to >=

30
Cheacking if a value is in a list

To find out whether a particular value is already in a list,
use the keyword in.

31
Checking whether a value is not in a list

We use the not key-word in situations where we want to
see if a value does not appear in a list:

32
Boolean expressions

Boolean expresion is just another name for a conditional
test. A boolean value is either True or False, just like the
value of a conditional expresion after it has been
evaluated. They are often used to keep track of certain
conditions, such as whether a game is running or
whether a user can edit certain content on a website:

33
If statements with lists

Combining lists and if statements can alow you to watch
for special values that need to be treated differently than
other values in the list.

34
Checking for special items

35
Checking that a list is not empty

We cant assume that a list not empty. In this case its
useful to check whether a list is empty befor running a
for loop.

36
Using multiple lists

37
DICTIONARIES

38
DICTIONARIES

Python dictionaries, allow you to connect pieces of
related information. You can store the a persons details
such as name, age, location, profession, and any other
aspect.

A dictionary can be created as follows:

39
Working with dictionaries

Dictionaries in python is a collection of key-values pairs. Each key
is connected to a value, and you can use a key to access the
value associated with the key.

A dictionary is wrapped in braces ({ }) with a series of key-values
pairs inside the braces as below:


A key-value pair is a set of values associated with each other.
Each key is connected to values by a colon, and individual key-
values pairs are separated by commas.

40
USER INPUT

41
USER INPUT

Our program needs to get some information from the
user, for example names, age, birthdays etc. so that it
can produce some meaninful information for the user.

To do this we use the input( ) function to accept user
data.

42
How the input() function works

The input() function pauses the program and waits for the
user to enter some text. Python after receiving the user’s
input, stores it in a variable to make it convenient for us to
work with it as below:


The input() function takes one aurgument: the prompt, or
instructions, that we want to display to the user so they
know what to do.

The program waits while the user enters their response and
continues after they press enter. 43
Using a flag

The previous slide controls program while a given condition
is true. When their more than one condition that can stop the
program from running a while loop cant becomes
complicated and difficult.

We introduces a variable called a flag which act as a signal
to the program. We write our program such that it runs as
long as the flag is set to true and stop running when any of
the several events sets the value of the flag to false. The
while loop will then cheak if the flag value is set to true or
false.

44
Using flag

45
Using break to exit a loop

The break ststement directs the flow of your program;
you can use it to control which lines of code are
executed and which aren’t, so the program only
executes code that you want it to, when ypu want it to.

46
Using the continue in a loop

Instead of breaking out of a loop entirely without
executing the rest of its code, we use the continue
statement to return to the beginning of the loop based
on the result of a contitional test.

47
Using int() to accept numerical input

When using the input() function, puthon interprets
everything the user enters as a string. When entering
numbers to use in calculation, python raises an error. To
resolve this issue we use the int() function which
converts a string representation of a number to a
numerical representation. We use the int() function as
below:

48
Working with while loops

While loop runs as long as a certain condition is true. In
contrast to a for loop which takes a collection of certain
items and executes a block of code once for each item
in the collection.

49

You might also like