0% found this document useful (0 votes)
71 views2 pages

Variables Are Used To Store Values. A String Is A Series of

1. The document covers various Python programming concepts including lists, slicing lists, variables, strings, conditionals, loops, functions, classes, inheritance, files, exceptions, and more. 2. Lists can be sliced to access subsets of items using indexes, lists can be looped through and items added or accessed. 3. Conditionals like if, elif, else statements allow for different code blocks to execute depending on certain conditions. 4. Functions allow code reuse and organization while classes define custom object types through attributes and methods.

Uploaded by

Anvitha anoop
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
Download as doc, pdf, or txt
0% found this document useful (0 votes)
71 views2 pages

Variables Are Used To Store Values. A String Is A Series of

1. The document covers various Python programming concepts including lists, slicing lists, variables, strings, conditionals, loops, functions, classes, inheritance, files, exceptions, and more. 2. Lists can be sliced to access subsets of items using indexes, lists can be looped through and items added or accessed. 3. Conditionals like if, elif, else statements allow for different code blocks to execute depending on certain conditions. 4. Functions allow code reuse and organization while classes define custom object types through attributes and methods.

Uploaded by

Anvitha anoop
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1/ 2

Slicing a list

Your programs can prompt the user for input. All input
finishers = ['sam', 'bob', 'ada', 'bea'] is stored as a string.
first_two = finishers[:2]
last_two = finishers[-2:] Prompting for a value
Variables are used to store values. A string is a series of two_and_three = finishers[1:3]
name = input("What's your name? ")
characters, surrounded by single or double quotes. Copying a list print("Hello, " + name + "!")
Hello world copy_of_bikes = bikes[:] Prompting for numerical input
print("Hello world!") #remember – we need int() and float()
Hello world with a variable to convert the input from a STRING

msg = "Hello world!" If statements are used to test for particular conditions age = int(input("How old are you? "))
print(msg) and respond appropriately. pi = float(input("What's the value of pi? "))

Concatenation (combining strings) Conditional tests


first_name = 'albert' equals x == 42
last_name = 'einstein' not equal x != 42
full_name = first_name + ' ' + last_name greater than x > 42
print(full_name) or equal to x >= 42
less than x < 42
or equal to x <= 42

A list stores a series of items in a particular order. Conditional test with lists
You access items using an index, or within a loop. bikes=['kona', 'merida', 'scott', 'giant']
Make a list 'trek' in bikes
'surly' not in bikes
bikes = ['trek', 'redline', 'giant']
Assigning boolean values
Get the first item in a list game_active = True
first_bike = bikes[0] can_edit = False

Get the last item in a list A simple if test

last_bike = bikes[-1] if (age >= 18):


print("You can vote!")
Looping through a list If-elif-else statements
for bike in bikes:
if (age < 4):
print(bike)
ticket_price = 0
Adding items to a list elif (age < 18):
ticket_price = 10
bikes = [] else:
bikes.append('trek') ticket_price = 15
bikes.append('redline')
bikes.append('giant')
Covers Python 3 and Python 2
Making numerical lists
squares = [0,1,2,3,4,5,6,7,8,9,10]
for x in range(1, 11):
print(x, 'squared is', x**2 )
A while loop repeats a block of code as long as a A class defines the behavior of an object and the kind of Your programs can read from files and write to files.
certain condition is true. information an object can store. The information in a class Files are opened in read mode ('r') by default, but can
is stored in attributes, and functions that belong to a class also be opened in write mode ('w') and append mode
A simple while loop are called methods. A child class inherits the attributes ('a').
current_value = 1 and methods from its parent class.
Reading a file and storing its lines
while (current_value <= 5): Creating a dog class (JN: We don’t cover this)
print(current_value) filename = 'siddhartha.txt'
current_value += 1 class Dog(): with open(filename) as file_object:
"""Represent a dog.""" lines = file_object.readlines()
Letting the user choose when to quit
msg = '' def __init__(self, name): for line in lines:
while (msg != 'quit'): """Initialize dog object.""" print(line)
self.name = name
msg = input("What's your message? ") Writing to a file
print(msg)
def sit(self): filename = 'journal.txt'
"""Simulate sitting.""" with open(filename, 'w') as file_object:
print(self.name + " is sitting.") file_object.write("I love programming.")
Functions are named blocks of code, designed to do one
specific job. Information passed to a function is called an my_dog = Dog('Peso') Appending to a file
argument, and information received by a function is called
filename = 'journal.txt'
a parameter. print(my_dog.name + " is a great with open(filename, 'a') as file_object:
A simple function dog!") my_dog.sit() file_object.write("\nI love making games.")
def greet_user(): Inheritance (JN: We don’t cover this)
"""Display a simple class SARDog(Dog):
greeting.""" print("Hello!") """Represent a search dog.""" Exceptions help you respond appropriately to errors that
are likely to occur. You place code that might cause an
greet_user() def __init__(self, name): error in the try block. Code that should run in response to
Passing an argument """Initialize the sardog.""" an error goes in the except block. Code that should run
super().__init__(name) only if the try block was successful goes in the else block.
def greet_user(username):
Catching an exception
"""Display a personalized greeting.""" def search(self):
print("Hello, " + username + "!") """Simulate searching.""" prompt = "How many tickets do you need? "
print(self.name + " is searching.") num_tickets = input(prompt)
greet_user('jesse')
my_dog = SARDog('Willie') try:
Default values for parameters
num_tickets = int(num_tickets)
def make_pizza(topping='bacon'): print(my_dog.name + " is a search dog.") except ValueError:
#Todo: make a single-topping pizza here! my_dog.sit() print("Please try
print("Have a " + topping + " pizza!") my_dog.search() again.") else:
print("Your tickets are printing.")
make_pizza()
make_pizza('pepperoni')
If you had infinite programming skills, what would
Returning a value you build? Simple is better than complex
def add_numbers(x, y): As you're learning to program, it's helpful to think If you have a choice between a simple and a complex
#Add two numbers and return the sum. about the real-world projects you'd like to create. It's solution, and both work, use the simple solution. Your
return (x + y) a good habit to keep an "ideas" notebook that you code will be easier to maintain, and it will be easier for
can refer to whenever you want to start a new project. you and others to build on that code later on.
sum = add_numbers(3, 5) If you haven't done so already, take a few minutes
print(sum)
and describe three projects you'd like to create.
More cheat sheets available at

You might also like