Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

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

Sign up
Appearance settings

Examples for people who want to learn Python

NotificationsYou must be signed in to change notification settings

krp/python-examples

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

20 Commits
 
 
 
 

Repository files navigation

Examples for people who want to learn Python

These are designed to be typed into a Python interpreter. These should be simple enough to be useful, but no simpler.

Topics to cover:

Output

# Lines that begin with a '#' are called comments# They're ignored by Python and used for documentation# This line prints "hello"print("hello")print(1234)

Variables

foo=1234# Create a variable called foo whose value is 1234print(foo)name="hello"# Create a variable called nameprint(name)

Input

number=input("Please enter a number: ")print(number)name=input("What is your name? ")print("hello "+name)

Primitive Data Types

# Boolean (True/False) valuesprint(True)print(False)is_hungry=Trueprint(is_hungry)# Toggle between True/False using 'not'is_hungry=notis_hungryprint(is_hungry)# Integersprint(1+1)# Additionprint(999)# Other numbersprint(1e4)# Scientific notation 1e4 is 1000print(1_000_000)# Python ignores _ in numbersprint(-42)# Negative Numbersprint(12-2)# Subtractionprint(12*2)# Multiplicationprint(12//2)# Integer division, converts result to int# Floats aka Floating Point Numbersprint(3.14159)# Approximation of piprint(1/3)# Converts a rational number into imprecise "float" valueprint(12/2)# Regular division, converts to floatprint(13/2)# Regular divisionprint(round(2.3))# Round a number from float to intprint(round(2.7))# Round another number from float to int# Stringslanguage="python"print(language)letters="abcd1234"print(letters)number_string="1234"print(number_string)

Type Conversion

If we want to add values of different types together, we usually need to convert them to the same type (except with int and float).

type(23)type(3.14)type(True)type(-12.4)type("hello")type("a")# Convert from float to intnumber=int(3.14)type(number)# Convert from int to floatnumber=float(3)type(number)# Convert from string to intnumber=int("1234")type(number)# Convert from string to floatnumber=float("12.345")type(number)# Convert from bool to stringvalue=str(True)type(value)# Convert from string to boolvalue=bool('False')# Convert from int to boolbool(0)bool(1)bool(5)bool(-2)# Convert from float to boolbool(0.0)bool(0.1)bool(-0.0)# Weird behaviour:1234+True# gives 1235 because "True" is 1 internally.1234+5*True# gives 12391234-True# gives 12331234/False# gives ZeroDivisionError

Collections 1 (tuple and list)

Tuples

# A tuple is a read-only data structure for storing collections that# don't need to be changed. You create one using ( and ) characters.# Create a tuple with ( and )my_tuple= (1,2,"hello",3.14,False,"hello")print(type(my_tuple))# Access an item by index using [ and ]. Indexes start at 0print(my_tuple[0])print(my_tuple[3])print(my_tuple[10])# IndexError.# Access a container from right-to-leftprint(my_tuple[-1])print(my_tuple[-3])# Count number of items in a tuplemy_tuple.count("hello")my_tuple.count(3.14)my_tuple.count("blahblah")# Search and get the index of an itemmy_tuple.index("hello")my_tuple.index(3.14)my_tuple.index(False)my_tuple.index("blah")# ValueError.# Trying to change the value of an item in a tuple causes an error.my_tuple[2]="newvalue"# TypeError.# Warning: If creating a tuple with only 1 item, you need to use this special syntax with a comma.my_tuple2= (42, )type(my_tuple2)# is a 'tuple' type# If you forget the comma, then Python doesn't create the tuple.fake_tuple= (42)type(fake_tuple)# is an 'int' type

Lists

# Unlike arrays in most other languages, Python lists can store data of any type.# Create a list with [ and ]my_list= [1,2,"this is a list",4.56,True]# Lists have the following methods:# append, clear, copy, count, extend, index, insert, pop, remove, reverse, sort# Accessing an item in a list using index, same as tuples.my_list[2]# displays "this is a list"# Appending an item (only 1 item can be appended at a time).my_list.append(123)# Appends 123 on to the end of the list.# Insert an item at a particular index.my_list.insert(0,'hello')# inserts 'hello' at the beginning (index 0) of list.my_list.insert(2,'blahblah')# inserts 'blahblah' at index 2.# "pop" an item from a list, which accesses an item and removes it.# defaults to end of list if no index is given as an argument.my_list.pop()# removes last item from the listmy_list.pop(2)# gets and removes item at index 2# "remove" differs from pop. pop uses an index. remove searches for the value and removes the first instance of it.my_list.remove("hello")# searches for "hello" and removes 1st instance if found.# Reverse the list (changes the actual list "in place").my_list.reverse()# Sort the list in ascending order. Advanced sorting can control how it'ssorted.my_list.sort()# Copy the list. Returns a "shallow copy". Read more about what this meanslater.my_list2=my_list.copy()# Count the number of occurrences of a value.my_list.count("hello")# Extend the list, aka add multiple items at a time.my_list.extend(["x",102,False])# Return the first index of a value. (without changing the list)my_list.index("hello")# You can also tell it where to start/stop searching.# Clear the list.my_list.clear()

Collections 2 (set and dictionary)

=======

Sets

# A set is an unordered collection of things without duplicates.# Python will automatically remove duplicates from a set.# Important methods you can use on sets are: add, difference,# intersection, union. Run help(set) for others.# Create two setsset_a= {'Apple','Banana','Carrot','Banana'}# duplicate gets removedset_b= {'Carrot','Date','Elderberry'}# Add an itemset_b.add('Hamster')# Remove an itemset_b.remove('Date')# Perform a "union" operation on the sets, aka join them together and return a new set.set_a.union(set_b)# Perform an "intersection" operation, aka return the set of items in both sets.set_a.intersection(set_b)# Perform a "set difference" operation on the two sets. (objects in set A but not set B)set_a.difference(set_b)# Objects only in one or the other, but not both.set_a.symmetric_difference(set_b)# See help(set) for more methods. These are the most common ones though.# You can also perform these operations on multiple sets at a time using operators.set_c= {'Banana','Elderberry','Plum'}# & is intersection. Items only in all sets.set_a&set_b&set_c# | is union. Join all sets together.set_a|set_b|set_c# - is difference (not-symmetric). Items in A but not others.set_a-set_b-set_c# ^ is symmetric difference. Items unique to each set but not overlapping.set_a^set_b^set_c

Dictionaries

# Dictionaries are a key-value object in Python.# Like sets, you create them using { and }, but unlike sets, they must be# created as key-value pairs using the : symbol.# The values used can be any object.my_dictionary= {'banana':'$10.00','cheese':True}# Access items like with lists, except keys are usually strings.my_dictionary['banana']# returns the string '$10.00'my_dictionary['cheese']# returns True# If accessing a key that doesn't exist using [ ], Python raises a KeyError.# e.g. my_dictionary['optimus'] will raise a KeyError.# Adding new items.my_dictionary['optimus']='Truck'# Changing existing items.my_dictionary['cheese']=False# Get all the keys. (used for looping/iterating later on)my_dictionary.keys()# Get all the values.my_dictionary.values()# Get all the items (key-value pairs)my_dictionary.items()# See help(dict) for other methods.

Conditionals / Control Flow Basics

Often you want your program to do different things based on user input.You do this with theif andelse keywords.

magic_word=input('Please enter the magic word: ')ifmagic_word=='Ni!':print('We are the knights who say Ni!')else:print('Bring me a shrubbery!')

Looping Basics

Now you know how to use collections in Python.The next thing to do is learn how to loop and iterate through collections.

A while loop will continue running and looping until its conditional(called theloop invariant) is false.

# The easiest possible loop is an "infinite loop".# Press Ctrl-C to stop it.whileTrue:print('looping')

A loop will automatically end when its loop invariant is no longer true.

number=1whilenumber<100:print(number)number=number+1

If you want tobreak out of a loop early, you can use thebreakkeyword.

number=1whileTrue:print(number)number=number+1ifnumber>=20:break

You can also tell the loop tocontinue using thecontinue keyword.

# Skip printing all numbers between 10 and 40number=1whilenumber<=50:number=number+1if10<number<40:print('skipping')continue# continue from next iteration of the loopprint(number)

The alternative towhile loops arefor loops. They're usually usedfor looping through collections, and there are a few ways to use them.

my_list= [1,2,'hello',4]# How does Python know what 'something' is?# Try a different name instead of 'something' here.# Any name will work. It gets reassigned on each iteration.forsomethinginmy_list:print(something)

Next is therange function which returns a range of numbers.(called arange object)The letteri is usually used when looping through numbers.It's just a convention though.

foriinrange(1,10):print(i)

These are the basics of looping. We'll cover more later. For now this willallow you to create programs that ask for input until some correct valueis entered.

# Exercise: Create a program that runs forever until the user entersacorrectword.# Hint: use input(), a while loop, and an if statement.

TBD

whilefor/inrange()break/continuepassmatchenumerate()ListComprehensions
  • Conditionals (if/elif/else)
  • Exceptions
  • Files (andwith keyword)
  • Modules (and packages / using pip)
  • Python Modules
  • Basic data structures. (stack, queue)

Releases

No releases published

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp