Chapter 13: Python Flashcards
Declaration of variables
- No declaration necessary
- A comment should be used either way
#Number1: Type INTEGER #YourName: Type STRING
Assignment of constants
- identifier=value
* PI=3.14
Assignment of variables
•identifier=expressions
- A=34
- B=B+1
Arithmetic operations
- | - | * | / | ** | // | %
* Rules of precedence should be followed
Outputting information
- print(printlist)
* print(“Hello, ”,YourName,”Your number is: “,Number1)
Comments
This is a comment
Data types
- int
- float
- str
- bool
- datetime
Boolean expressions
- ==
- !=
- >
- <
- > =
- <=
- and | or | not
- in
Selection statements
if x<0: print(“Negative”) elif x=0: print(“Zero”) else: print(“Positive”)
Count-controlled loops
for x in range (5):
print(x)
Pre-condition loops
Answer=‘ ‘
while Answer != “Y”:
Answer=input(“Enter Y or N”)
Creating 1D arrays
•List1=[] List1.append(“Fred”) List1.append(“Jack”) List1.append(“Ali”) •List2=[0,0,0,0,0,0,0] •List3=[0 for i in range (100)] •List4=[“ “]*100
Accessing 1D arrays
- NList[24]=0
* AList[3]=“D”
Creating 2D arrays
•Board=[0 for i in range(7)]
for j in range(6)
•Board=[07]6
Accessing 2D arrays
Board [2][3]=0
String manipulation built-in functions
- ThisString[P]
- chr(i)
- ord(ch)
- len(s)
- s=s1+s2
Slicing
- ThisString[2:]: CDEFG
- ThisString[:2]: AB
- ThisString[-2:]: FG
- ThisString[:-2]: ABCDE
Truncating numbers
int(x)
String —> integer
int(s)
String —> float
float(x)
Random number generator
randint(1,6)
Date and time
from datetime import * SomeDate=date(2015,3,15)
Today=date.today
print(SomeDate)
print(Today)
SomeDate=SomeDate+TimeDelat(1)
Writing on a text file
FileHandle=open(“Text.txt”,”w”)
FileHandle.write(LineOfText)
FileHandle.close()
Reading from a text file
FileHandle=open(“Text.txt”,”r”)
LineOfText=FileHandle.readline()
FileHandle.close
Appending to a text file
FileHandle=open(“Text.txt”,”a”)
FileHandle.write(LineOfText)
FileHandle.close()
EoF marker
FileHandle=open(“Text.txt”,”r”) LineOfText=FileHandle.readline() while len(LineOfText)>0: LineOfText=FileHandle.readline() print(LineOfText) FileHandle.close()