how to draw shapes using inputs from the user using SimpleGraphics? - python

from SimpleGraphics import *
f = open("shape.txt","w")
print("Please provide the necessary information below.")
while (True):
s=input("please select one of following shapes (line, rect, elipse or quit): ")
if s=="line":
f.write(s+"\n")
y=float(input("please enter you Y value: "))
f.write(str(y)+"\n")
x=float(input("please enter you X value: "))
f.write(str(x)+"\n")
h=float(input("please enter the value for the height: "))
f.write(str(h)+"\n")
w=float(input("please enter the value for the width: "))
f.write(str(w)+"\n")
c=input("please enter the colour: ")
f.write=(c+"\n")
print(h)
if s=="quit":
break
f.close()

Related

How can I print the report without the first in the list

I'm trying to display the names except the 'name' and trying to get the average of age without 'age' on the list and lastly get the average of the grade without the 'Grade'.
I have a problem I'm trying to print the names of the list without the first row in the list(['Name', 'Age', 'Grade']) without pop or removing them from the list.
studentDB = [['Name', 'Age', 'Grade'], ['Con', 20, 90.2],
['Juan', 45, 70.2], ['Jed', 39, 100.0]]
while True:
for i in range(len(studentDB)):
print(i, studentDB[i])
print("\n********** Hackathon ***********")
CRUD = """1- Add
2- Delete
3- Edit
4- Print Report
----------------
Enter a number: """
choice = float(input(CRUD))
if (choice == 1):
Name = input("Please Enter your Name: ")
Age = int(input("Please Enter your Age: "))
Grade = float(input("Please Enter your Grade: "))
studentDB.append([Name, Age, Grade])
print(studentDB)
elif (choice == 2):
Del = int(input("Please Enter the row you want to delete: "))
studentDB.pop(Del)
elif (choice == 3):
Del1 = int(input("Please Enter the row you want to delete: "))
Name1 = input("Please Enter your Name: ")
Age1 = int(input("Please Enter your Age: "))
Grade1 = float(input("Please Enter your Grade: "))
studentDB.pop(Del1)
studentDB.insert(Del1,[Name1, Age1, Grade1])
print(studentDB)
elif (choice == 4):
#here is the problem
for s in range(1, len(studentDB)):
print("")
print(f"There are in the {s} student table. The people included in the list are.")
else:
print("Invalid input")
Here is the output that I wanted to do
This is the online compiler: https://www.programiz.com/python-programming/online-compiler/
There can be many ways to solve this. One could be to use starting index in range and use slice while calculating average of age or grades.
from statistics import mean
while True:
# Use the start index in range.
for i in range(len(studentDB)):
print(i, studentDB[i])
print("\n********** Hackathon ***********")
CRUD = """1- Add
2- Delete
3- Edit
4- Print Report
----------------
Enter a number: """
choice = float(input(CRUD))
if (choice == 1):
Name = input("Please Enter your Name: ")
Age = int(input("Please Enter your Age: "))
Grade = float(input("Please Enter your Grade: "))
studentDB.append([Name, Age, Grade])
print(studentDB)
elif (choice == 2):
Del = int(input("Please Enter the row you want to delete: "))
studentDB.pop(Del)
elif (choice == 3):
Del1 = int(input("Please Enter the row you want to delete: "))
Name1 = input("Please Enter your Name: ")
Age1 = int(input("Please Enter your Age: "))
Grade1 = float(input("Please Enter your Grade: "))
studentDB.pop(Del1)
studentDB.insert(Del1,[Name1, Age1, Grade1])
print(studentDB)
elif (choice == 4):
#here is the problem
# Use slice to get the row from index 1 afterwards
print(f"There are in the {len(studentDB) - 1} records in the student table. The people included in the list are.")
print(",".join([student[0] for student in studentDB[1:]]))
average_age = mean([row[1] for row in studentDB[1:]])
average_grades = mean([row[2] for row in studentDB[1:]])
# Print average age and grades here
else:
print("Invalid input")```

error! minus isn't supported? from input weight [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 3 years ago.
I am trying to do a simple calculation but once the user inputs the weight it wont print out the remaining weight left. comes with the error code
unsupported operand type(s) for -: 'str' and 'int'
here is my code. is there something i am missing?
def Massallowance():
person = input("Crew or Specialist? ")
if person== 'Crew':
definedMass = 100
weight = input("Please enter weight: ")
print("Allowance" + weight-definedMass)
elif person== 'Specialist':
definedMass = 150
weight = input("Please enter weight: ")
print("Allowance" + weight-definedMass)
You are trying to do minus operation between str and int
First convert input string to int and then do operation.
weight = int(input("Please enter weight: "))
Updated code will be like
def Massallowance():
person = input("Crew or Specialist? ")
if person== 'Crew':
definedMass = 100
weight = int(input("Please enter weight: "))
print("Allowance" + weight-definedMass)
elif person== 'Specialist':
definedMass = 150
weight = int(input("Please enter weight: "))
print("Allowance" + weight-definedMass)
input() gives you strings, you can't subtract a string from a number - that doesn't make sense. You should turn the input string into a number with int or float
def Massallowance():
person = input("Crew or Specialist? ")
if person== 'Crew':
definedMass = 100
weight = int(input("Please enter weight: "))
print("Allowance" + weight-definedMass)
elif person== 'Specialist':
definedMass = 150
weight = int(input("Please enter weight: "))
print("Allowance" + weight-definedMass)
The 'input' method takes a 'String' as an input. So whenever the user inputs a number it is directly converted to a 'string'. Since you cannot substact a string with an integer, you get the error. This should be a simple fix:
def Massallowance():
person = input("Crew or Specialist? ")
if person== 'Crew':
definedMass = 100
weight = int(input("Please enter weight: "))
print("Allowance" + weight-definedMass)
elif person== 'Specialist':
definedMass = 150
weight = int(input("Please enter weight: "))
print("Allowance" + weight-definedMass)

Python: Returning array values from a function

I'm trying to understand how to use functions properly. In this code, I want to return 2 arrays for pupil names and percentage scores. However I am unable to return the array variables from the first function.
I've tried using different ways of defining the arrays (with and without brackets, both globally and locally)
This is the relevant section of code for the program
#function to ask user to input name and score
def GetInput():
for counter in range(0,10):
names[counter] = input("Please enter the student's name: ")
valid = False
while valid == False:
percentages[counter] = int(input("Please enter the student's score %: "))
if percentages[counter] < 0 or percentages[counter] > 100:
print("Please enter a valid % [0-100]")
else:
valid = True
return names, percentages
name, mark = GetInput()
I'm expecting to be asked to enter the values for both arrays.
I'm instead getting:
Traceback (most recent call last):
File "H:/py/H/marks.py", line 35, in <module>
name, mark = GetInput()
File "H:/py/H/marks.py", line 7, in GetInput
names[counter] = input("Please enter the student's name: ")
NameError: global name 'names' is not defined
You need to use dictionary instead of list if your want to use key-value pairs. furthermore you need to return the values outside of for loop. You can try the following code.
Code:
def GetInput():
names = {} # Needs to declare your dict
percentages = {} # Needs to declare your dict
for counter in range(0, 3):
names[counter] = input("Please enter the student's name: ")
valid = False
while valid == False:
percentages[counter] = int(input("Please enter the student's score %: "))
if percentages[counter] < 0 or percentages[counter] > 100:
print("Please enter a valid % [0-100]")
else:
valid = True
return names, percentages # Return outside of for loop.
name, mark = GetInput()
print(name)
print(mark)
Output:
>>> python3 test.py
Please enter the student's name: bob
Please enter the student's score %: 20
Please enter the student's name: ann
Please enter the student's score %: 30
Please enter the student's name: joe
Please enter the student's score %: 40
{0: 'bob', 1: 'ann', 2: 'joe'}
{0: 20, 1: 30, 2: 40}
If you want to create a common dictionary which contains the students' name and percentages, you can try the following implementation:
Code:
def GetInput():
students = {}
for _ in range(0, 3):
student_name = input("Please enter the student's name: ")
valid = False
while not valid:
student_percentages = int(input("Please enter the student's score %: "))
if student_percentages < 0 or student_percentages > 100:
print("Please enter a valid % [0-100]")
continue
valid = True
students[student_name] = student_percentages
return students
students = GetInput()
print(students)
Output:
>>> python3 test.py
Please enter the student's name: ann
Please enter the student's score %: 20
Please enter the student's name: bob
Please enter the student's score %: 30
Please enter the student's name: joe
Please enter the student's score %: 40
{'ann': 20, 'bob': 30, 'joe': 40}
You forgot to set the names and percentages as empty dictionaries so you can use them. Also the "return" should be outside of the for loop.:
def GetInput():
names={}
percentages={}
for counter in range(0,10):
names[counter] = input("Please enter the student's name: ")
valid = False
while valid == False:
percentages[counter] = int(input("Please enter the student's score %: "))
if percentages[counter] < 0 or percentages[counter] > 100:
print("Please enter a valid % [0-100]")
else:
valid = True
return names, percentages
name, mark = GetInput()
Probably this may help to you.
#function to ask user to input name and score
def GetInput():
names=[]
percentages=[]
for counter in range(0,3):
names.append(input("Please enter the student's name: "))
valid = False
while valid == False:
percentages.append(int(input("Please enter the student's score %: ")))
if percentages[counter] < 0 or percentages[counter] > 100:
print("Please enter a valid % [0-100]")
else:
valid = True
return names, percentages
name, mark = GetInput()
print(name,mark)
This is implemented by using two lists. (Not suggested for keeping records. Better use dictionary as done below.)
counter = 10
def GetInput():
names = []
percentage = []
for i in range(counter):
names.append(input("Please enter the student's name: "))
valid = False
while not(valid):
try:
percent = int(input("Please enter the student's score between 0 and 100%: "))
if percent >= 0 and percent <= 100:
percentage.append(percent)
valid = True
break
else:
continue
except ValueError:
print("\nEnter valid marks!!!")
continue
valid = True
return names, percentage
students, marks = GetInput()
The following is implemented by using dictionary, and for this, you do not need the variable counter.
def GetInput():
records = dict()
for i in range(counter):
name = input("Please enter the student's name: ")
valid = False
while not(valid):
try:
percent = int(input("Please enter the student's score between 0 and 100%: "))
if percent >= 0 and percent <= 100:
#percentage.append(percent)
valid = True
break
else:
continue
except ValueError:
print("\nEnter valid marks!!!")
continue
valid = True
records[name] = percent
return records
record = GetInput()
Change the value of counter to how many records you want. This takes care of marks to be between 0 and 100 (included) and to be integer. Its better if you implement it with dictionary.
Wouldn't it be better to have name and percentage in one dict?
#function to ask user to input name and score
def GetInput():
name_percentage = {}
for counter in range(0,10):
name = input("Please enter the student's name: ")
valid = False
while not valid:
percentage = int(input("Please enter the student's score %: "))
if percentage < 0 or percentage > 100:
print("Please enter a valid % [0-100]")
else:
valid = True
name_percentage[name] = percentage
return name_percentage
name_percentage = GetInput()
print(name_percentage)

Passing 'ValueError' & 'continue' in a function and call it

I am trying to check user inputs to ensure that:
1) It is a floating number
2) Floating number is not negative
I am trying to put above 2 checks into a function and call it after user has input into a variable.
However, I cant seem to put 'ValueError' & 'continue' in a function that I can call. Is this possible?
I have tried below code, but it repeats from the top when I key in 't' for salCredit, or any of the next few variables. The code will work if I were to repeat 'ValueError' & 'continue' for every variable. I'm just wondering if there is a shorter way of doing do?
def interestCalculator():
#User inputs required for calculation of interest earned.
while True:
try:
mul_AccBal = float(input("Enter your Account Balance: "))
#checkInputError(accBal)
salCredit = float(input("Enter your Salary: "))
#checkInputError(salCredit)
creditCard = float(input("Credit Card Spend (S$): "))
#checkInputError(creditCard)
except ValueError:
print("Please enter a valid number.")
continue
def checkInputError(userInput):
if userInput < 0:
print("Please enter a positive number.")
interestCalculator()
Expected results:
Scenario 1: if user inputs 't'
Enter your Account Balance: 5000
Enter your Salary: t
Please enter a valid number.
Enter your Salary: 500
Scenario 2: if user inputs negative number
Enter your Account Balance: 5000
Enter your Salary: -50
Please enter a valid number.
Enter your Salary: 500
Current results:
Scenario 1: if user inputs 't'
Enter your Account Balance: 5000
Enter your Salary: t
Please enter a valid number.
Enter your Account Balance:
Scenario 2: if user inputs negative number
Enter your Account Balance: 5000
Enter your Salary: -50
Please enter a positive number.
Credit Card Spend (S$):
You could create a function that continues prompting for input until a valid float is input
def get_float_input(prompt):
while True:
try:
user_input = float(input(prompt))
if user_input < 0:
print("Please enter a positive number.")
continue # start the while loop again
return user_input # return will break out of the while loop
except ValueError:
print("Please enter a valid number.")
mul_AccBal = get_float_input("Enter your Account Balance: ")
salCredit = get_float_input("Enter your Salary: ")
creditCard = get_float_input("Credit Card Spend (S$): ")
Try this:
def interestCalculator():
#User inputs required for calculation of interest earned.
while True:
invalid = True
while invalid:
try:
mul_AccBal = float(input("Enter your Account Balance: "))
invalid=checkInputError(salCredit)
except ValueError:
print("Please enter a valid number.")
continue
invalid = True
while invalid:
try:
salCredit = float(input("Enter your Salary: "))
invalid=checkInputError(salCredit)
except ValueError:
print("Please enter a valid number.")
continue
invalid = True
while invalid:
try:
creditCard = float(input("Credit Card Spend (S$): "))
invalid=checkInputError(salCredit)
except ValueError:
print("Please enter a valid number.")
continue
def checkInputError(userInput):
if userInput < 0:
print("Please enter a positive number.")
return True
return False
interestCalculator()
you need to break you while loop if all the input is successful (also note that the continue at the end of the while loop is unnecessary). and if you want to have a validation for every number separately, you could do something like this:
def get_float(message, retry_message="Please enter a valid number."):
while True:
try:
ret = float(input(message))
if ret >= 0:
return ret
else:
print(retry_message)
except ValueError:
print(retry_message)
def interestCalculator():
mul_AccBal = get_float("Enter your Account Balance: ")
salCredit = get_float("Enter your Salary: ")
creditCard = get_float("Credit Card Spend (S$): ")

How to make while True loop running in python?

I want to write a program to have the (name, age, height) where name is string, age and height are numbers for at least 2 users. So I have tried to use a while True loop but it breaks after just one entry (name, age, height). This is because number of items in the list is tree. How could I make a tuple so that the number of items would count as one for all the name, age and height? or is there any easy way?
data=[]
while True:
name = raw_input("Please enter your name: ")
age = int(raw_input("Please enter your age: "))
height = int(raw_input("Please enter your height: "))
data.append(name)
data.append(age)
data.append(height)
if len(data) <2:
print "you need to enter at least 2 users"
else:
break
print data
Try
data=[]
while len(data) < 2:
name = raw_input("Please enter your name: ")
age = int(raw_input("Please enter your age: "))
height = int(raw_input("Please enter your height: "))
data.append({
'name': name,
'age': age,
'height': height,
})
print data
It is because you put name instead of dict of user information (name, age, height).
You can use range
Ex:
data=[]
for _ in range(2):
name = raw_input("Please enter your name: ")
age = int(raw_input("Please enter your age: "))
height = int(raw_input("Please enter your height: "))
data.append((name, age, height))
print(data)
Or: using a while loop.
data=[]
while True:
name = raw_input("Please enter your name: ")
age = int(raw_input("Please enter your age: "))
height = int(raw_input("Please enter your height: "))
data.append((name, age, height))
if len(data) == 2:
break
print(data)

Categories

Resources