Welcome to BleepingComputer, a free community where people like yourself come together to discuss and learn how to use their computers. Using the site is easy and fun. As a guest, you can browse and view the various discussions in the forums, but can not create a new topic or reply to an existing one unless you are logged in. Other benefits of registering an account are subscribing to topics and forums, creating a blog, and having no ads shown anywhere on the site.

# First Python Project

20 replies to this topic

### #1 thelittleduck

thelittleduck

• Members
• 920 posts
• ONLINE
•
• Gender:Male
• Location:Pond
• Local time:07:30 PM

Posted 15 February 2016 - 12:33 PM

I'm attempting the first project from a book I'm trying to learn Python from.

The task was to write a function called 'collatz', with a parameter named 'number'.   if number is even, then collatz should print number // 2 and return this value.

If odd then collatz should print and return 3 * number + 1.

Then the task was to write a program that lets the user input an integer, so that collatz keeps getting called with the entered argument, until the return value is 1.

I know I've printed in the loop, rather than the function, but other than that, does it seem ok?

# The Collatz Sequence

def collatz(number):
if number % 2 == 0:
return (number // 2)
elif number % 2 == 1:
return (3 * number + 1)

ans = ''

while ans != 1:
print('Enter an integer')
r = int(input())
ans = collatz®
print(ans)

### #2 thelittleduck

thelittleduck
• Topic Starter

• Members
• 920 posts
• ONLINE
•
• Gender:Male
• Location:Pond
• Local time:07:30 PM

Posted 16 February 2016 - 03:48 AM

There was a bit more to the task.  Use Try and Except to check that an integer is being entered.  Changed variable r to o as was appearing strange when posted.

# The Collatz Sequence

def collatz(number):
if number % 2 == 0:
return (number // 2)
elif number % 2 == 1:
return (3 * number + 1)

ans = ''

while ans != 1:
print('Enter an integer')
try:
o = int(input())
except ValueError:
print('That is not an integer, try again!')
continue

ans = collatz(o)
print(ans)

### #3 JohnnyJammer

JohnnyJammer

• Members
• 1,117 posts
• OFFLINE
•
• Gender:Male
• Location:QLD Australia
• Local time:04:30 AM

Posted 16 February 2016 - 07:46 PM

ans = "" not ans = "

### #4 thelittleduck

thelittleduck
• Topic Starter

• Members
• 920 posts
• ONLINE
•
• Gender:Male
• Location:Pond
• Local time:07:30 PM

Posted 17 February 2016 - 02:39 AM

ans = "" not ans = "

That's two single quotes.  The book I'm learning from says to use single quotes.  Thanks for the reply.

### #5 thelittleduck

thelittleduck
• Topic Starter

• Members
• 920 posts
• ONLINE
•
• Gender:Male
• Location:Pond
• Local time:07:30 PM

Posted 14 March 2016 - 07:12 AM

On to project 2:  Write a function that takes a list value as an argument, and returns a string with all the items separated by a comma and a space, with and inserted before the last item.  The function should be able to work with any list value passed to it.

Is this OK?

# Comma Code Project

def commaCode(meow):
global biggerCats
for i in range(len(meow)):
if i < len(meow) - 1:
biggerCats = biggerCats + (meow[i] + ', ')
elif i == len(meow) - 1:
biggerCats = biggerCats + ('and ' + meow[len(meow) - 1])
else:
return biggerCats

biggerCats = ''

cats = []

while True:
print('Enter name of cat ' + str(len(cats) + 1) + ', or enter nothing to finish.')
name = input()
if name == '':
break
cats.append(name)

commaCode(cats)

print(biggerCats)

### #6 Struppigel

Struppigel

Karsten Hahn, G DATA Malware Analyst

• Malware Response Team
• 231 posts
• OFFLINE
•
• Gender:Male
• Local time:08:30 PM

Posted 27 March 2016 - 07:54 AM

Don't make biggerCats global. Have you ever checked what happens if you use your commaCode function twice in your script? It will append the string of the second list to the string for the first list, which is not a behaviour you would expect or want.

### #7 thelittleduck

thelittleduck
• Topic Starter

• Members
• 920 posts
• ONLINE
•
• Gender:Male
• Location:Pond
• Local time:07:30 PM

Posted 27 March 2016 - 09:15 AM

Thanks for the reply.  I am aware of the basic differences between the global scope and local scopes, but the task seemed to indicate the function only had to work once.

Good advice for the future though.  Thanks.

### #8 thelittleduck

thelittleduck
• Topic Starter

• Members
• 920 posts
• ONLINE
•
• Gender:Male
• Location:Pond
• Local time:07:30 PM

Posted 30 March 2016 - 11:02 PM

I've done it without the global variable in the function.

# Comma Code Project

def commaCode(meow):
biggerCats = ''
for i in range(len(meow)):
if i < (len(meow) - 1):
biggerCats = biggerCats + (meow[i] + ', ')
elif i == len(meow) - 1:
biggerCats = biggerCats + ('and ' + meow[len(meow) - 1])
return biggerCats

cats = []

while True:
print('Enter name of cat ' + str(len(cats) + 1) + ', or enter nothing to finish.')
name = input()
if name == '':
break
cats.append(name)

Edited by thelittleduck, 30 March 2016 - 11:09 PM.

### #9 thelittleduck

thelittleduck
• Topic Starter

• Members
• 920 posts
• ONLINE
•
• Gender:Male
• Location:Pond
• Local time:07:30 PM

Posted 31 March 2016 - 07:50 AM

The task this time was to make a given nested list, print as a ceratin image - from left 90 degrees clockwise.

Is this OK?

# Character Picture Grid

grid = [['.', '.', '.', '.', '.', '.'],
['.', '0', '0', '.', '.', '.'],
['0', '0', '0', '0', '.', '.'],
['0', '0', '0', '0', '0', '.'],
['.', '0', '0', '0', '0', '0'],
['0', '0', '0', '0', '0', '.'],
['0', '0', '0', '0', '.', '.'],
['.', '0', '0', '.', '.', '.'],
['.', '.', '.', '.', '.', '.']]

for x in range(6):
for y in range(9):
if y != 8:
print(grid[y][x], end ='')
else:
print(grid[y][x])

### #10 thelittleduck

thelittleduck
• Topic Starter

• Members
• 920 posts
• ONLINE
•
• Gender:Male
• Location:Pond
• Local time:07:30 PM

Posted 31 March 2016 - 02:33 PM

The next project was to write a function that adds a list of found items, to a dictionary of already owned items.  Also to write a function that calculates the total objects owned.

Does this seem OK?

# List to Dictionary Function for Fantasy Game Inventory

playerHas = {'Gold': 82, 'Food': 5, 'Drink': 4, 'Magic': 45, 'Sword': 2}

inventory.setdefault(i, 0)
inventory[i] = inventory[i] + 1

def displayInventory(inventory):
print('Inventory:')
itemTotal = 0
for k, v in inventory.items():
print(str(v) + ' ' + k)
itemTotal = itemTotal + v
print('Total number of items: ' + str(itemTotal))

dragonLoot = ['Gold', 'Food', 'Gold', 'Magic', 'Axe', 'Gold', 'Magic', 'Drink', 'Gold', 'Sword']

displayInventory(playerHas)

### #11 thelittleduck

thelittleduck
• Topic Starter

• Members
• 920 posts
• ONLINE
•
• Gender:Male
• Location:Pond
• Local time:07:30 PM

Posted 19 April 2016 - 12:35 PM

This time the project was to write  a function that takes a list of strings, and displays it in a well-organized table with each column right-justified.

It said to assume the inner lists will contain the same number of strings.  Does this seem acceptable?

# Table Printer

stuff = [['Vodka', 'Whiskey', 'Cider', 'Beer', 'Wine'],
['Nuts', 'Cheese', 'Biscuits', 'Crisps', 'Dip'],
['DVD', 'Book', 'TV', 'Cinema', 'Match']]

def tablePrinter(tableData):
colWidths = [0] * len(tableData)
for i in range(len(tableData)):
for x in tableData[i]:
if len(x) > colWidths[i]:
colWidths[i] = len(x)

glue = []
size = 0
for y in range(len(tableData[size])):
for z in range(len(tableData)):
glue.append(tableData[z][y])
continue
for a in range(len(tableData) - 1):
print(glue[a].rjust(colWidths[a]) + ' ', end = '')
continue
print(glue[len(tableData) - 1].rjust(colWidths[len(tableData) -1]))
glue = []
size = size + 1

tablePrinter(stuff)

Edited by thelittleduck, 19 April 2016 - 01:18 PM.

### #12 thelittleduck

thelittleduck
• Topic Starter

• Members
• 920 posts
• ONLINE
•
• Gender:Male
• Location:Pond
• Local time:07:30 PM

Posted 23 April 2016 - 05:43 AM

This time the task was to write a function that uses regular expressions, to check that a password is strong.

The authors definition of a strong password - at least 8 characters long, with both uppercase and lowercase letters, and at least one digit.  It said several regexes would need to be used.

Does this seem OK?

import re

checkRegexLen = re.compile(r'(.){8,}')
checkRegexUpper = re.compile(r'[A-Z]+')
checkRegexLower = re.compile(r'[a-z]+')
checkRegexDigit = re.compile(r'\d+')

def strongPC(check):
if checkRegexLen.search(check) == None:
return 'Password must be at least 8 characters.'
if checkRegexUpper.search(check) == None:
return 'Password must contain at least one uppercase letter.'
if checkRegexLower.search(check) == None:
return 'Password must contain at least one lowercase letter.'
if checkRegexDigit.search(check) == None:
return 'Password must contain at least one digit.'

while True:
if not ans == 'Password accepted.':
print(ans)
continue
print(ans)
break

### #13 thelittleduck

thelittleduck
• Topic Starter

• Members
• 920 posts
• ONLINE
•
• Gender:Male
• Location:Pond
• Local time:07:30 PM

Posted 03 March 2017 - 08:45 PM

Thought I would try to convert positive integers from decimal to octal.

This is what I ended with:

# decimal to octal converter

print('What number do you want to convert? ')

while True:
decimal = input()
if decimal.isdecimal():
break
print('Invalid input')
print()
continue

swap = int(decimal)
trail = 5

while not trail == 0:
trail = swap // 8
swap = trail
continue

print()

for i in range(l, -1, -1):

Edited by thelittleduck, 03 March 2017 - 08:48 PM.

### #14 thelittleduck

thelittleduck
• Topic Starter

• Members
• 920 posts
• ONLINE
•
• Gender:Male
• Location:Pond
• Local time:07:30 PM

Posted 06 May 2017 - 11:30 AM

I tried doing a tic-tac-toe game. Here's what I ended up with.

# Tic Tac Toe

import random, sys, time

def showPoss():
print('Keys')
print()
print('t-l t-c t-r')
print()
print('m-l m-c m-r')
print()
print('b-l b-c b-r')
print()

def humanWins():
print()
print('Congratulations!  You have won!')
time.sleep(3)
sys.exit()

def computerWins():
print()
print('The computer has won')
time.sleep(3)
sys.exit()

def checkWin(spacing, play):
if (spacing['t-l'] + spacing['t-c'] + spacing['t-r'] == 'XXX' or
spacing['m-l'] + spacing['m-c'] + spacing['m-r'] == 'XXX' or
spacing['b-l'] + spacing['b-c'] + spacing['b-r'] == 'XXX' or
spacing['t-l'] + spacing['m-l'] + spacing['b-l'] == 'XXX' or
spacing['t-c'] + spacing['m-c'] + spacing['b-c'] == 'XXX' or
spacing['t-r'] + spacing['m-r'] + spacing['b-r'] == 'XXX' or
spacing['t-l'] + spacing['m-c'] + spacing['b-r'] == 'XXX' or
spacing['b-l'] + spacing['m-c'] + spacing['t-r'] == 'XXX'):
if play == 1:
humanWins()
else:
computerWins()
if (spacing['t-l'] + spacing['t-c'] + spacing['t-r'] == 'OOO' or
spacing['m-l'] + spacing['m-c'] + spacing['m-r'] == 'OOO' or
spacing['b-l'] + spacing['b-c'] + spacing['b-r'] == 'OOO' or
spacing['t-l'] + spacing['m-l'] + spacing['b-l'] == 'OOO' or
spacing['t-c'] + spacing['m-c'] + spacing['b-c'] == 'OOO' or
spacing['t-r'] + spacing['m-r'] + spacing['b-r'] == 'OOO' or
spacing['t-l'] + spacing['m-c'] + spacing['b-r'] == 'OOO' or
spacing['b-l'] + spacing['m-c'] + spacing['t-r'] == 'OOO'):
if play == 1:
computerWins()
else:
humanWins()

def compMove2(goes, spa, a):
if a < 3:
if spa['m-c'] == ' ':
spa['m-c'] = goes
else:
spa['t-l'] = goes
return
if a == 3:
if spa['t-l'] == ' ':
spa['t-l'] = goes
elif spa['b-l'] == ' ':
spa['b-l'] = goes
else:
spa['b-r'] = goes
return
if spa['b-l'] == ' ':
spa['b-l'] = goes
elif spa['b-r'] == ' ':
spa['b-r'] = goes
else:
spa['t-r'] = goes

def compMove(go, spac, compsGo):
while True:
move = random.randint(0, 8)
if not spac[compsGo[move]] == ' ':
continue
spac[compsGo[move]] = go
return

def checkMove(moves, space, compsGo):
again = 0
for i in range(9):
if not compsGo[i] == moves:
again += 1
if again == 9:
return 'takens'

if not space[moves] == ' ':
return 'taken'

def showBoard(space, playing):
print('   |   |    ')
print(' ' + space['t-l'] + ' | ' + space['t-c'] + ' | ' + space['t-r'])
print('___|___|___')
print('   |   |    ')
print(' ' + space['m-l'] + ' | ' + space['m-c'] + ' | ' + space['m-r'])
print('   |   |    ')
print(u'̅̅̅|̅̅̅|̅̅̅')
print(' ' + space['b-l'] + ' | ' + space['b-c'] + ' | ' + space['b-r'])
print('   |   |    ')
time.sleep(0.7)

checkWin(space, playing)

spaces = {'t-l': ' ', 't-c': ' ', 't-r': ' ',
'm-l': ' ', 'm-c': ' ', 'm-r': ' ',
'b-l': ' ', 'b-c': ' ', 'b-r': ' '}

compGo = ['t-l', 't-c', 't-r',
'm-l', 'm-c', 'm-r',
'b-l', 'b-c', 'b-r']

while True:
print()
print('Choose level 1-2 (2 is hardest)')
print()
level = input()
if level.isdecimal():
if int(level) < 1 or int(level) > 2:
print('Out of range')
continue
else:
level = int(level)
break
else:

while True:
print('Enter 1 to be X or 2 to be O (X goes first)')
print()
choice = input()
if choice == '1':
turn, player, cg = 'X', 1, 'O'
break
if choice == '2':
turn, player, cg = 'O', 2, 'X'
break
print()

showPoss()

for i in range(1, 10):
print()
if (player == 1 and (i % 2 == 1) or player == 2 and (i % 2 == 0)):
while True:
print()
move = input()
isTaken = checkMove(move, spaces, compGo)
if isTaken == 'takens':
print('Invalid move')
print()
continue
if isTaken == 'taken':
print()
continue
if player == 1:
spaces[move] = 'X'
else:
spaces[move] = 'O'
showBoard(spaces, player)
break
if (player == 1 and(i % 2 == 0) or player == 2 and (i % 2 == 1)):
if level == 1:
compMove(cg, spaces, compGo)
if level == 2 and i > 4:
compMove(cg, spaces, compGo)
if level == 2 and i < 5:
compMove2(cg, spaces, i)
showBoard(spaces, player)

print()
print('It\'s a draw!')
time.sleep(3)

### #15 KingDavidlll

KingDavidlll

• Members
• 297 posts
• OFFLINE
•
• Gender:Male
• Local time:04:30 AM

Posted 29 May 2017 - 06:55 AM

I'd recommend putting this on github.  It makes it easier to categorise and share your projects and others can give you feedback!

#### 0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users