Question

In: Computer Science

I wrote this code and it produces a typeError, so please can you fix it? import...

I wrote this code and it produces a typeError, so please can you fix it?

import random

def first_to_a_word():

print("###### First to a Word ######")
print("Instructions:")
print("You will take turns choosing letters one at a time until a word is formed.")
print("After each letter is chosen you will have a chance to confirm whether or not a word has been formed.")
print("When a word is formed, the player who played the last letter wins!")
print("One of you has been chosen at random to initiate the game.")
print()
print("Note: Words must be longer than a single letter!")
print()

  
#inputs / randomNumGen
player1 = input("Enter player 1's name: ")
player2 = input("Enter player 2's name: ")
random_number = random.randint(0, 1)
  
#output function
def output_func(player1, player2, random_number):
if random_number == 0:
word = input(player1, 'please enter a character: ')
print(player1, 'input:', word)
else:
word = input(player2, 'please enter a character: ')
print(player2, 'input:', word)
  
return word
  
#initial variables
word_confirm = ''
counter = 0
word_array = []
  
#character input loop
while word_confirm != 'yes':
  
#function call
word = output_func(player1, player2, random_number)
  
#append
word_array.append(word)
  
#alternate players turns
if random_number == 0:
random_number = 1
else:
random_number = 0
  
#check for exit after >=3 letters formed
if counter >= 2:
print('You have formed the letters:') #three letters
word_confirm = input('Has the word been formed? (type "yes" or "no"): ')
word_confirm = word_confirm.lower()
  
counter += 1
  
complete_word = ''
i = 0
while i < len(word_array):
  
complete_word += word_array[i]
i += 1
  
if random_number == 1:
print(player1, 'Wins!')
print('The word was:', complete_word)
else:
print(player2, 'Wins!')
print('The word was:', complete_word)
  
  

first_to_a_word()

Solutions

Expert Solution

Hi,

Hope you are doing fine. You have a super clean job with the code. However, there was only one error in output_func() which has been corrected. Also I have slighly modifies the sequence of program as according to the original code, the instructions are printed after finishing the game. I have made sure that there are printed before taking the player names as input. Coming to the error, after the compilation of the given code, you'll see an error something like this:

Explanation:

The error is because the predefined function input() considers player1 as an additional parameter. Unlike print() which will append the name of player prior to the statement in quotes, input() will consider this as a parameter and will raise a TypeError. In order to fix this replace ',' with a concatenation operator '+'. This will clearly indicate input() that value at player1 must be concatenated to the next statement.

Fix:

Corrected code:

import random

def first_to_a_word():

print("###### First to a Word ######")
print("Instructions:")
print("You will take turns choosing letters one at a time until a word is formed.")
print("After each letter is chosen you will have a chance to confirm whether or not a word has been formed.")
print("When a word is formed, the player who played the last letter wins!")
print("One of you has been chosen at random to initiate the game.")
print()
print("Note: Words must be longer than a single letter!")
print()

#printing game instructions
first_to_a_word()
print()

#inputs / randomNumGen
player1 = input("Enter player 1's name: ")
player2 = input("Enter player 2's name: ")
random_number = random.randint(0, 1)
  
#output function
def output_func(player1, player2, random_number):
if random_number == 0:
word = input(player1+ ' please enter a character: ')
print(player1, 'input:', word)
else:
word = input(player2+ ' please enter a character: ')
print(player2, 'input:', word)
  
return word
  
#initial variables
word_confirm = ''
counter = 0
word_array = []


#character input loop
while word_confirm != 'yes':
  
#function call
word = output_func(player1, player2, random_number)
  
#append
word_array.append(word)
  
#alternate players turns
if random_number == 0:
random_number = 1
else:
random_number = 0
  
#check for exit after >=3 letters formed
if counter >= 2:
print('You have formed the letters:') #three letters
word_confirm = input('Has the word been formed? (type "yes" or "no"): ')
word_confirm = word_confirm.lower()
  
counter += 1

complete_word = ''
i = 0
while i < len(word_array):
complete_word += word_array[i]
i += 1

if random_number == 1:
print(player1, 'Wins!')
print('The word was:', complete_word)
else:
print(player2, 'Wins!')
print('The word was:', complete_word)
  
Executable code snippet from jupyter notebook:

Output:


Related Solutions

Can someone fix this code so that it can count comparison and exchange? import java.util.Arrays; class...
Can someone fix this code so that it can count comparison and exchange? import java.util.Arrays; class Main { static int comparisons; static int exchanges; // Recursive function to perform insertion sort on sub-array arr[i..n] public static void insertionSort(int[] arr, int i, int n) { int value = arr[i]; int j = i; // Find index j within the sorted subset arr[0..i-1] // where element arr[i] belongs while (j > 0 && arr[j - 1] > value) { arr[j] = arr[j...
Can you please rewrite this Java code so it can be better understood. import java.util.HashMap; import...
Can you please rewrite this Java code so it can be better understood. import java.util.HashMap; import java.util.Scanner; import java.util.Map.Entry; public class Shopping_cart {       static Scanner s= new Scanner (System.in);    //   declare hashmap in which key is dates as per mentioned and Values class as value which consists all the record of cases    static HashMap<String,Item> map= new HashMap<>();    public static void main(String[] args) {        // TODO Auto-generated method stub        getupdates();    }...
Can you fix the errors in this code? package demo; /** * * */ import java.util.Scanner;...
Can you fix the errors in this code? package demo; /** * * */ import java.util.Scanner; public class Booolean0p {        public class BooleanOp {            public static void main(String[] args) {                int a = 0, b = 0 , c = 0;                Scanner kbd = new Scanner(System.in);                System.out.print("Input the first number: ");                a = kbd.nextInt();                System.out.print("Input...
Can you fix the errors in this code? import java.util.Scanner; public class Errors6 {    public...
Can you fix the errors in this code? import java.util.Scanner; public class Errors6 {    public static void main(String[] args) {        System.out.println("This program will ask the user for three sets of two numbers and will calculate the average of each set.");        Scanner input = new Scanner(System.in);        int n1, n2;        System.out.print("Please enter the first number: ");        n1 = input.nextInt();        System.out.print("Please enter the second number: ");        n2 =...
Please fix all of the errors in this Python Code. import math """ A collection of...
Please fix all of the errors in this Python Code. import math """ A collection of methods for dealing with triangles specified by the length of three sides (a, b, c) If the sides cannot form a triangle,then return None for the value """ ## @TODO - add the errlog method and use wolf fencing to identify the errors in this code def validate_triangle(sides): """ This method should return True if and only if the sides form a valid triangle...
Please I can get a flowchart and a pseudocode for this java code. Thank you //import...
Please I can get a flowchart and a pseudocode for this java code. Thank you //import the required classes import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class BirthdayReminder {       public static void main(String[] args) throws IOException {        // declare the required variables String sName = null; String names[] = new String[10]; String birthDates[] = new String[10]; int count = 0; boolean flag = false; // to read values from the console BufferedReader dataIn = new BufferedReader(new...
Python 3 Fix the code so i can make the window larger or smaller and the...
Python 3 Fix the code so i can make the window larger or smaller and the fields adjusts everytime according to the window size import tkinter as tk from tkcalendar import DateEntry from openpyxl import load_workbook window = tk.Tk() window.title("daily logs") # window.resizable(0,0) # labels tk.Label(window, text="Bar code").grid(row=0, sticky="W", pady=20, padx=20) tk.Label(window, text="Products failed").grid(row=1, sticky="W", pady=20, padx=20) tk.Label(window, text="Money Lost").grid(row=2, sticky="W", pady=20, padx=20) tk.Label(window, text="sold by").grid(row=3, sticky="W", pady=20, padx=20) tk.Label(window, text="Failed date").grid(row=4, sticky="W", pady=20, padx=20) # entries barcode = tk.Entry(window)...
Please can I get a flowchart and pseudocode for this java code. Thank you. TestScore.java import...
Please can I get a flowchart and pseudocode for this java code. Thank you. TestScore.java import java.util.Scanner; ;//import Scanner to take input from user public class TestScore {    @SuppressWarnings("resource")    public static void main(String[] args) throws ScoreException {//main method may throw Score exception        int [] arr = new int [5]; //creating an integer array for student id        arr[0] = 20025; //assigning id for each student        arr[1] = 20026;        arr[2] = 20027;...
Please can I kindly get a flowchart for this java code. Thank you. //import the required...
Please can I kindly get a flowchart for this java code. Thank you. //import the required classes import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class BirthdayReminder {       public static void main(String[] args) throws IOException {        // declare the required variables String sName = null; String names[] = new String[10]; String birthDates[] = new String[10]; int count = 0; boolean flag = false; // to read values from the console BufferedReader dataIn = new BufferedReader(new InputStreamReader( System.in));...
Python 3 Fix the code so i can make the window larger and the fields increase...
Python 3 Fix the code so i can make the window larger and the fields increase size import tkinter as tk from tkcalendar import DateEntry from openpyxl import load_workbook window = tk.Tk() window.title("daily logs") # window.resizable(0,0) # labels tk.Label(window, text="Bar code").grid(row=0, sticky="W", pady=20, padx=20) tk.Label(window, text="Products failed").grid(row=1, sticky="W", pady=20, padx=20) tk.Label(window, text="Money Lost").grid(row=2, sticky="W", pady=20, padx=20) tk.Label(window, text="sold by").grid(row=3, sticky="W", pady=20, padx=20) tk.Label(window, text="Failed date").grid(row=4, sticky="W", pady=20, padx=20) # entries barcode = tk.Entry(window) product = tk.Entry(window) money = tk.Entry(window) #...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT