Difference between revisions of "CSC111 Programs Created in Class 2018"
(→Working with Text Files (chocolate program)) |
(→Working with Text Files) |
||
Line 761: | Line 761: | ||
+ | </source> | ||
+ | =2/26/18= | ||
+ | <br /> | ||
+ | ::<source lang="python"> | ||
+ | # readChocolateFile.py | ||
+ | # D. Thiebaut | ||
+ | # Opens a text file and displays it contents. | ||
+ | # Note: you need to have a file called chocolate.txt | ||
+ | # in the same directory/folder where you have saved | ||
+ | # this program!!! | ||
+ | |||
+ | |||
+ | def main(): | ||
+ | # open file | ||
+ | file = open( "chocolate.txt", "r" ) | ||
+ | |||
+ | # read each line from file and display it | ||
+ | for line in file: | ||
+ | print( line.strip() ) | ||
+ | |||
+ | # close the file | ||
+ | file.close() | ||
+ | |||
+ | main() | ||
+ | |||
+ | # ---------------------------------------------------------------------- | ||
+ | |||
+ | |||
+ | def singHappyBirthday( minion ): | ||
+ | print( "Happy birthday to you" ) | ||
+ | print( "Happy birthday to you" ) | ||
+ | print( "Happy birthday, dear", minion ) | ||
+ | print( "Happy birthday to you" ) | ||
+ | print( ) | ||
+ | |||
+ | def main(): | ||
+ | for minion in [ "Dave", "Stuart", "Jerry", "Jorge" ]: | ||
+ | singHappyBirthday( minion ) | ||
+ | |||
+ | main() | ||
+ | |||
+ | # ---------------------------------------------------------------------- | ||
+ | |||
+ | # DaveEats.py | ||
+ | # D. Thiebaut | ||
+ | |||
+ | |||
+ | def DaveEats( fruit ): | ||
+ | print( "Dave opens their mouth" ) | ||
+ | print( "and eats the", fruit ) | ||
+ | print() | ||
+ | |||
+ | |||
+ | |||
+ | def main(): | ||
+ | for fruit in [ "banana", "apple", "orange" ]: | ||
+ | DaveEats( fruit ) | ||
+ | |||
+ | |||
+ | main() | ||
+ | |||
+ | # ---------------------------------------------------------------------- | ||
+ | |||
+ | # printBarSayHello.py | ||
+ | # D. Thiebaut | ||
+ | |||
+ | |||
+ | def printBar(): | ||
+ | print( 60 * '-' ) | ||
+ | |||
+ | |||
+ | def sayHello(): | ||
+ | print( ) | ||
+ | print( "Hello, and welcome!" ) | ||
+ | print( ) | ||
+ | |||
+ | def main(): | ||
+ | printBar() | ||
+ | printBar() | ||
+ | |||
+ | main() | ||
+ | |||
+ | |||
+ | # ---------------------------------------------------------------------- | ||
+ | |||
+ | |||
+ | # ---------------------------------------------------------------------- | ||
+ | # ---------------------------------------------------------------------- | ||
</source> | </source> | ||
[[Category:Python]][[Category:CSC111]] | [[Category:Python]][[Category:CSC111]] |
Revision as of 12:27, 26 February 2018
D. Thiebaut (talk) 12:30, 31 January 2018 (EST)
Contents
1/30/18
# wedWeek1.py
# D. Thiebaut
# Demo program week 1
# variables
age = 20
year = 2018
# compute year born
print( year - age )
# example of for loop
for name in [ "smith", 23, 3.14159, "hello" ]:
print( name )
"""
challenge: print the following lines
***
Mae
*****
Alice
*******
Felicia
"""
for name in [ "Mae", "Alice", "Felicia" ]:
print( '*' * len( name ) )
print( name )
"""
new challenge: print the following lines
*
Mae
********
Alice
****
Felicia
**
"""
for name in [ "*", "Mae", "********", "Alice", "****", "Felicia", "**" ]:
print( name )
02/05/18
Table of Fahrenheit to Celsius conversion
# 020518.py # D. Thiebaut # # print table of temperatures # start at 100 F down to -30 F # in steps of 10 # using the formula: Celsius = (Farhenheit - 32 ) * 5 / 9 # print the header print( "Fahrenheit --> Celsius" ) # display the table of temperatures # ranging from 100 down to -30F. for fTemp in range( 100, -31, -10 ): cTemp = ( fTemp - 32 ) * 5 / 9 print( fTemp, '-->', cTemp )
Problem: get user name and grade and display user information and grade as a bar graph.
# barGraph.py
# D. Thiebaut
# this program prompts the user for her information
# and grade and displays a bar-graph.
#
#First name? Dominique
#Last name? Thiebaut
#Id? 990123456
#Final grade? 90
#
#+———————————————————————————————————-———————————-+
#|Dominique Thiebaut 990123456 |
#+———————————————————————————————————-———————————-+
# 00...10...20...30...40...50...60...70...80...90...100
#grade: #############################################
#class: ########################################
#
#
# input section
fName = input( "First name? " )
lName = input( "Last name? " )
Id = input( "Id? " )
final = input( "Final grade? " )
# output section
print( fName, lName, Id )
bar = "+———————————————————————————————————-———————————-+"
barLen = len( bar )
print( "barLen =", barLen )
nameIdLen = len( fName )+1+len( lName ) + len( Id )+1
print( "nameIdLen =", nameIdLen )
print( bar )
print( "|", fName, lName, ' '*(barLen-nameIdLen), Id, '|' )
print( bar )
2/7/18
We didn't have time to cover this problem, because of the snow storm... But it simply displays
an 8 by 8 chessboard using hash tags.
# chessBoard.py # D. Thiebaut # displays an 8x8 chessboard, as shown below. """ ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### """ numRows = eval( input( "Number of rows? " ) ) numCols = eval( input( "Number of columns? " ) ) white=" " black="###" bar1 = "" bar2 = "" for i in range( numCols//2 ): bar1 = bar1 + white + black bar2 = bar2 + black + white for i in range( numRows//2 ): # display 2 lines of squares # alternating the colors # 5 ### ### ### ### # ### ### ### ### # ### ### ### ### # ### ### ### ### # ### ### ### ### # ### ### ### ### for n in range( 3 ): print( bar1 ) for n in range( 3 ): print( bar2 )
2/9/18
# barGraph.py # D. Thiebaut # this program prompts the user for her information # and grade and displays a bar-graph. # #First name? Dominique #Last name? Thiebaut #Id? 990123456 #Final grade? 90 # #+———————————————————————————————————-———————————-+ #|Dominique Thiebaut 990123456 | #+———————————————————————————————————-———————————-+ # 00...10...20...30...40...50...60...70...80...90...100 #grade: ############################################# #class: ######################################## # # # box geometry bar = "+———————————————————————————————————-———————————-+" barLen = len( bar ) # input section fName = input( "First name? " ) fNameLen = len( fName ) lName = input( "Last name? " ) lNameLen = len( lName ) Id = input( "Id? " ) IdLen = len( Id ) numSpaces = barLen -3 -(fNameLen+1+lNameLen+IdLen) grade = eval( input( "Final grade? " ) ) classGrade = 80 # output section print( bar ) print( '|' + fName, ' ', lName, ' '*(numSpaces), Id, ' |', sep='' ) print( bar ) # print the scale print( " 00...10...20...30...40...50...60...70...80...90...100" ) # print the student grade as a bar numHashTags = grade // 2 print( "grade:", '#' * numHashTags ) #print the class grade as a bar numHashTags = classGrade // 2 print( "class:", '#' * numHashTags )
2/12/18
# teller.py # D. Thiebaut # simulates teller machine program # prompts user, displays number of bills # input amount to withdraw (use eval) amount = eval( input( "Amount to withdraw? " ) ) amount = abs( amount ) print( "Amount:", amount ) # compute number of bills, 20, 10, 5, 1 no20s = amount // 20 amount = amount % 20 # leftover after giving out all the 20s no10s = amount // 10 amount = amount % 10 # leftover after giving out all the 10s no5s = amount // 5 amount = amount % 5 # leftover after giving out all the 5s no1s = amount # display number of bills print( no20s, "$20-bill(s)" ) print( no10s, "$10-bill(s)" ) print( no5s, "$5-bill(s)" ) print( no1s, "$1-bill(s)" )
2/14/18
# generate a table of the powers of 2 """ 0 1 1 2 2 4 3 8 4 16 5 32 6 64 7 128 8 256 9 512 1234567890123 """ for i in range( 10 ): print( "{0:5}{1:5}".format( i, 2**i ) ) # display the following table: # 1: len(Doc )= 3 # 2: len(Grumpy )= 6 # 3: len(Happy )= 5 # 4: len(Sleepy )= 6 # 5: len(Dopey )= 5 # 6: len(Bashful)= 7 # 7: len(Sneezy )= 6 count = 1 for name in ["Doc", "Grumpy", "Happy", "Sleepy", "Dopey", "Bashful", "Sneezy" ]: print( "{0:1}: len({1:<7})= {2:1}" .format( count, name, len(name) ) ) count = count + 1
2/16/18
# accumulate.py # D. Thiebaut # solution programs for 2/16/18 # -------------------------------------- # sum of all the numbers from 1 to 100 total = 0 #print( "initial total:", total ) for i in range( 0, 100+1, 5): #print( i, total ) total = total + i #print( "after sum:", i, total ) #print() print( total ) # -------------------------------------- # average of [100, 95,100, 90, 60, 85] total = 0 count = 0 for i in [100, 95,100, 90, 60, 85]: total = total + i print( "i =", i ) count = count + 1 print( "count = ", count ) print( "total = ", total, "count = ", count ) print( "average = ", total/count ) # -------------------------------------- a = "#" b = "+" final = "" # from numbers to string print( "before loop: a=", a, "b=", b ) for i in [1,2,1,1,3,4]: #print( i * a, end="", sep="" ) print( "i=", i, "a=", a, "b=", b ) final = final + i*a print( "final =", final ) a, b = b, a print( "final string = ", final )
2/19/18
Different ways to print all the strings in a list.
def main(): farm = ["pig", "dog", "horse", "hen" ] #-------------------------------------------------- print( "method 1" ) print( """pig dog horse hen""" ) #-------------------------------------------------- print( "method 2" ) print( farm ) #-------------------------------------------------- print( "method 3" ) print( "pig\ndog\nhorse\nhen" ) #-------------------------------------------------- print( "method 4" ) print( list( farm ) ) #-------------------------------------------------- print( "method 5" ) print( farm[0], farm[1], farm[2], farm[3] ) #-------------------------------------------------- print( "method 6" ) print( farm[0], farm[1], farm[2], farm[3], sep="\n" ) #-------------------------------------------------- print( "method 7" ) for n in [0,1,2,3]: print( farm[n] ) #-------------------------------------------------- print( "method 8" ) for animal in farm: print( animal ) #-------------------------------------------------- print( "method 9" ) for animal in farm: for c in range( len( animal ) ): print( animal[c], sep="", end="") print(" " ) #-------------------------------------------------- print( "method 10" ) for i in range( len( farm ) ): print( farm[i] ) #-------------------------------------------------- print( "method 11" ) for i in range( -1, -len(farm), -1 ): print( farm[ i ] ) #-------------------------------------------------- print( "method 12" ) for i in range( -1, -len(farm)-1, -1 ): print( farm[ i ] ) #-------------------------------------------------- print( "method 13" ) for i in range( -len(farm), 0, 1 ): print(farm[i] ) main()
02/21/18
>>> name = "H:/Documents/solutionsHw4.doc" >>> name 'H:/Documents/solutionsHw4.doc' >>> drive = name[0:2] >>> drive 'H:' >>> name 'H:/Documents/solutionsHw4.doc' >>> ext = name[-3: ] >>> ext 'doc' >>> newName = name[0:-3] >>> newName 'H:/Documents/solutionsHw4.' >>> newName = name[0:-3] + "txt" >>> newName 'H:/Documents/solutionsHw4.txt' >>> fname = "Alex" >>> lname = "Booth" >>> account = fname[0:1] + lname >>> account 'ABooth' >>> account = fname[0] + lname >>> account 'ABooth' >>> date = "02212018" >>> wanted = "21 Feb 2018" >>> date '02212018' >>> wanted '21 Feb 2018' >>> months = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun" ,"Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ] >>> months ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] >>> months[1] 'Feb' >>> months[2] 'Mar' >>> months = ["Dummy", 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] >>> months[2] 'Feb' >>> day = date[2:4] >>> day '21' >>> month = date[0:2] >>> month '02' >>> int( month ) 2 >>> months[ int( month ) ] 'Feb' >>> date '02212018' >>> year = date[4: ] >>> year '2018' >>> print( day, months[ int( month ) ], year ) 21 Feb 2018 >>> date '02212018' >>> day '21' >>> month '02' >>> year '2018' >>> months ['Dummy', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] >>> months[ int( month ) ] 'Feb' >>> fname = "Maria" >>> lname = "Luce" >>> name = fname + lname >>> name 'MariaLuce' >>> for i in range( len( name ) ): print( i ) 0 1 2 3 4 5 6 7 8 >>> for i in range( len( name ) ): print( i, name[0:i] ) 0 1 M 2 Ma 3 Mar 4 Mari 5 Maria 6 MariaL 7 MariaLu 8 MariaLuc >>> for i in range( len(name ) ): print( i, name[0:i+1] ) 0 M 1 Ma 2 Mar 3 Mari 4 Maria 5 MariaL 6 MariaLu 7 MariaLuc 8 MariaLuce >>> for i in range( len( name ) ): print( name[0:i+1] ) M Ma Mar Mari Maria MariaL MariaLu MariaLuc MariaLuce >>> farm = [ "pig", "dog", "cat" ] >>> farm ['pig', 'dog', 'cat'] >>> farm[0] 'pig' >>> farm[1] 'dog' >>> farm[-1] 'cat' >>> >>> >>> farm[ 0 ] = "horse" >>> farm ['horse', 'dog', 'cat'] >>> farm[2] = "mouse" >>> farm ['horse', 'dog', 'mouse'] >>> farm[-1] = "cat" >>> farm ['horse', 'dog', 'cat'] >>> name = "Smith College" >>> >>> >>> >>> >>> name[0] 'S' >>> name[-1] 'e' >>> name[2] 'i' >>> name[0] = 'Z' Traceback (most recent call last): File "<pyshell#94>", line 1, in <module> name[0] = 'Z' TypeError: 'str' object does not support item assignment <--- strings are immutable! >>> farm2 = ( "cat", "dog", "mouse" ) >>> farm2[1] 'dog' >>> farm2[1] = "horse" Traceback (most recent call last): File "<pyshell#97>", line 1, in <module> farm2[1] = "horse" TypeError: 'tuple' object does not support item assignment >>> animal = "horse" >>> animal[0] = 'H' Traceback (most recent call last): File "<pyshell#99>", line 1, in <module> animal[0] = 'H' TypeError: 'str' object does not support item assignment >>> animal = 'H' + animal[1: ] >>> animal 'Horse' >>> greeting = "hello there" >>> greeting.upper() 'HELLO THERE' >>> greeting 'hello there' >>> greeting = greeting.upper() >>> greeting 'HELLO THERE' >>> lname = "Max" >>> fname = "Joe" >>> fname[0] + lname 'JMax' >>> account = fname[0] + lname >>> account 'JMax' >>> account = account.lower() >>> account 'jmax' >>> title = "CSC111 Intro to CS" >>> title.center( 60 ) ' CSC111 Intro to CS ' >>> title 'CSC111 Intro to CS' >>> print( title.center( 60 ) ) CSC111 Intro to CS >>> name = "alex booth" >>> name.capitalize() 'Alex booth' >>> name 'alex booth' >>> name.title() 'Alex Booth' >>> name = "MICKEY MOUSE" >>> name.capitalize() 'Mickey mouse' >>> name.title() 'Mickey Mouse' >>> name 'MICKEY MOUSE' >>> name = name.title() >>> name 'Mickey Mouse' >>> name.find( 'z' ) -1 >>> name.find( 'o' ) 8 >>> name.find( 'M' ) 0 >>> name.find( 'c' ) 2 >>> name.find( "ou" ) 8 >>> name 'Mickey Mouse' >>> name.replace( "Mickey", "Minnie" ) 'Minnie Mouse' >>> name 'Mickey Mouse' >>> name.replace( "Mouse", "Cat" ) 'Mickey Cat' >>> name 'Mickey Mouse' >>> name.replace( 'M', 'Z' ) 'Zickey Zouse' >>> name 'Mickey Mouse' >>>
2/23/18
# examples # D. Thiebaut line = "The quick red fox jumped over the lazy brown sleeping dog" line.split( " " ) # that's a space poem = """Chocolate Chocolate is the first luxury. It has so many things wrapped up in it: Deliciousness in the moment, childhood memories, and that grin-inducing feeling of getting a reward for being good. --Mariska Hargitay"""
Working with Text Files
Here's the text to store in the text file called chocolate.txt. You can use Notepad or TextEdit to do that. Make sure you use ".txt" as the extension, and select "plain text" or "plain ASCII" as the format.
Strength is the capacity to break a Hershey bar into four pieces with your bare hands - and then eat just one of the pieces. —Judith Viorst
And here's the program that reads this file
# readChocolateFile.py # D. Thiebaut # Opens a text file and displays it contents. # Note: you need to have a file called chocolate.txt # in the same directory/folder where you have saved # this program!!! @ def main(): # open file file = open( "chocolate.txt", "r" ) # read each line from file and display it for line in file: print( line ) # close the file file.close() main()
2/26/18
# readChocolateFile.py # D. Thiebaut # Opens a text file and displays it contents. # Note: you need to have a file called chocolate.txt # in the same directory/folder where you have saved # this program!!! def main(): # open file file = open( "chocolate.txt", "r" ) # read each line from file and display it for line in file: print( line.strip() ) # close the file file.close() main() # ---------------------------------------------------------------------- def singHappyBirthday( minion ): print( "Happy birthday to you" ) print( "Happy birthday to you" ) print( "Happy birthday, dear", minion ) print( "Happy birthday to you" ) print( ) def main(): for minion in [ "Dave", "Stuart", "Jerry", "Jorge" ]: singHappyBirthday( minion ) main() # ---------------------------------------------------------------------- # DaveEats.py # D. Thiebaut def DaveEats( fruit ): print( "Dave opens their mouth" ) print( "and eats the", fruit ) print() def main(): for fruit in [ "banana", "apple", "orange" ]: DaveEats( fruit ) main() # ---------------------------------------------------------------------- # printBarSayHello.py # D. Thiebaut def printBar(): print( 60 * '-' ) def sayHello(): print( ) print( "Hello, and welcome!" ) print( ) def main(): printBar() printBar() main() # ---------------------------------------------------------------------- # ---------------------------------------------------------------------- # ----------------------------------------------------------------------